From 6f928622baa04a919369b9e4e12b74a39e87f499 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Sat, 4 Jan 2025 04:07:23 -0800 Subject: [PATCH] Push new bundles for platform testing. --- global.min.js | 97 ++++++++++++++++++++++++----------------------- global.min.js.map | 4 +- 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/global.min.js b/global.min.js index 9d4062c..52be84e 100644 --- a/global.min.js +++ b/global.min.js @@ -3105,6 +3105,7 @@ var init_powgpu = __esm({ static #shader = ` struct UBO { blockhash: array, 2>, + random: u32, threshold: u32 }; @group(0) @binding(0) var ubo: UBO; @@ -3199,23 +3200,24 @@ var init_powgpu = __esm({ /** * Main compute function - * - * 8-byte work is split into two 4-byte u32 - * First 4 bytes will be iterated by shader - * Last 4 bytes are defined by index of each thread + * 8-byte work is split into two 4-byte u32. Low 4 bytes are random u32 from + * UBO. High 4 bytes are the random value XOR'd with index of each thread. */ @compute @workgroup_size(256) fn main( @builtin(workgroup_id) workgroup_id: vec3, @builtin(local_invocation_id) local_id: vec3 ) { + if (atomicLoad(&work.found) != 0u) { + return; + } var id: u32 = ((workgroup_id.x & 0xff) << 24) | - ((workgroup_id.y & 0xff) << 16) | - ((workgroup_id.z & 0xff) << 8) | - (local_id.x & 0xff); + ((workgroup_id.y & 0xff) << 16) | + ((workgroup_id.z & 0xff) << 8) | + (local_id.x & 0xff); var m: array; - m[0u] = id; - m[1u] = id; + m[0u] = ubo.random; + m[1u] = id ^ ubo.random; m[2u] = ubo.blockhash[0u].x; m[3u] = ubo.blockhash[0u].y; m[4u] = ubo.blockhash[0u].z; @@ -3225,15 +3227,14 @@ var init_powgpu = __esm({ m[8u] = ubo.blockhash[1u].z; m[9u] = ubo.blockhash[1u].w; - /** - * Compression buffer, intialized to 2 instances of the initialization vector + * Compression buffer intialized to 2 instances of initialization vector * The following values have been modified from the BLAKE2B_IV: * OUTLEN is constant 8 bytes * v[0u] ^= 0x01010000u ^ uint(OUTLEN); * INLEN is constant 40 bytes: work value (8) + block hash (32) * v[24u] ^= uint(INLEN); - * It's always the "last" compression at this INLEN + * It is always the "last" compression at this INLEN * v[28u] = ~v[28u]; * v[29u] = ~v[29u]; */ @@ -3249,40 +3250,38 @@ var init_powgpu = __esm({ ); /** - * Iterate and hash until nonce found + * Twelve rounds of mixing as part of compression step + */ + for (var i: u32 = 0u; i < 12u; i = i + 1u) { + G(&v, &m, 0u, 8u, 16u, 24u, SIGMA82[i * 16u + 0u], SIGMA82[i * 16u + 1u]); + G(&v, &m, 2u, 10u, 18u, 26u, SIGMA82[i * 16u + 2u], SIGMA82[i * 16u + 3u]); + G(&v, &m, 4u, 12u, 20u, 28u, SIGMA82[i * 16u + 4u], SIGMA82[i * 16u + 5u]); + G(&v, &m, 6u, 14u, 22u, 30u, SIGMA82[i * 16u + 6u], SIGMA82[i * 16u + 7u]); + G(&v, &m, 0u, 10u, 20u, 30u, SIGMA82[i * 16u + 8u], SIGMA82[i * 16u + 9u]); + G(&v, &m, 2u, 12u, 22u, 24u, SIGMA82[i * 16u + 10u], SIGMA82[i * 16u + 11u]); + G(&v, &m, 4u, 14u, 16u, 26u, SIGMA82[i * 16u + 12u], SIGMA82[i * 16u + 13u]); + G(&v, &m, 6u, 8u, 18u, 28u, SIGMA82[i * 16u + 14u], SIGMA82[i * 16u + 15u]); + } + + /** + * Set nonce if it passes the threshold and no other thread has set it */ - for (var j: u32 = id; j < id + 1u; j = j + 1u) { - if (atomicLoad(&work.found) != 0u) { - return; - } - m[0u] = j; - - // twelve rounds of mixing - for (var i: u32 = 0u; i < 12u; i = i + 1u) { - G(&v, &m, 0u, 8u, 16u, 24u, SIGMA82[i * 16u + 0u], SIGMA82[i * 16u + 1u]); - G(&v, &m, 2u, 10u, 18u, 26u, SIGMA82[i * 16u + 2u], SIGMA82[i * 16u + 3u]); - G(&v, &m, 4u, 12u, 20u, 28u, SIGMA82[i * 16u + 4u], SIGMA82[i * 16u + 5u]); - G(&v, &m, 6u, 14u, 22u, 30u, SIGMA82[i * 16u + 6u], SIGMA82[i * 16u + 7u]); - G(&v, &m, 0u, 10u, 20u, 30u, SIGMA82[i * 16u + 8u], SIGMA82[i * 16u + 9u]); - G(&v, &m, 2u, 12u, 22u, 24u, SIGMA82[i * 16u + 10u], SIGMA82[i * 16u + 11u]); - G(&v, &m, 4u, 14u, 16u, 26u, SIGMA82[i * 16u + 12u], SIGMA82[i * 16u + 13u]); - G(&v, &m, 6u, 8u, 18u, 28u, SIGMA82[i * 16u + 14u], SIGMA82[i * 16u + 15u]); - } - - // Store the result directly into work array - if ((BLAKE2B_IV32_1 ^ v[1u] ^ v[17u]) > ubo.threshold) { - atomicStore(&work.found, 1u); - work.nonce.x = id; - work.nonce.y = j; - return; - } + if (atomicLoad(&work.found) == 0u && (BLAKE2B_IV32_1 ^ v[1u] ^ v[17u]) > ubo.threshold) { + atomicStore(&work.found, 1u); + work.nonce.x = m[0]; + work.nonce.y = m[1]; + return; } + /** + * Nonce not found in this execution context + */ return; } `; // Initialize WebGPU static #device = null; + static #uboBuffer; static #gpuBuffer; static #cpuBuffer; static #bindGroupLayout; @@ -3297,6 +3296,10 @@ var init_powgpu = __esm({ } adapter.requestDevice().then((device) => { this.#device = device; + this.#uboBuffer = this.#device.createBuffer({ + size: 48, + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST + }); this.#gpuBuffer = this.#device.createBuffer({ size: 16, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC @@ -3355,19 +3358,18 @@ var init_powgpu = __esm({ const uint32 = hashHex.slice(i, i + 8); uboView.setUint32(i / 2, parseInt(uint32, 16)); } - uboView.setUint32(32, threshold, true); - const uboBuffer = _PowGpu.#device.createBuffer({ - size: uboView.byteLength, - usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST - }); - _PowGpu.#device.queue.writeBuffer(uboBuffer, 0, uboView); + const random = crypto.getRandomValues(new Uint32Array(1))[0]; + uboView.setUint32(32, random, true); + uboView.setUint32(36, threshold, true); + _PowGpu.#device.queue.writeBuffer(_PowGpu.#uboBuffer, 0, uboView); + _PowGpu.#device.queue.writeBuffer(_PowGpu.#gpuBuffer, 8, new Uint32Array([0])); const bindGroup = _PowGpu.#device.createBindGroup({ layout: _PowGpu.#bindGroupLayout, entries: [ { binding: 0, resource: { - buffer: uboBuffer + buffer: _PowGpu.#uboBuffer } }, { @@ -3391,10 +3393,7 @@ var init_powgpu = __esm({ const data = new DataView(_PowGpu.#cpuBuffer.getMappedRange()); const nonce = data.getBigUint64(0, true); const found = !!data.getUint32(8); - console.log(new Uint32Array(data.buffer)); _PowGpu.#cpuBuffer.unmap(); - console.log(`found: ${found}`); - console.log(`nonce: ${nonce}`); if (found) { const hex2 = nonce.toString(16).padStart(16, "0"); typeof callback === "function" && callback(hex2); @@ -10470,6 +10469,7 @@ __export(main_exports, { ChangeBlock: () => ChangeBlock, LedgerWallet: () => LedgerWallet, Pow: () => Pow, + PowGpu: () => PowGpu, ReceiveBlock: () => ReceiveBlock, Rolodex: () => Rolodex, Rpc: () => Rpc, @@ -10481,6 +10481,7 @@ init_account(); init_blake2b(); init_block(); init_powgl(); +init_powgpu(); init_rpc(); // dist/lib/rolodex.js diff --git a/global.min.js.map b/global.min.js.map index fd2dc6d..7d3f914 100644 --- a/global.min.js.map +++ b/global.min.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["lib/blake2b.js", "lib/constants.js", "lib/convert.js", "lib/rpc.js", "lib/entropy.js", "lib/safe.js", "lib/pool.js", "lib/workers/nano-nacl.js", "lib/account.js", "lib/workers/bip44-ckd.js", "lib/workers/powgl.js", "lib/workers/powgpu.js", "lib/workers.js", "../node_modules/events/events.js", "../node_modules/@ledgerhq/errors/src/helpers.ts", "../node_modules/@ledgerhq/errors/src/index.ts", "../node_modules/@ledgerhq/logs/src/index.ts", "../node_modules/@ledgerhq/hw-transport/src/Transport.ts", "../node_modules/semver/internal/constants.js", "../node_modules/semver/internal/debug.js", "../node_modules/semver/internal/re.js", "../node_modules/semver/internal/parse-options.js", "../node_modules/semver/internal/identifiers.js", "../node_modules/semver/classes/semver.js", "../node_modules/semver/functions/parse.js", "../node_modules/semver/functions/valid.js", "../node_modules/semver/functions/clean.js", "../node_modules/semver/functions/inc.js", "../node_modules/semver/functions/diff.js", "../node_modules/semver/functions/major.js", "../node_modules/semver/functions/minor.js", "../node_modules/semver/functions/patch.js", "../node_modules/semver/functions/prerelease.js", "../node_modules/semver/functions/compare.js", "../node_modules/semver/functions/rcompare.js", "../node_modules/semver/functions/compare-loose.js", "../node_modules/semver/functions/compare-build.js", "../node_modules/semver/functions/sort.js", "../node_modules/semver/functions/rsort.js", "../node_modules/semver/functions/gt.js", "../node_modules/semver/functions/lt.js", "../node_modules/semver/functions/eq.js", "../node_modules/semver/functions/neq.js", "../node_modules/semver/functions/gte.js", "../node_modules/semver/functions/lte.js", "../node_modules/semver/functions/cmp.js", "../node_modules/semver/functions/coerce.js", "../node_modules/semver/internal/lrucache.js", "../node_modules/semver/classes/range.js", "../node_modules/semver/classes/comparator.js", "../node_modules/semver/functions/satisfies.js", "../node_modules/semver/ranges/to-comparators.js", "../node_modules/semver/ranges/max-satisfying.js", "../node_modules/semver/ranges/min-satisfying.js", "../node_modules/semver/ranges/min-version.js", "../node_modules/semver/ranges/valid.js", "../node_modules/semver/ranges/outside.js", "../node_modules/semver/ranges/gtr.js", "../node_modules/semver/ranges/ltr.js", "../node_modules/semver/ranges/intersects.js", "../node_modules/semver/ranges/simplify.js", "../node_modules/semver/ranges/subset.js", "../node_modules/semver/index.js", "../node_modules/@ledgerhq/devices/src/index.ts", "../node_modules/tslib/tslib.es6.mjs", "../node_modules/rxjs/src/internal/util/isFunction.ts", "../node_modules/rxjs/src/internal/util/createErrorClass.ts", "../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts", "../node_modules/rxjs/src/internal/util/arrRemove.ts", "../node_modules/rxjs/src/internal/Subscription.ts", "../node_modules/rxjs/src/internal/config.ts", "../node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts", "../node_modules/rxjs/src/internal/util/reportUnhandledError.ts", "../node_modules/rxjs/src/internal/util/noop.ts", "../node_modules/rxjs/src/internal/NotificationFactories.ts", "../node_modules/rxjs/src/internal/util/errorContext.ts", "../node_modules/rxjs/src/internal/Subscriber.ts", "../node_modules/rxjs/src/internal/symbol/observable.ts", "../node_modules/rxjs/src/internal/util/identity.ts", "../node_modules/rxjs/src/internal/util/pipe.ts", "../node_modules/rxjs/src/internal/Observable.ts", "../node_modules/rxjs/src/internal/util/lift.ts", "../node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts", "../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts", "../node_modules/rxjs/src/internal/Subject.ts", "../node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts", "../node_modules/rxjs/src/internal/ReplaySubject.ts", "../node_modules/rxjs/src/internal/observable/empty.ts", "../node_modules/rxjs/src/internal/util/isScheduler.ts", "../node_modules/rxjs/src/internal/util/args.ts", "../node_modules/rxjs/src/internal/util/isArrayLike.ts", "../node_modules/rxjs/src/internal/util/isPromise.ts", "../node_modules/rxjs/src/internal/util/isInteropObservable.ts", "../node_modules/rxjs/src/internal/util/isAsyncIterable.ts", "../node_modules/rxjs/src/internal/util/throwUnobservableError.ts", "../node_modules/rxjs/src/internal/symbol/iterator.ts", "../node_modules/rxjs/src/internal/util/isIterable.ts", "../node_modules/rxjs/src/internal/util/isReadableStreamLike.ts", "../node_modules/rxjs/src/internal/observable/innerFrom.ts", "../node_modules/rxjs/src/internal/util/executeSchedule.ts", "../node_modules/rxjs/src/internal/operators/observeOn.ts", "../node_modules/rxjs/src/internal/operators/subscribeOn.ts", "../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts", "../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts", "../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts", "../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts", "../node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "../node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "../node_modules/rxjs/src/internal/scheduled/scheduled.ts", "../node_modules/rxjs/src/internal/observable/from.ts", "../node_modules/rxjs/src/internal/util/EmptyError.ts", "../node_modules/rxjs/src/internal/firstValueFrom.ts", "../node_modules/rxjs/src/internal/operators/map.ts", "../node_modules/rxjs/src/internal/operators/mergeInternals.ts", "../node_modules/rxjs/src/internal/operators/mergeMap.ts", "../node_modules/rxjs/src/internal/operators/mergeAll.ts", "../node_modules/rxjs/src/internal/observable/defer.ts", "../node_modules/rxjs/src/internal/observable/merge.ts", "../node_modules/rxjs/src/internal/operators/filter.ts", "../node_modules/rxjs/dist/esm5/internal/types.js", "../node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts", "../node_modules/rxjs/src/internal/operators/take.ts", "../node_modules/rxjs/src/internal/operators/ignoreElements.ts", "../node_modules/rxjs/src/internal/operators/throwIfEmpty.ts", "../node_modules/rxjs/src/internal/operators/first.ts", "../node_modules/rxjs/src/internal/operators/share.ts", "../node_modules/rxjs/src/internal/operators/takeUntil.ts", "../node_modules/rxjs/src/internal/operators/tap.ts", "../node_modules/rxjs/src/index.ts", "../node_modules/@ledgerhq/devices/src/ble/sendAPDU.ts", "../node_modules/@ledgerhq/devices/src/ble/receiveAPDU.ts", "../node_modules/rxjs/src/operators/index.ts", "../node_modules/@ledgerhq/hw-transport-web-ble/src/monitorCharacteristic.ts", "../node_modules/@ledgerhq/hw-transport-web-ble/src/TransportWebBLE.ts", "../node_modules/@ledgerhq/devices/src/hid-framing.ts", "../node_modules/@ledgerhq/hw-transport-webusb/src/webusb.ts", "../node_modules/@ledgerhq/hw-transport-webusb/src/TransportWebUSB.ts", "../node_modules/@ledgerhq/hw-transport-webhid/src/TransportWebHID.ts", "lib/ledger.js", "lib/block.js", "lib/tools.js", "main.js", "lib/rolodex.js", "lib/wallet.js", "lib/bip39-wordlist.js", "lib/bip39-mnemonic.js", "global.js"], - "sourcesContent": ["// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n/**\n* Implementation derived from blake2b@2.1.4. Copyright 2017 Emil Bay\n* (https://github.com/emilbayes/blake2b). See LICENSES/ISC.txt\n*\n* Modified to eliminate dependencies, port to TypeScript, and embed in web\n* workers.\n*\n* Original source commit: https://github.com/emilbayes/blake2b/blob/1f63e02e3f226642959506cdaa67c8819ff145cd/index.js\n*/\nexport class Blake2b {\n static BYTES_MIN = 1;\n static BYTES_MAX = 64;\n static KEYBYTES_MIN = 16;\n static KEYBYTES_MAX = 64;\n static SALTBYTES = 16;\n static PERSONALBYTES = 16;\n // Initialization Vector\n static BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n ]);\n static SIGMA8 = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n ];\n /**\n * These are offsets into a uint64 buffer.\n * Multiply them all by 2 to make them offsets into a uint32 buffer,\n * because this is Javascript and we don't have uint64s\n */\n static SIGMA82 = new Uint8Array(this.SIGMA8.map(x => x * 2));\n // reusable parameter_block\n static parameter_block = new Uint8Array([\n 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth\n 0, 0, 0, 0, // 4: leaf length, sequential mode\n 0, 0, 0, 0, // 8: node offset\n 0, 0, 0, 0, // 12: node offset\n 0, 0, 0, 0, // 16: node depth, inner length, rfu\n 0, 0, 0, 0, // 20: rfu\n 0, 0, 0, 0, // 24: rfu\n 0, 0, 0, 0, // 28: rfu\n 0, 0, 0, 0, // 32: salt\n 0, 0, 0, 0, // 36: salt\n 0, 0, 0, 0, // 40: salt\n 0, 0, 0, 0, // 44: salt\n 0, 0, 0, 0, // 48: personal\n 0, 0, 0, 0, // 52: personal\n 0, 0, 0, 0, // 56: personal\n 0, 0, 0, 0 // 60: personal\n ]);\n static v = new Uint32Array(32);\n static m = new Uint32Array(32);\n /**\n * 64-bit unsigned addition\n * Sets v[a,a+1] += v[b,b+1]\n * v should be a Uint32Array\n */\n static ADD64AA(v, a, b) {\n var o0 = v[a] + v[b];\n var o1 = v[a + 1] + v[b + 1];\n if (o0 >= 0x100000000) {\n o1++;\n }\n v[a] = o0;\n v[a + 1] = o1;\n }\n /**\n * 64-bit unsigned addition\n * Sets v[a,a+1] += b\n * b0 is the low 32 bits of b, b1 represents the high 32 bits\n */\n static ADD64AC(v, a, b0, b1) {\n var o0 = v[a] + b0;\n if (b0 < 0) {\n o0 += 0x100000000;\n }\n var o1 = v[a + 1] + b1;\n if (o0 >= 0x100000000) {\n o1++;\n }\n v[a] = o0;\n v[a + 1] = o1;\n }\n // Little-endian byte access\n static B2B_GET32(arr, i) {\n return (arr[i] ^\n (arr[i + 1] << 8) ^\n (arr[i + 2] << 16) ^\n (arr[i + 3] << 24));\n }\n /**\n * G Mixing function\n * The ROTRs are inlined for speed\n */\n static B2B_G(a, b, c, d, ix, iy) {\n var x0 = Blake2b.m[ix];\n var x1 = Blake2b.m[ix + 1];\n var y0 = Blake2b.m[iy];\n var y1 = Blake2b.m[iy + 1];\n Blake2b.ADD64AA(Blake2b.v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s\n Blake2b.ADD64AC(Blake2b.v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n var xor0 = Blake2b.v[d] ^ Blake2b.v[a];\n var xor1 = Blake2b.v[d + 1] ^ Blake2b.v[a + 1];\n Blake2b.v[d] = xor1;\n Blake2b.v[d + 1] = xor0;\n Blake2b.ADD64AA(Blake2b.v, c, d);\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = Blake2b.v[b] ^ Blake2b.v[c];\n xor1 = Blake2b.v[b + 1] ^ Blake2b.v[c + 1];\n Blake2b.v[b] = (xor0 >>> 24) ^ (xor1 << 8);\n Blake2b.v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);\n Blake2b.ADD64AA(Blake2b.v, a, b);\n Blake2b.ADD64AC(Blake2b.v, a, y0, y1);\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = Blake2b.v[d] ^ Blake2b.v[a];\n xor1 = Blake2b.v[d + 1] ^ Blake2b.v[a + 1];\n Blake2b.v[d] = (xor0 >>> 16) ^ (xor1 << 16);\n Blake2b.v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);\n Blake2b.ADD64AA(Blake2b.v, c, d);\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = Blake2b.v[b] ^ Blake2b.v[c];\n xor1 = Blake2b.v[b + 1] ^ Blake2b.v[c + 1];\n Blake2b.v[b] = (xor1 >>> 31) ^ (xor0 << 1);\n Blake2b.v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);\n }\n /**\n * Compression function. 'last' flag indicates last block.\n * Note we're representing 16 uint64s as 32 uint32s\n */\n static blake2bCompress(ctx, last) {\n let i = 0;\n // init work variables\n for (i = 0; i < 16; i++) {\n Blake2b.v[i] = ctx.h[i];\n Blake2b.v[i + 16] = Blake2b.BLAKE2B_IV32[i];\n }\n // low 64 bits of offset\n Blake2b.v[24] = Blake2b.v[24] ^ ctx.t;\n Blake2b.v[25] = Blake2b.v[25] ^ (ctx.t / 0x100000000);\n // high 64 bits not supported, offset may not be higher than 2**53-1\n // last block flag set ?\n if (last) {\n Blake2b.v[28] = ~Blake2b.v[28];\n Blake2b.v[29] = ~Blake2b.v[29];\n }\n // get little-endian words\n for (i = 0; i < 32; i++) {\n Blake2b.m[i] = Blake2b.B2B_GET32(ctx.b, 4 * i);\n }\n // twelve rounds of mixing\n for (i = 0; i < 12; i++) {\n Blake2b.B2B_G(0, 8, 16, 24, Blake2b.SIGMA82[i * 16 + 0], Blake2b.SIGMA82[i * 16 + 1]);\n Blake2b.B2B_G(2, 10, 18, 26, Blake2b.SIGMA82[i * 16 + 2], Blake2b.SIGMA82[i * 16 + 3]);\n Blake2b.B2B_G(4, 12, 20, 28, Blake2b.SIGMA82[i * 16 + 4], Blake2b.SIGMA82[i * 16 + 5]);\n Blake2b.B2B_G(6, 14, 22, 30, Blake2b.SIGMA82[i * 16 + 6], Blake2b.SIGMA82[i * 16 + 7]);\n Blake2b.B2B_G(0, 10, 20, 30, Blake2b.SIGMA82[i * 16 + 8], Blake2b.SIGMA82[i * 16 + 9]);\n Blake2b.B2B_G(2, 12, 22, 24, Blake2b.SIGMA82[i * 16 + 10], Blake2b.SIGMA82[i * 16 + 11]);\n Blake2b.B2B_G(4, 14, 16, 26, Blake2b.SIGMA82[i * 16 + 12], Blake2b.SIGMA82[i * 16 + 13]);\n Blake2b.B2B_G(6, 8, 18, 28, Blake2b.SIGMA82[i * 16 + 14], Blake2b.SIGMA82[i * 16 + 15]);\n }\n for (i = 0; i < 16; i++) {\n ctx.h[i] = ctx.h[i] ^ Blake2b.v[i] ^ Blake2b.v[i + 16];\n }\n }\n /**\n * Updates a BLAKE2b streaming hash\n * Requires hash context and Uint8Array (byte array)\n */\n static blake2bUpdate(ctx, input) {\n for (var i = 0; i < input.length; i++) {\n if (ctx.c === 128) { // buffer full ?\n ctx.t += ctx.c; // add counters\n Blake2b.blake2bCompress(ctx, false); // compress (not last)\n ctx.c = 0; // counter to zero\n }\n ctx.b[ctx.c++] = input[i];\n }\n }\n /**\n * Completes a BLAKE2b streaming hash\n * Returns a Uint8Array containing the message digest\n */\n static blake2bFinal(ctx, out) {\n ctx.t += ctx.c; // mark last block offset\n while (ctx.c < 128) { // fill up with zeros\n ctx.b[ctx.c++] = 0;\n }\n Blake2b.blake2bCompress(ctx, true); // final block flag = 1\n for (var i = 0; i < ctx.outlen; i++) {\n out[i] = ctx.h[i >> 2] >> (8 * (i & 3));\n }\n return out;\n }\n static hexSlice(buf) {\n let str = '';\n for (let i = 0; i < buf.length; i++)\n str += Blake2b.toHex(buf[i]);\n return str;\n }\n static toHex(n) {\n if (typeof n !== 'number')\n throw new TypeError(`expected number to convert to hex; received ${typeof n}`);\n if (n < 0 || n > 255)\n throw new RangeError(`expected byte value 0-255; received ${n}`);\n return n.toString(16).padStart(2, '0');\n }\n b;\n h;\n t;\n c;\n outlen;\n /**\n * Creates a BLAKE2b hashing context\n * Requires an output length between 1 and 64 bytes\n * Takes an optional Uint8Array key\n */\n constructor(outlen, key, salt, personal, noAssert) {\n if (noAssert !== true) {\n if (outlen < Blake2b.BYTES_MIN)\n throw new RangeError(`expected outlen >= ${Blake2b.BYTES_MIN}; actual ${outlen}`);\n if (outlen > Blake2b.BYTES_MAX)\n throw new RangeError(`expectd outlen <= ${Blake2b.BYTES_MAX}; actual ${outlen}`);\n if (key != null) {\n if (!(key instanceof Uint8Array))\n throw new TypeError(`key must be Uint8Array or Buffer`);\n if (key.length < Blake2b.KEYBYTES_MIN)\n throw new RangeError(`expected key >= ${Blake2b.KEYBYTES_MIN}; actual ${key.length}`);\n if (key.length > Blake2b.KEYBYTES_MAX)\n throw new RangeError(`expected key <= ${Blake2b.KEYBYTES_MAX}; actual ${key.length}`);\n }\n if (salt != null) {\n if (!(salt instanceof Uint8Array))\n throw new TypeError(`salt must be Uint8Array or Buffer`);\n if (salt.length !== Blake2b.SALTBYTES)\n throw new RangeError(`expected salt ${Blake2b.SALTBYTES} bytes; actual ${salt.length} bytes`);\n }\n if (personal != null) {\n if (!(personal instanceof Uint8Array))\n throw new TypeError(`personal must be Uint8Array or Buffer`);\n if (personal.length !== Blake2b.PERSONALBYTES)\n throw new RangeError(`expected personal ${Blake2b.PERSONALBYTES} bytes; actual ${personal.length} bytes`);\n }\n }\n this.b = new Uint8Array(128);\n this.h = new Uint32Array(16);\n this.t = 0; // input count\n this.c = 0; // pointer within buffer\n this.outlen = outlen; // output length in bytes\n // zero out parameter_block before usage\n Blake2b.parameter_block.fill(0);\n // state, 'param block'\n Blake2b.parameter_block[0] = outlen;\n if (key)\n Blake2b.parameter_block[1] = key.length;\n Blake2b.parameter_block[2] = 1; // fanout\n Blake2b.parameter_block[3] = 1; // depth\n if (salt)\n Blake2b.parameter_block.set(salt, 32);\n if (personal)\n Blake2b.parameter_block.set(personal, 48);\n // initialize hash state\n for (var i = 0; i < 16; i++) {\n this.h[i] = Blake2b.BLAKE2B_IV32[i] ^ Blake2b.B2B_GET32(Blake2b.parameter_block, i * 4);\n }\n // key the hash, if applicable\n if (key) {\n Blake2b.blake2bUpdate(this, key);\n // at the end\n this.c = 128;\n }\n }\n update(input) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`input must be Uint8Array or Buffer`);\n Blake2b.blake2bUpdate(this, input);\n return this;\n }\n digest(out) {\n const buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out;\n if (!(buf instanceof Uint8Array))\n throw new TypeError(`out must be \"binary\", \"hex\", Uint8Array, or Buffer`);\n if (buf.length < this.outlen)\n throw new RangeError(`out must have at least outlen bytes of space`);\n Blake2b.blake2bFinal(this, buf);\n if (out === 'hex')\n return Blake2b.hexSlice(buf);\n return buf;\n }\n}\nexport default Blake2b.toString();\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nexport const ACCOUNT_KEY_LENGTH = 64;\nexport const ADDRESS_GAP = 20;\nexport const ALPHABET = '13456789abcdefghijkmnopqrstuwxyz';\nexport const BIP39_ITERATIONS = 2048;\nexport const BIP44_PURPOSE = 44;\nexport const BIP44_COIN_NANO = 165;\nexport const BURN_ADDRESS = 'nano_1111111111111111111111111111111111111111111111111111hifc8npp';\nexport const HARDENED_OFFSET = 0x80000000;\nexport const NONCE_LENGTH = 24;\nexport const PREAMBLE = '0000000000000000000000000000000000000000000000000000000000000006';\nexport const PREFIX = 'nano_';\nexport const PREFIX_LEGACY = 'xrb_';\nexport const SEED_LENGTH_BIP44 = 128;\nexport const SEED_LENGTH_BLAKE2B = 64;\nexport const SLIP10_ED25519 = 'ed25519 seed';\nexport const THRESHOLD_RECEIVE = 0xfffffe00;\nexport const THRESHOLD_SEND = 0xfffffff8;\nexport const XNO = '\u04FE';\nexport const LEDGER_STATUS_CODES = Object.freeze({\n 0x6700: 'INCORRECT_LENGTH',\n 0x670a: 'NO_APPLICATION_SPECIFIED',\n 0x6807: 'APPLICATION_NOT_INSTALLED',\n 0x6d00: 'APPLICATION_ALREADY_LAUNCHED',\n 0x6982: 'SECURITY_STATUS_NOT_SATISFIED',\n 0x6985: 'CONDITIONS_OF_USE_NOT_SATISFIED',\n 0x6a81: 'INVALID_SIGNATURE',\n 0x6a82: 'CACHE_MISS',\n 0x6b00: 'INCORRECT_PARAMETER',\n 0x6e01: 'TRANSPORT_STATUS_ERROR',\n 0x9000: 'OK'\n});\nexport const UNITS = Object.freeze({\n RAW: 0,\n RAI: 24,\n NYANO: 24,\n KRAI: 27,\n PICO: 27,\n MRAI: 30,\n NANO: 30,\n KNANO: 33,\n MNANO: 36\n});\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { ALPHABET } from \"./constants.js\";\nexport const base32 = {\n /**\n * Converts a base32 string to a Uint8Array of bytes.\n *\n * @param {string} base32 - String to convert\n * @returns {Uint8Array} Byte array representation of the input string\n */\n toBytes(base32) {\n const leftover = (base32.length * 5) % 8;\n const offset = leftover === 0\n ? 0\n : 8 - leftover;\n let bits = 0;\n let value = 0;\n let index = 0;\n let output = new Uint8Array(Math.ceil((base32.length * 5) / 8));\n for (let i = 0; i < base32.length; i++) {\n value = (value << 5) | ALPHABET.indexOf(base32[i]);\n bits += 5;\n if (bits >= 8) {\n output[index++] = (value >>> (bits + offset - 8)) & 255;\n bits -= 8;\n }\n }\n if (bits > 0) {\n output[index++] = (value << (bits + offset - 8)) & 255;\n }\n if (leftover !== 0) {\n output = output.slice(1);\n }\n return output;\n },\n /**\n * Converts a base32 string to a hexadecimal string.\n *\n * @param {string} base32 - String to convert\n * @returns {string} Hexadecimal representation of the input base32\n */\n toHex(base32) {\n return bytes.toHex(this.toBytes(base32));\n }\n};\nexport const bin = {\n /**\n * Convert a binary string to a Uint8Array of bytes.\n *\n * @param {string} bin - String to convert\n * @returns {Uint8Array} Byte array representation of the input string\n */\n toBytes(bin) {\n const bytes = [];\n while (bin.length > 0) {\n const bits = bin.substring(0, 8);\n bytes.push(parseInt(bits, 2));\n bin = bin.substring(8);\n }\n return new Uint8Array(bytes);\n },\n /**\n * Convert a binary string to a hexadecimal string.\n *\n * @param {string} bin - String to convert\n * @returns {string} Hexadecimal string representation of the input binary\n */\n toHex(bin) {\n return parseInt(bin, 2).toString(16);\n }\n};\nexport const buffer = {\n /**\n * Converts an ArrayBuffer to a base32 string.\n *\n * @param {ArrayBuffer} buffer - Buffer to convert\n * @returns {string} Base32 string representation of the input buffer\n */\n toBase32(buffer) {\n return bytes.toBase32(new Uint8Array(buffer));\n },\n /**\n * Converts an ArrayBuffer to a binary string.\n *\n * @param {ArrayBuffer} buffer - Buffer to convert\n * @returns {string} Binary string representation of the input buffer\n */\n toBin(buffer) {\n return bytes.toBin(new Uint8Array(buffer));\n },\n /**\n * Sums an ArrayBuffer to a decimal integer. If the result is larger than\n * Number.MAX_SAFE_INTEGER, it will be returned as a bigint.\n *\n * @param {ArrayBuffer} buffer - Buffer to convert\n * @returns {bigint|number} Decimal sum of the literal buffer values\n */\n toDec(buffer) {\n return bytes.toDec(new Uint8Array(buffer));\n },\n /**\n * Converts an ArrayBuffer to a hexadecimal string.\n *\n * @param {ArrayBuffer} buffer - Buffer to convert\n * @returns {string} Hexadecimal string representation of the input buffer\n */\n toHex(buffer) {\n return bytes.toHex(new Uint8Array(buffer));\n },\n /**\n * Converts an ArrayBuffer to a UTF-8 text string.\n *\n * @param {ArrayBuffer} buffer - Buffer to convert\n * @returns {string} UTF-8 encoded text string\n */\n toUtf8(buffer) {\n return bytes.toUtf8(new Uint8Array(buffer));\n }\n};\nexport const bytes = {\n /**\n * Converts a Uint8Aarray of bytes to a base32 string.\n *\n * @param {Uint8Array} bytes - Byte array to convert\n * @returns {string} Base32 string representation of the input bytes\n */\n toBase32(bytes) {\n const leftover = (bytes.length * 8) % 5;\n const offset = leftover === 0\n ? 0\n : 5 - leftover;\n let value = 0;\n let output = '';\n let bits = 0;\n for (let i = 0; i < bytes.length; i++) {\n value = (value << 8) | bytes[i];\n bits += 8;\n while (bits >= 5) {\n output += ALPHABET[(value >>> (bits + offset - 5)) & 31];\n bits -= 5;\n }\n }\n if (bits > 0) {\n output += ALPHABET[(value << (5 - (bits + offset))) & 31];\n }\n return output;\n },\n /**\n * Convert a Uint8Array of bytes to a binary string.\n *\n * @param {Uint8Array} bytes - Byte array to convert\n * @returns {string} Binary string representation of the input value\n */\n toBin(bytes) {\n return [...bytes].map(b => b.toString(2).padStart(8, '0')).join('');\n },\n /**\n * Sums an array of bytes to a decimal integer. If the result is larger than\n * Number.MAX_SAFE_INTEGER, it will be returned as a bigint.\n *\n * @param {Uint8Array} bytes - Byte array to convert\n * @returns {bigint|number} Decimal sum of the literal byte values\n */\n toDec(bytes) {\n const integers = [];\n bytes.reverse().forEach(b => integers.push(BigInt(b)));\n let decimal = 0n;\n for (let i = 0; i < integers.length; i++) {\n decimal += integers[i] << BigInt(i * 8);\n }\n if (decimal > 9007199254740991n) {\n return decimal;\n }\n else {\n return Number(decimal);\n }\n },\n /**\n * Converts a Uint8Array of bytes to a hexadecimal string.\n *\n * @param {Uint8Array} bytes - Byte array to convert\n * @returns {string} Hexadecimal string representation of the input bytes\n */\n toHex(bytes) {\n const byteArray = [...bytes].map(byte => byte.toString(16).padStart(2, '0'));\n return byteArray.join('').toUpperCase();\n },\n /**\n * Converts a Uint8Array of bytes to a UTF-8 text string.\n *\n * @param {Uint8Array} bytes - Byte array to convert\n * @returns {string} UTF-8 encoded text string\n */\n toUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n }\n};\nexport const dec = {\n /**\n * Convert a decimal integer to a binary string.\n *\n * @param {bigint|number|string} decimal - Integer to convert\n * @param {number} [padding=0] - Minimum length of the resulting string which will be padded as necessary with starting zeroes\n * @returns {string} Binary string representation of the input decimal\n */\n toBin(decimal, padding = 0) {\n if (typeof padding !== 'number') {\n throw new TypeError('Invalid padding');\n }\n try {\n return BigInt(decimal)\n .toString(2)\n .padStart(padding, '0');\n }\n catch (err) {\n throw new RangeError('Invalid decimal integer');\n }\n },\n /**\n * Convert a decimal integer to a Uint8Array of bytes. Fractional part is truncated.\n *\n * @param {bigint|number|string} decimal - Integer to convert\n * @param {number} [padding=0] - Minimum length of the resulting array which will be padded as necessary with starting 0x00 bytes\n * @returns {Uint8Array} Byte array representation of the input decimal\n */\n toBytes(decimal, padding = 0) {\n if (typeof padding !== 'number') {\n throw new TypeError('Invalid padding');\n }\n let integer = BigInt(decimal);\n const bytes = [];\n while (integer > 0) {\n const lsb = BigInt.asUintN(8, integer);\n bytes.push(Number(lsb));\n integer >>= 8n;\n }\n const result = new Uint8Array(Math.max(padding, bytes.length));\n result.set(bytes);\n return (result.reverse());\n },\n /**\n * Convert a decimal integer to a hexadecimal string.\n *\n * @param {(bigint|number|string)} decimal - Integer to convert\n * @param {number} [padding=0] - Minimum length of the resulting string which will be padded as necessary with starting zeroes\n * @returns {string} Hexadecimal string representation of the input decimal\n */\n toHex(decimal, padding = 0) {\n if (typeof padding !== 'number') {\n throw new TypeError('Invalid padding');\n }\n try {\n return BigInt(decimal)\n .toString(16)\n .padStart(padding, '0')\n .toUpperCase();\n }\n catch (err) {\n throw new RangeError('Invalid decimal integer');\n }\n }\n};\nexport const hex = {\n /**\n * Convert a hexadecimal string to a binary string.\n *\n * @param {string} hex - Hexadecimal number string to convert\n * @returns {string} Binary string representation of the input value\n */\n toBin(hex) {\n return [...hex].map(c => dec.toBin(parseInt(c, 16), 4)).join('');\n },\n /**\n * Convert a hexadecimal string to a Uint8Array of bytes.\n *\n * @param {string} hex - Hexadecimal number string to convert\n * @param {number} [padding=0] - Minimum length of the resulting array which will be padded as necessary with starting 0x00 bytes\n * @returns {Uint8Array} Byte array representation of the input value\n */\n toBytes(hex, padding = 0) {\n if (typeof padding !== 'number') {\n throw new TypeError('Invalid padding when converting hex to bytes');\n }\n const hexArray = hex.match(/.{1,2}/g);\n if (!/^[0-9a-f]+$/i.test(hex) || hexArray == null) {\n console.warn('Invalid hex string when converting to bytes');\n return new Uint8Array();\n }\n else {\n const bytes = Uint8Array.from(hexArray.map(byte => parseInt(byte, 16)));\n const result = new Uint8Array(Math.max(padding, bytes.length));\n result.set(bytes.reverse());\n return result.reverse();\n }\n }\n};\nexport const utf8 = {\n /**\n * Convert a UTF-8 text string to a Uint8Array of bytes.\n *\n * @param {string} utf8 - String to convert\n * @returns {Uint8Array} Byte array representation of the input string\n */\n toBytes(utf8) {\n return new TextEncoder().encode(utf8);\n },\n /**\n * Convert a string to a hexadecimal representation\n *\n * @param {string} utf8 - String to convert\n * @returns {string} Hexadecimal representation of the input string\n */\n toHex(utf8) {\n return bytes.toHex(this.toBytes(utf8));\n }\n};\nexport default { base32, bin, bytes, dec, hex, utf8 };\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n/**\n* Represents a Nano network node. It primarily consists of a URL which will\n* accept RPC calls, and an optional API key header construction can be passed if\n* required by the node. Once instantiated, the Rpc object can be used to call\n* any action supported by the Nano protocol. The URL protocol must be HTTPS; any\n* other value will be changed automatically.\n*/\nexport class Rpc {\n #u;\n #n;\n constructor(url, apiKeyName) {\n this.#u = new URL(url);\n this.#u.protocol = 'https:';\n this.#n = apiKeyName;\n }\n /**\n *\n * @param {string} action - Nano protocol RPC call to execute\n * @param {object} [data] - JSON to send to the node as defined by the action\n * @returns {Promise} JSON-formatted RPC results from the node\n */\n async call(action, data) {\n var process = process || null;\n this.#validate(action);\n const headers = {};\n headers['Content-Type'] = 'application/json';\n if (this.#n && process?.env?.LIBNEMO_RPC_API_KEY) {\n headers[this.#n] = process.env.LIBNEMO_RPC_API_KEY;\n }\n data ??= {};\n data.action = action.toLowerCase();\n const body = JSON.stringify(data)\n .replaceAll('/', '\\\\u002f')\n .replaceAll('<', '\\\\u003c')\n .replaceAll('>', '\\\\u003d')\n .replaceAll('\\\\', '\\\\u005c');\n const req = new Request(this.#u, {\n method: 'POST',\n headers,\n body\n });\n try {\n const res = await fetch(req);\n return await res.json();\n }\n catch (err) {\n console.error(err);\n return JSON.stringify(err);\n }\n }\n #validate(action) {\n if (!action) {\n throw new ReferenceError('Action is required for RPCs');\n }\n if (typeof action !== 'string') {\n throw new TypeError('RPC action must be a string');\n }\n if (!/^[A-Za-z]+(_[A-Za-z]+)*$/.test(action)) {\n throw new TypeError('RPC action contains invalid characters');\n }\n }\n}\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { bytes, hex } from './convert.js';\nconst { crypto } = globalThis;\nconst MIN = 16;\nconst MAX = 32;\nconst MOD = 4;\n/**\n* Represents a cryptographically strong source of entropy suitable for use in\n* BIP-39 mnemonic phrase generation and consequently BIP-44 key derivation.\n*\n* The constructor will accept one of several different data types under certain\n* constraints. If the constraints are not met, an error will be thrown. If no\n* value, or the equivalent of no value, is passed to the constructor, then a\n* brand new source of entropy will be generated at the maximum size of 256 bits.\n*/\nexport class Entropy {\n static #isInternal = false;\n #bytes;\n get bits() { return bytes.toBin(this.#bytes); }\n get buffer() { return this.#bytes.buffer; }\n get bytes() { return this.#bytes; }\n get hex() { return bytes.toHex(this.#bytes); }\n constructor(bytes) {\n if (!Entropy.#isInternal) {\n throw new Error(`Entropy cannot be instantiated directly. Use 'await Entropy.create()' instead.`);\n }\n Entropy.#isInternal = false;\n this.#bytes = bytes;\n }\n static async create(size) {\n return new Promise(resolve => {\n if (size != null) {\n if (typeof size !== 'number') {\n throw new TypeError(`Entropy cannot use ${typeof size} as a size`);\n }\n if (size < MIN || size > MAX) {\n throw new RangeError(`Entropy must be ${MIN}-${MAX} bytes`);\n }\n if (size % MOD !== 0) {\n throw new RangeError(`Entropy must be a multiple of ${MOD} bytes`);\n }\n }\n Entropy.#isInternal = true;\n resolve(new this(crypto.getRandomValues(new Uint8Array(size ?? MAX))));\n });\n }\n static async import(input) {\n return new Promise((resolve, reject) => {\n if (typeof input === 'string') {\n if (input.length < MIN * 2 || input.length > MAX * 2) {\n throw new RangeError(`Entropy must be ${MIN * 2}-${MAX * 2} characters`);\n }\n if (input.length % MOD * 2 !== 0) {\n throw new RangeError(`Entropy must be a multiple of ${MOD * 2} characters`);\n }\n if (!/^[0-9a-fA-F]+$/i.test(input)) {\n throw new RangeError('Entropy contains invalid hexadecimal characters');\n }\n Entropy.#isInternal = true;\n resolve(new this(hex.toBytes(input)));\n }\n if (input instanceof ArrayBuffer) {\n if (input.byteLength < MIN || input.byteLength > MAX) {\n throw new Error(`Entropy must be ${MIN}-${MAX} bytes`);\n }\n if (input.byteLength % MOD !== 0) {\n throw new RangeError(`Entropy must be a multiple of ${MOD} bytes`);\n }\n Entropy.#isInternal = true;\n resolve(new this(new Uint8Array(input)));\n }\n if (input instanceof Uint8Array) {\n if (input.length < MIN || input.length > MAX) {\n throw new Error(`Entropy must be ${MIN}-${MAX} bytes`);\n }\n if (input.length % MOD !== 0) {\n throw new RangeError(`Entropy must be a multiple of ${MOD} bytes`);\n }\n Entropy.#isInternal = true;\n resolve(new this(input));\n }\n reject(new TypeError(`Entropy cannot import ${typeof input}`));\n });\n }\n /**\n * Randomizes the bytes, rendering the original values generally inaccessible.\n */\n destroy() {\n try {\n crypto.getRandomValues(this.#bytes);\n return true;\n }\n catch (err) {\n return false;\n }\n }\n}\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { buffer, hex, utf8 } from './convert.js';\nimport { Entropy } from './entropy.js';\nconst { subtle } = globalThis.crypto;\nconst ERR_MSG = 'Failed to store item in Safe';\nexport class Safe {\n #storage;\n constructor() {\n this.#storage = globalThis.sessionStorage;\n }\n async put(name, passkey, data) {\n if (this.#storage.getItem(name)) {\n throw new Error(ERR_MSG);\n }\n return this.overwrite(name, passkey, data);\n }\n async overwrite(name, passkey, data) {\n if (this.#isNotValid(name, passkey, data)) {\n throw new Error(ERR_MSG);\n }\n const iv = await Entropy.create();\n if (typeof passkey === 'string') {\n try {\n passkey = await subtle.importKey('raw', utf8.toBytes(passkey), 'PBKDF2', false, ['deriveBits', 'deriveKey']);\n passkey = await subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-512', salt: iv.bytes, iterations: 210000 }, passkey, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);\n }\n catch (err) {\n throw new Error(ERR_MSG);\n }\n }\n try {\n if (typeof data === 'bigint') {\n data = data.toString();\n }\n data = JSON.stringify(data);\n const encoded = utf8.toBytes(data);\n const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv: iv.buffer }, passkey, encoded);\n const record = {\n encrypted: buffer.toHex(encrypted),\n iv: iv.hex\n };\n await new Promise((resolve, reject) => {\n try {\n this.#storage.setItem(name, JSON.stringify(record));\n resolve();\n }\n catch (err) {\n reject(err);\n }\n });\n passkey = '';\n }\n catch (err) {\n throw new Error(ERR_MSG);\n }\n return (this.#storage.getItem(name) != null);\n }\n async get(name, passkey) {\n if (this.#isNotValid(name, passkey)) {\n return null;\n }\n const item = await new Promise(resolve => {\n resolve(this.#storage.getItem(name));\n });\n if (item == null) {\n return null;\n }\n const record = JSON.parse(item);\n const encrypted = hex.toBytes(record.encrypted);\n const iv = await Entropy.import(record.iv);\n try {\n if (typeof passkey === 'string') {\n passkey = await subtle.importKey('raw', utf8.toBytes(passkey), 'PBKDF2', false, ['deriveBits', 'deriveKey']);\n passkey = await subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-512', salt: iv.bytes, iterations: 210000 }, passkey, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);\n }\n }\n catch (err) {\n return null;\n }\n try {\n const decrypted = await subtle.decrypt({ name: 'AES-GCM', iv: iv.buffer }, passkey, encrypted);\n const decoded = buffer.toUtf8(decrypted);\n const data = JSON.parse(decoded);\n passkey = '';\n this.#storage.removeItem(name);\n return data;\n }\n catch (err) {\n return null;\n }\n }\n #isNotValid(name, passkey, data) {\n if (typeof name !== 'string' || name === '') {\n return true;\n }\n if (typeof passkey !== 'string' || passkey === '') {\n if (!(passkey instanceof CryptoKey)) {\n return true;\n }\n }\n if (typeof data === 'object') {\n try {\n JSON.stringify(data);\n }\n catch (err) {\n return true;\n }\n }\n return false;\n }\n}\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n/**\n* Processes an array of tasks using Web Workers.\n*/\nexport class Pool {\n static #cores = Math.max(1, navigator.hardwareConcurrency - 1);\n #queue = [];\n #threads = [];\n #url;\n get threadsBusy() {\n let n = 0;\n for (const thread of this.#threads) {\n n += +(thread.job != null);\n }\n return n;\n }\n get threadsIdle() {\n let n = 0;\n for (const thread of this.#threads) {\n n += +(thread.job == null);\n }\n return n;\n }\n async assign(data) {\n if (!(data instanceof ArrayBuffer || Array.isArray(data)))\n data = [data];\n return new Promise((resolve, reject) => {\n const job = {\n id: performance.now(),\n results: [],\n data,\n resolve,\n reject\n };\n if (this.#queue.length > 0) {\n this.#queue.push(job);\n }\n else {\n for (const thread of this.#threads)\n this.#assign(thread, job);\n }\n });\n }\n /**\n *\n * @param {string} worker - Stringified worker class\n * @param {number} [count=1] - Integer between 1 and CPU thread count shared among all Pools\n */\n constructor(worker, count = 1) {\n count = Math.min(Pool.#cores, Math.max(1, Math.floor(Math.abs(count))));\n this.#url = URL.createObjectURL(new Blob([worker], { type: 'text/javascript' }));\n for (let i = 0; i < count; i++) {\n const thread = {\n worker: new Worker(this.#url, { type: 'module' }),\n job: null\n };\n thread.worker.addEventListener('message', message => {\n let result = JSON.parse(new TextDecoder().decode(message.data) || \"[]\");\n if (!Array.isArray(result))\n result = [result];\n this.#report(thread, result);\n });\n this.#threads.push(thread);\n Pool.#cores = Math.max(1, Pool.#cores - this.#threads.length);\n }\n }\n #assign(thread, job) {\n if (job.data instanceof ArrayBuffer) {\n if (job.data.byteLength > 0) {\n thread.job = job;\n thread.worker.postMessage({ buffer: job.data }, [job.data]);\n }\n }\n else {\n const chunk = 1 + (job.data.length / this.threadsIdle);\n const next = job.data.slice(0, chunk);\n job.data = job.data.slice(chunk);\n if (job.data.length === 0)\n this.#queue.shift();\n if (next?.length > 0) {\n const buffer = new TextEncoder().encode(JSON.stringify(next)).buffer;\n thread.job = job;\n thread.worker.postMessage({ buffer }, [buffer]);\n }\n }\n }\n #isJobDone(jobId) {\n for (const thread of this.#threads) {\n if (thread.job?.id === jobId)\n return false;\n }\n return true;\n }\n #report(thread, results) {\n if (thread.job == null) {\n throw new Error('Thread returned results but had nowhere to report it.');\n }\n const job = thread.job;\n if (this.#queue.length > 0) {\n this.#assign(thread, this.#queue[0]);\n }\n else {\n thread.job = null;\n }\n if (results.length > 0) {\n job.results.push(...results);\n }\n if (this.#isJobDone(job.id)) {\n job.resolve(job.results);\n }\n }\n}\n/**\n* Provides basic worker event messaging to extending classes.\n*\n* In order to be properly bundled in a format that can be used to create an\n* inline Web Worker, the extending classes must export WorkerInterface and\n* themselves as a string:\n*```\n* export default `\n* \tconst WorkerInterface = ${WorkerInterface}\n* \tconst Pow = ${Pow}\n* `\n* ```\n* They must also initialize the event listener by calling their inherited\n* `listen()` function. Finally, they must override the implementation of the\n* `work()` function. See the documentation of those functions for details.\n*/\nexport class WorkerInterface {\n /**\n * Processes data through a worker.\n *\n * Extending classes must override this template by implementing the same\n * function signature and providing their own processing call in the try-catch\n * block.\n *\n * @param {any[]} data - Array of data to process\n * @returns Promise for that data after being processed\n */\n static async work(data) {\n return new Promise(async (resolve, reject) => {\n for (let d of data) {\n try {\n d = await d;\n }\n catch (err) {\n reject(err);\n }\n }\n resolve(data);\n });\n }\n /**\n * Encodes worker results as an ArrayBuffer so it can be transferred back to\n * the main thread.\n *\n * @param {any[]} results - Array of processed data\n */\n static report(results) {\n const buffer = new TextEncoder().encode(JSON.stringify(results)).buffer;\n //@ts-expect-error\n postMessage(buffer, [buffer]);\n }\n /**\n * Listens for messages from the main thread.\n *\n * Extending classes must call this in a static initialization block:\n * ```\n * static {\n * \tPow.listen()\n * }\n * ```\n */\n static listen() {\n addEventListener('message', (message) => {\n const { name, buffer } = message.data;\n if (name === 'STOP') {\n close();\n const buffer = new ArrayBuffer(0);\n //@ts-expect-error\n postMessage(buffer, [buffer]);\n }\n else {\n const data = JSON.parse(new TextDecoder().decode(buffer));\n this.work(data).then(this.report);\n }\n });\n }\n}\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n'use strict';\nimport { Blake2b } from '../blake2b.js';\nimport { WorkerInterface } from '../pool.js';\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n//\n// Modified in 2024 by Chris Duncan to hash secret key to public key using\n// BLAKE2b instead of SHA-512 as specified in the documentation for Nano\n// cryptocurrency.\n// See for details: https://docs.nano.org/integration-guides/the-basics/\n// Original source commit: https://github.com/dchest/tweetnacl-js/blob/71df1d6a1d78236ca3e9f6c788786e21f5a651a6/nacl-fast.js\nexport class NanoNaCl extends WorkerInterface {\n static {\n NanoNaCl.listen();\n }\n static async work(data) {\n return new Promise(async (resolve, reject) => {\n for (let d of data) {\n try {\n d.publicKey = await this.convert(d.privateKey);\n }\n catch (err) {\n reject(err);\n }\n }\n resolve(data);\n });\n }\n static gf = function (init) {\n const r = new Float64Array(16);\n if (init)\n for (let i = 0; i < init.length; i++)\n r[i] = init[i];\n return r;\n };\n static gf0 = this.gf();\n static gf1 = this.gf([1]);\n static D = this.gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\n static D2 = this.gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\n static X = this.gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\n static Y = this.gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\n static I = this.gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n static vn(x, xi, y, yi, n) {\n let d = 0;\n for (let i = 0; i < n; i++)\n d |= x[xi + i] ^ y[yi + i];\n return (1 & ((d - 1) >>> 8)) - 1;\n }\n static crypto_verify_32(x, xi, y, yi) {\n return this.vn(x, xi, y, yi, 32);\n }\n static set25519(r, a) {\n for (let i = 0; i < 16; i++)\n r[i] = a[i] | 0;\n }\n static car25519(o) {\n let v, c = 1;\n for (let i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n }\n static sel25519(p, q, b) {\n let t;\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n }\n static pack25519(o, n) {\n let b;\n const m = this.gf();\n const t = this.gf();\n for (let i = 0; i < 16; i++)\n t[i] = n[i];\n this.car25519(t);\n this.car25519(t);\n this.car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n this.sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n }\n static neq25519(a, b) {\n const c = new Uint8Array(32);\n const d = new Uint8Array(32);\n this.pack25519(c, a);\n this.pack25519(d, b);\n return this.crypto_verify_32(c, 0, d, 0);\n }\n static par25519(a) {\n var d = new Uint8Array(32);\n this.pack25519(d, a);\n return d[0] & 1;\n }\n static unpack25519(o, n) {\n for (let i = 0; i < 16; i++)\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n o[15] &= 0x7fff;\n }\n static A(o, a, b) {\n for (let i = 0; i < 16; i++)\n o[i] = a[i] + b[i];\n }\n static Z(o, a, b) {\n for (let i = 0; i < 16; i++)\n o[i] = a[i] - b[i];\n }\n static M(o, a, b) {\n let 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];\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n // first car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n // second car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n }\n static S(o, a) {\n this.M(o, a, a);\n }\n static inv25519(o, i) {\n const c = this.gf();\n for (let a = 0; a < 16; a++)\n c[a] = i[a];\n for (let a = 253; a >= 0; a--) {\n this.S(c, c);\n if (a !== 2 && a !== 4)\n this.M(c, c, i);\n }\n for (let a = 0; a < 16; a++)\n o[a] = c[a];\n }\n static pow2523(o, i) {\n const c = this.gf();\n for (let a = 0; a < 16; a++)\n c[a] = i[a];\n for (let a = 250; a >= 0; a--) {\n this.S(c, c);\n if (a !== 1)\n this.M(c, c, i);\n }\n for (let a = 0; a < 16; a++)\n o[a] = c[a];\n }\n // Note: difference from TweetNaCl - BLAKE2b used to hash instead of SHA-512.\n static crypto_hash(out, m, n) {\n const input = new Uint8Array(n);\n for (let i = 0; i < n; ++i)\n input[i] = m[i];\n const hash = new Blake2b(64).update(m).digest();\n for (let i = 0; i < 64; ++i)\n out[i] = hash[i];\n return 0;\n }\n static add(p, q) {\n const a = this.gf();\n const b = this.gf();\n const c = this.gf();\n const d = this.gf();\n const e = this.gf();\n const f = this.gf();\n const g = this.gf();\n const h = this.gf();\n const t = this.gf();\n this.Z(a, p[1], p[0]);\n this.Z(t, q[1], q[0]);\n this.M(a, a, t);\n this.A(b, p[0], p[1]);\n this.A(t, q[0], q[1]);\n this.M(b, b, t);\n this.M(c, p[3], q[3]);\n this.M(c, c, this.D2);\n this.M(d, p[2], q[2]);\n this.A(d, d, d);\n this.Z(e, b, a);\n this.Z(f, d, c);\n this.A(g, d, c);\n this.A(h, b, a);\n this.M(p[0], e, f);\n this.M(p[1], h, g);\n this.M(p[2], g, f);\n this.M(p[3], e, h);\n }\n static cswap(p, q, b) {\n for (let i = 0; i < 4; i++) {\n this.sel25519(p[i], q[i], b);\n }\n }\n static pack(r, p) {\n const tx = this.gf();\n const ty = this.gf();\n const zi = this.gf();\n this.inv25519(zi, p[2]);\n this.M(tx, p[0], zi);\n this.M(ty, p[1], zi);\n this.pack25519(r, ty);\n r[31] ^= this.par25519(tx) << 7;\n }\n static scalarmult(p, q, s) {\n this.set25519(p[0], this.gf0);\n this.set25519(p[1], this.gf1);\n this.set25519(p[2], this.gf1);\n this.set25519(p[3], this.gf0);\n for (let i = 255; i >= 0; --i) {\n const b = (s[(i / 8) | 0] >> (i & 7)) & 1;\n this.cswap(p, q, b);\n this.add(q, p);\n this.add(p, p);\n this.cswap(p, q, b);\n }\n }\n static scalarbase(p, s) {\n const q = [this.gf(), this.gf(), this.gf(), this.gf()];\n this.set25519(q[0], this.X);\n this.set25519(q[1], this.Y);\n this.set25519(q[2], this.gf1);\n this.M(q[3], this.X, this.Y);\n this.scalarmult(p, q, s);\n }\n static L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10\n ]);\n static modL(r, x) {\n let carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * this.L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * this.L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++)\n x[j] -= carry * this.L[j];\n for (i = 0; i < 32; i++) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n }\n static reduce(r) {\n let x = new Float64Array(64);\n for (let i = 0; i < 64; i++)\n x[i] = r[i];\n for (let i = 0; i < 64; i++)\n r[i] = 0;\n this.modL(r, x);\n }\n // Note: difference from C - smlen returned, not passed as argument.\n static crypto_sign(sm, m, n, sk, pk) {\n const d = new Uint8Array(64);\n const h = new Uint8Array(64);\n const r = new Uint8Array(64);\n const x = new Float64Array(64);\n const p = [this.gf(), this.gf(), this.gf(), this.gf()];\n this.crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const smlen = n + 64;\n for (let i = 0; i < n; i++)\n sm[64 + i] = m[i];\n for (let i = 0; i < 32; i++)\n sm[32 + i] = d[32 + i];\n this.crypto_hash(r, sm.subarray(32), n + 32);\n this.reduce(r);\n this.scalarbase(p, r);\n this.pack(sm, p);\n for (let i = 0; i < 32; i++)\n sm[i + 32] = pk[i];\n this.crypto_hash(h, sm, n + 64);\n this.reduce(h);\n for (let i = 0; i < 64; i++)\n x[i] = 0;\n for (let i = 0; i < 32; i++)\n x[i] = r[i];\n for (let i = 0; i < 32; i++) {\n for (let j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n this.modL(sm.subarray(32), x);\n return smlen;\n }\n static unpackneg(r, p) {\n const t = this.gf();\n const chk = this.gf();\n const num = this.gf();\n const den = this.gf();\n const den2 = this.gf();\n const den4 = this.gf();\n const den6 = this.gf();\n this.set25519(r[2], this.gf1);\n this.unpack25519(r[1], p);\n this.S(num, r[1]);\n this.M(den, num, this.D);\n this.Z(num, num, r[2]);\n this.A(den, r[2], den);\n this.S(den2, den);\n this.S(den4, den2);\n this.M(den6, den4, den2);\n this.M(t, den6, num);\n this.M(t, t, den);\n this.pow2523(t, t);\n this.M(t, t, num);\n this.M(t, t, den);\n this.M(t, t, den);\n this.M(r[0], t, den);\n this.S(chk, r[0]);\n this.M(chk, chk, den);\n if (this.neq25519(chk, num))\n this.M(r[0], r[0], this.I);\n this.S(chk, r[0]);\n this.M(chk, chk, den);\n if (this.neq25519(chk, num))\n return -1;\n if (this.par25519(r[0]) === (p[31] >> 7))\n this.Z(r[0], this.gf0, r[0]);\n this.M(r[3], r[0], r[1]);\n return 0;\n }\n static crypto_sign_open(m, sm, n, pk) {\n const t = new Uint8Array(32);\n const h = new Uint8Array(64);\n const p = [this.gf(), this.gf(), this.gf(), this.gf()];\n const q = [this.gf(), this.gf(), this.gf(), this.gf()];\n if (n < 64)\n return -1;\n if (this.unpackneg(q, pk))\n return -1;\n for (let i = 0; i < n; i++)\n m[i] = sm[i];\n for (let i = 0; i < 32; i++)\n m[i + 32] = pk[i];\n this.crypto_hash(h, m, n);\n this.reduce(h);\n this.scalarmult(p, q, h);\n this.scalarbase(q, sm.subarray(32));\n this.add(p, q);\n this.pack(t, p);\n n -= 64;\n if (this.crypto_verify_32(sm, 0, t, 0)) {\n for (let i = 0; i < n; i++)\n m[i] = 0;\n return -1;\n }\n for (let i = 0; i < n; i++)\n m[i] = sm[i + 64];\n return n;\n }\n static crypto_sign_BYTES = 64;\n static crypto_sign_PUBLICKEYBYTES = 32;\n static crypto_sign_SECRETKEYBYTES = 32;\n static crypto_sign_SEEDBYTES = 32;\n /* High-level API */\n static checkArrayTypes(...args) {\n for (let i = 0; i < args.length; i++) {\n if (!(args[i] instanceof Uint8Array))\n throw new TypeError(`expected Uint8Array; received ${args[i].constructor?.name ?? typeof args[i]}`);\n }\n }\n static parseHex(hex) {\n if (hex.length % 2 === 1)\n hex = `0${hex}`;\n const arr = hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16));\n return Uint8Array.from(arr ?? []);\n }\n static hexify(buf) {\n let str = '';\n for (let i = 0; i < buf.length; i++) {\n if (typeof buf[i] !== 'number')\n throw new TypeError(`expected number to convert to hex; received ${typeof buf[i]}`);\n if (buf[i] < 0 || buf[i] > 255)\n throw new RangeError(`expected byte value 0-255; received ${buf[i]}`);\n str += buf[i].toString(16).padStart(2, '0');\n }\n return str;\n }\n static sign(msg, secretKey) {\n this.checkArrayTypes(msg, secretKey);\n if (secretKey.length !== this.crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(this.crypto_sign_BYTES + msg.length);\n const publicKey = this.parseHex(this.convert(secretKey));\n this.crypto_sign(signedMsg, msg, msg.length, secretKey, publicKey);\n return signedMsg;\n }\n static open(signedMsg, publicKey) {\n this.checkArrayTypes(signedMsg, publicKey);\n if (publicKey.length !== this.crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n const tmp = new Uint8Array(signedMsg.length);\n var mlen = this.crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);\n if (mlen < 0)\n return new Uint8Array(0);\n var m = new Uint8Array(mlen);\n for (var i = 0; i < m.length; i++)\n m[i] = tmp[i];\n return m;\n }\n static detached(msg, secretKey) {\n var signedMsg = this.sign(msg, secretKey);\n var sig = new Uint8Array(this.crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++)\n sig[i] = signedMsg[i];\n return this.hexify(sig).toUpperCase();\n }\n static verify(msg, sig, publicKey) {\n this.checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== this.crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== this.crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n const sm = new Uint8Array(this.crypto_sign_BYTES + msg.length);\n const m = new Uint8Array(this.crypto_sign_BYTES + msg.length);\n for (let i = 0; i < this.crypto_sign_BYTES; i++)\n sm[i] = sig[i];\n for (let i = 0; i < msg.length; i++)\n sm[i + this.crypto_sign_BYTES] = msg[i];\n return (this.crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n }\n static convert(seed) {\n if (typeof seed === 'string')\n seed = this.parseHex(seed);\n this.checkArrayTypes(seed);\n if (seed.length !== this.crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n const pk = new Uint8Array(this.crypto_sign_PUBLICKEYBYTES);\n const p = [this.gf(), this.gf(), this.gf(), this.gf()];\n const hash = new Blake2b(64).update(seed).digest();\n hash[0] &= 248;\n hash[31] &= 127;\n hash[31] |= 64;\n this.scalarbase(p, hash);\n this.pack(pk, p);\n return this.hexify(pk).toUpperCase();\n }\n}\nexport default `\r\n\tconst Blake2b = ${Blake2b}\r\n\tconst WorkerInterface = ${WorkerInterface}\r\n\tconst NanoNaCl = ${NanoNaCl}\r\n`;\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { Blake2b } from './blake2b.js';\nimport { ACCOUNT_KEY_LENGTH, ALPHABET, PREFIX, PREFIX_LEGACY } from './constants.js';\nimport { base32, bytes, hex } from './convert.js';\nimport { Rpc } from './rpc.js';\nimport { Safe } from './safe.js';\nimport { NanoNaCl } from './workers/nano-nacl.js';\n/**\n* Represents a single Nano address and the associated public key. To include the\n* matching private key, it must be known at the time of object instantiation.\n* The frontier, balance, and representative for the account can also be set or\n* be fetched from the network.\n*/\nexport class Account {\n static #isInternal = false;\n #a;\n #pub;\n #prv;\n #i;\n #f;\n #b;\n #r;\n #rep;\n #w;\n #s;\n get address() { return `${PREFIX}${this.#a}`; }\n get publicKey() { return this.#pub; }\n get privateKey() { return this.#prv; }\n get index() { return this.#i; }\n get frontier() { return this.#f; }\n get balance() { return this.#b; }\n get receivable() { return this.#r; }\n get representative() { return this.#rep; }\n get weight() { return this.#w; }\n set frontier(v) { this.#f = v; }\n set balance(v) { this.#b = v ? BigInt(v) : undefined; }\n set receivable(v) { this.#r = v ? BigInt(v) : undefined; }\n set representative(v) {\n if (v?.constructor === Account) {\n this.#rep = v;\n }\n else if (typeof v === 'string') {\n this.#rep = Account.fromAddress(v);\n }\n else {\n throw new TypeError(`Invalid argument for account representative: ${v}`);\n }\n }\n set weight(v) { this.#w = v ? BigInt(v) : undefined; }\n constructor(address, publicKey, privateKey, index) {\n if (!Account.#isInternal) {\n throw new Error(`Account cannot be instantiated directly. Use factory methods instead.`);\n }\n if (index !== undefined && typeof index !== 'number') {\n throw new TypeError(`Invalid index ${index} when creating Account ${address}`);\n }\n this.#a = address\n .replace(PREFIX, '')\n .replace(PREFIX_LEGACY, '');\n this.#pub = publicKey;\n this.#prv = privateKey ?? null;\n this.#i = index;\n this.#s = new Safe();\n Account.#isInternal = false;\n }\n /**\n * Instantiates an Account object from its Nano address.\n *\n * @param {string} address - Address of the account\n * @param {number} [index] - Account number used when deriving the address\n * @returns {Account} The instantiated Account object\n */\n static fromAddress(address, index) {\n Account.#isInternal = true;\n Account.validate(address);\n const publicKey = Account.#addressToKey(address);\n const account = new this(address, publicKey, undefined, index);\n return account;\n }\n /**\n * Instantiates an Account object from its public key.\n *\n * @param {string} publicKey - Public key of the account\n * @param {number} [index] - Account number used when deriving the key\n * @returns {Account} The instantiated Account object\n */\n static fromPublicKey(publicKey, index) {\n Account.#isInternal = true;\n Account.#validateKey(publicKey);\n const address = Account.#keyToAddress(publicKey);\n const account = new this(address, publicKey, undefined, index);\n return account;\n }\n /**\n * Instantiates an Account object from its private key. The\n * corresponding public key will automatically be derived and saved.\n *\n * @param {string} privateKey - Private key of the account\n * @param {number} [index] - Account number used when deriving the key\n * @returns {Account} A new Account object\n */\n static fromPrivateKey(privateKey, index) {\n Account.#isInternal = true;\n Account.#validateKey(privateKey);\n const publicKey = NanoNaCl.convert(privateKey);\n const account = Account.fromPublicKey(publicKey, index);\n account.#prv = privateKey.toUpperCase();\n return account;\n }\n /**\n * Instantiates an Account object from its public and private\n * keys.\n *\n * WARNING: The validity of the keys is checked, but they are assumed to have\n * been precalculated. Whether they are an actual matching pair is NOT checked!\n * If unsure, use `Account.fromPrivateKey(key)` instead.\n *\n * @param {string} publicKey - Public key of the account\n * @param {string} privateKey - Private key of the account\n * @param {number} [index] - Account number used when deriving the key\n * @returns {Account} The instantiated Account object\n */\n static fromKeypair(privateKey, publicKey, index) {\n Account.#isInternal = true;\n Account.#validateKey(privateKey);\n const account = Account.fromPublicKey(publicKey, index);\n account.#prv = privateKey.toUpperCase();\n return account;\n }\n async lock(passkey) {\n try {\n if (this.#prv != null) {\n await this.#s.put(this.#pub, passkey, this.#prv);\n }\n }\n catch (err) {\n console.error(`Failed to lock account ${this.address}`, err);\n return false;\n }\n this.#prv = null;\n return true;\n }\n async unlock(passkey) {\n try {\n this.#prv = await this.#s.get(this.#pub, passkey);\n }\n catch (err) {\n console.error(`Failed to unlock account ${this.address}`, err);\n return false;\n }\n return true;\n }\n /**\n * Validates a Nano address with 'nano' and 'xrb' prefixes\n * Derived from https://github.com/alecrios/nano-address-validator\n *\n * @param {string} address - Nano address to validate\n * @throws Error if address is undefined, not a string, or an invalid format\n */\n static validate(address) {\n if (address === undefined) {\n throw new ReferenceError('Address is undefined.');\n }\n if (typeof address !== 'string') {\n throw new TypeError('Address must be a string.');\n }\n const pattern = new RegExp(`^(${PREFIX}|${PREFIX_LEGACY})[13]{1}[${ALPHABET}]{59}$`);\n if (!pattern.test(address)) {\n throw new RangeError('Invalid address format');\n }\n const expectedChecksum = address.slice(-8);\n const keyBase32 = address.slice(address.indexOf('_') + 1, -8);\n const keyBuf = base32.toBytes(keyBase32);\n const actualChecksumBuf = new Blake2b(5).update(keyBuf).digest();\n actualChecksumBuf.reverse();\n const actualChecksum = bytes.toBase32(actualChecksumBuf);\n if (expectedChecksum !== actualChecksum) {\n throw new Error('Incorrect address checksum');\n }\n }\n /**\n * Refreshes the account from its current state on the network.\n *\n * A successful response sets the balance, frontier, and representative\n * properties.\n *\n * @param {Rpc|string|URL} rpc - RPC node information required to call `account_info`\n */\n async refresh(rpc) {\n if (typeof rpc === 'string' || rpc.constructor === URL) {\n rpc = new Rpc(rpc);\n }\n if (rpc.constructor !== Rpc) {\n throw new TypeError('RPC must be a valid node');\n }\n const data = {\n \"account\": this.address,\n \"receivable\": \"true\",\n \"representative\": \"true\",\n \"weight\": \"true\"\n };\n const { balance, frontier, receivable, representative, weight } = await rpc.call('account_info', data);\n if (frontier == null) {\n throw new Error('Account not found');\n }\n this.#b = BigInt(balance);\n this.#f = frontier;\n this.#r = BigInt(receivable);\n this.#rep = Account.fromAddress(representative);\n this.#w = BigInt(weight);\n }\n static #addressToKey(v) {\n const publicKeyBytes = base32.toBytes(v.slice(-60, -8));\n const checksumBytes = base32.toBytes(v.slice(-8));\n const rechecksumBytes = new Blake2b(5).update(publicKeyBytes).digest().reverse();\n if (bytes.toHex(checksumBytes) !== bytes.toHex(rechecksumBytes)) {\n throw new Error('Checksum mismatch in address');\n }\n return bytes.toHex(publicKeyBytes);\n }\n static #keyToAddress(publicKey) {\n const publicKeyBytes = hex.toBytes(publicKey);\n const checksumBytes = new Blake2b(5).update(publicKeyBytes).digest().reverse();\n const encodedPublicKey = bytes.toBase32(publicKeyBytes);\n const encodedChecksum = bytes.toBase32(checksumBytes);\n return `${PREFIX}${encodedPublicKey}${encodedChecksum}`;\n }\n static #validateKey(key) {\n if (key === undefined) {\n throw new TypeError(`Key is undefined`);\n }\n if (typeof key !== 'string') {\n throw new TypeError(`Key must be a string`);\n }\n if (key.length !== ACCOUNT_KEY_LENGTH) {\n throw new TypeError(`Key must be ${ACCOUNT_KEY_LENGTH} characters`);\n }\n if (!/^[0-9a-fA-F]+$/i.test(key)) {\n throw new RangeError('Key is not a valid hexadecimal value');\n }\n }\n}\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { WorkerInterface } from '../pool.js';\nexport class Bip44Ckd extends WorkerInterface {\n static BIP44_COIN_NANO = 165;\n static BIP44_PURPOSE = 44;\n static HARDENED_OFFSET = 0x80000000;\n static SLIP10_ED25519 = 'ed25519 seed';\n static {\n Bip44Ckd.listen();\n }\n static async work(data) {\n for (const d of data) {\n if (d.coin != null && d.coin !== this.BIP44_PURPOSE) {\n d.privateKey = await this.ckd(d.seed, d.coin, d.index);\n }\n else {\n d.privateKey = await this.nanoCKD(d.seed, d.index);\n }\n }\n return data;\n }\n /**\n * Derives a private child key following the BIP-32 and BIP-44 derivation path\n * registered to the Nano block lattice. Only hardened child keys are defined.\n *\n * @param {string} seed - Hexadecimal seed derived from mnemonic phrase\n * @param {number} index - Account number between 0 and 2^31-1\n * @returns {Promise} Private child key for the account\n */\n static async nanoCKD(seed, index) {\n if (!Number.isSafeInteger(index) || index < 0 || index > 0x7fffffff) {\n throw new RangeError(`Invalid child key index 0x${index.toString(16)}`);\n }\n return await this.ckd(seed, this.BIP44_COIN_NANO, index);\n }\n /**\n * Derives a private child key for a coin by following the specified BIP-32 and\n * BIP-44 derivation path. Purpose is always 44'. Only hardened child keys are\n * defined.\n *\n * @param {string} seed - Hexadecimal seed derived from mnemonic phrase\n * @param {number} coin - Number registered to a specific coin in SLIP-044\n * @param {number} index - Account number between 0 and 2^31-1\n * @returns {Promise} Private child key for the account\n */\n static async ckd(seed, coin, index) {\n if (seed.length < 32 || seed.length > 128) {\n throw new RangeError(`Invalid seed length`);\n }\n if (!Number.isSafeInteger(index) || index < 0 || index > 0x7fffffff) {\n throw new RangeError(`Invalid child key index 0x${index.toString(16)}`);\n }\n const masterKey = await this.slip10(this.SLIP10_ED25519, seed);\n const purposeKey = await this.CKDpriv(masterKey, this.BIP44_PURPOSE + this.HARDENED_OFFSET);\n const coinKey = await this.CKDpriv(purposeKey, coin + this.HARDENED_OFFSET);\n const accountKey = await this.CKDpriv(coinKey, index + this.HARDENED_OFFSET);\n const privateKey = new Uint8Array(accountKey.privateKey.buffer);\n let hex = '';\n for (let i = 0; i < privateKey.length; i++) {\n hex += privateKey[i].toString(16).padStart(2, '0');\n }\n return hex;\n }\n static async slip10(curve, S) {\n const key = new TextEncoder().encode(curve);\n const data = new Uint8Array(64);\n data.set(S.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));\n const I = await this.hmac(key, data);\n const IL = new DataView(I.buffer.slice(0, I.length / 2));\n const IR = new DataView(I.buffer.slice(I.length / 2));\n return ({ privateKey: IL, chainCode: IR });\n }\n static async CKDpriv({ privateKey, chainCode }, index) {\n const key = new Uint8Array(chainCode.buffer);\n const data = new Uint8Array(37);\n data.set([0]);\n data.set(this.ser256(privateKey), 1);\n data.set(this.ser32(index), 33);\n const I = await this.hmac(key, data);\n const IL = new DataView(I.buffer.slice(0, I.length / 2));\n const IR = new DataView(I.buffer.slice(I.length / 2));\n return ({ privateKey: IL, chainCode: IR });\n }\n static ser32(integer) {\n if (typeof integer !== 'number') {\n throw new TypeError(`Expected a number, received ${typeof integer}`);\n }\n if (integer > 0xffffffff) {\n throw new RangeError(`Expected 32-bit integer, received ${integer.toString(2).length}-bit value: ${integer}`);\n }\n const view = new DataView(new ArrayBuffer(4));\n view.setUint32(0, integer, false);\n return new Uint8Array(view.buffer);\n }\n static ser256(integer) {\n if (integer.constructor !== DataView) {\n throw new TypeError(`Expected DataView, received ${typeof integer}`);\n }\n if (integer.byteLength > 32) {\n throw new RangeError(`Expected 32-byte integer, received ${integer.byteLength}-byte value: ${integer}`);\n }\n return new Uint8Array(integer.buffer);\n }\n static async hmac(key, data) {\n const { subtle } = globalThis.crypto;\n const pk = await subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-512' }, false, ['sign']);\n const signature = await subtle.sign('HMAC', pk, data);\n return new Uint8Array(signature);\n }\n}\nexport default `\n\tconst WorkerInterface = ${WorkerInterface}\n\tconst Bip44Ckd = ${Bip44Ckd}\n`;\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n// Based on nano-webgl-pow by Ben Green (numtel) \n// https://github.com/numtel/nano-webgl-pow\nimport { WorkerInterface } from '../pool.js';\nexport class Pow extends WorkerInterface {\n static {\n Pow.listen();\n }\n /**\n * Calculates proof-of-work as described by the Nano cryptocurrency protocol.\n *\n * @param {any[]} data - Array of hashes and minimum thresholds\n * @returns Promise for proof-of-work attached to original array objects\n */\n static async work(data) {\n return new Promise(async (resolve, reject) => {\n for (const d of data) {\n try {\n d.work = await this.find(d.hash, d.threshold);\n }\n catch (err) {\n reject(err);\n }\n }\n resolve(data);\n });\n }\n /**\n * Finds a nonce that satisfies the Nano proof-of-work requirements.\n *\n * @param {string} hashHex - Hexadecimal hash of previous block, or public key for new accounts\n * @param {number} [threshold=0xfffffff8] - Difficulty of proof-of-work calculation\n */\n static async find(hash, threshold = 0xfffffff8) {\n return new Promise(resolve => {\n this.#calculate(hash, resolve, threshold);\n });\n }\n // Vertex Shader\n static #vsSource = `#version 300 es\n#pragma vscode_glsllint_stage: vert\nprecision highp float;\nlayout (location=0) in vec4 position;\nlayout (location=1) in vec2 uv;\n\nout vec2 uv_pos;\n\nvoid main() {\n\tuv_pos = uv;\n\tgl_Position = position;\n}`;\n // Fragment shader\n static #fsSource = `#version 300 es\n#pragma vscode_glsllint_stage: frag\nprecision highp float;\nprecision highp int;\n\nin vec2 uv_pos;\nout vec4 fragColor;\n\n// blockhash - array of precalculated block hash components\n// threshold - 0xfffffff8 for send/change blocks, 0xfffffe00 for all else\n// workload - Defines canvas size\nlayout(std140) uniform UBO {\n\tuint blockhash[8];\n\tuint threshold;\n\tfloat workload;\n};\n\n// Random work values\n// First 2 bytes will be overwritten by texture pixel position\n// Second 2 bytes will be modified if the canvas size is greater than 256x256\n// Last 4 bytes remain as generated externally\nlayout(std140) uniform WORK {\n\tuvec4 work[2];\n};\n\n// Defined separately from uint v[32] below as the original value is required\n// to calculate the second uint32 of the digest for threshold comparison\nconst uint BLAKE2B_IV32_1 = 0x6A09E667u;\n\n// Both buffers represent 16 uint64s as 32 uint32s\n// because that's what GLSL offers, just like Javascript\n\n// Compression buffer, intialized to 2 instances of the initialization vector\n// The following values have been modified from the BLAKE2B_IV:\n// OUTLEN is constant 8 bytes\n// v[0] ^= 0x01010000u ^ uint(OUTLEN);\n// INLEN is constant 40 bytes: work value (8) + block hash (32)\n// v[24] ^= uint(INLEN);\n// It's always the \"last\" compression at this INLEN\n// v[28] = ~v[28];\n// v[29] = ~v[29];\nuint v[32] = uint[32](\n\t0xF2BDC900u, 0x6A09E667u, 0x84CAA73Bu, 0xBB67AE85u,\n\t0xFE94F82Bu, 0x3C6EF372u, 0x5F1D36F1u, 0xA54FF53Au,\n\t0xADE682D1u, 0x510E527Fu, 0x2B3E6C1Fu, 0x9B05688Cu,\n\t0xFB41BD6Bu, 0x1F83D9ABu, 0x137E2179u, 0x5BE0CD19u,\n\t0xF3BCC908u, 0x6A09E667u, 0x84CAA73Bu, 0xBB67AE85u,\n\t0xFE94F82Bu, 0x3C6EF372u, 0x5F1D36F1u, 0xA54FF53Au,\n\t0xADE682F9u, 0x510E527Fu, 0x2B3E6C1Fu, 0x9B05688Cu,\n\t0x04BE4294u, 0xE07C2654u, 0x137E2179u, 0x5BE0CD19u\n);\n// Input data buffer\nuint m[32];\n\n// These are offsets into the input data buffer for each mixing step.\n// They are multiplied by 2 from the original SIGMA values in\n// the C reference implementation, which refered to uint64s.\nconst uint SIGMA82[192] = uint[192](\n\t0u,2u,4u,6u,8u,10u,12u,14u,16u,18u,20u,22u,24u,26u,28u,30u,\n\t28u,20u,8u,16u,18u,30u,26u,12u,2u,24u,0u,4u,22u,14u,10u,6u,\n\t22u,16u,24u,0u,10u,4u,30u,26u,20u,28u,6u,12u,14u,2u,18u,8u,\n\t14u,18u,6u,2u,26u,24u,22u,28u,4u,12u,10u,20u,8u,0u,30u,16u,\n\t18u,0u,10u,14u,4u,8u,20u,30u,28u,2u,22u,24u,12u,16u,6u,26u,\n\t4u,24u,12u,20u,0u,22u,16u,6u,8u,26u,14u,10u,30u,28u,2u,18u,\n\t24u,10u,2u,30u,28u,26u,8u,20u,0u,14u,12u,6u,18u,4u,16u,22u,\n\t26u,22u,14u,28u,24u,2u,6u,18u,10u,0u,30u,8u,16u,12u,4u,20u,\n\t12u,30u,28u,18u,22u,6u,0u,16u,24u,4u,26u,14u,2u,8u,20u,10u,\n\t20u,4u,16u,8u,14u,12u,2u,10u,30u,22u,18u,28u,6u,24u,26u,0u,\n\t0u,2u,4u,6u,8u,10u,12u,14u,16u,18u,20u,22u,24u,26u,28u,30u,\n\t28u,20u,8u,16u,18u,30u,26u,12u,2u,24u,0u,4u,22u,14u,10u,6u\n);\n\n// 64-bit unsigned addition within the compression buffer\n// Sets v[a,a+1] += b\n// b0 is the low 32 bits of b, b1 represents the high 32 bits\nvoid add_uint64 (uint a, uint b0, uint b1) {\n\tuint o0 = v[a] + b0;\n\tuint o1 = v[a+1u] + b1;\n\tif (v[a] > 0xFFFFFFFFu - b0) { // did low 32 bits overflow?\n\t\to1++;\n\t}\n\tv[a] = o0;\n\tv[a+1u] = o1;\n}\n\n// G Mixing function\nvoid B2B_G (uint a, uint b, uint c, uint d, uint ix, uint iy) {\n\tadd_uint64(a, v[b], v[b+1u]);\n\tadd_uint64(a, m[ix], m[ix+1u]);\n\n\t// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n\tuint xor0 = v[d] ^ v[a];\n\tuint xor1 = v[d+1u] ^ v[a+1u];\n\tv[d] = xor1;\n\tv[d+1u] = xor0;\n\n\tadd_uint64(c, v[d], v[d+1u]);\n\n\t// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n\txor0 = v[b] ^ v[c];\n\txor1 = v[b+1u] ^ v[c+1u];\n\tv[b] = (xor0 >> 24u) ^ (xor1 << 8u);\n\tv[b+1u] = (xor1 >> 24u) ^ (xor0 << 8u);\n\n\tadd_uint64(a, v[b], v[b+1u]);\n\tadd_uint64(a, m[iy], m[iy+1u]);\n\n\t// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n\txor0 = v[d] ^ v[a];\n\txor1 = v[d+1u] ^ v[a+1u];\n\tv[d] = (xor0 >> 16u) ^ (xor1 << 16u);\n\tv[d+1u] = (xor1 >> 16u) ^ (xor0 << 16u);\n\n\tadd_uint64(c, v[d], v[d+1u]);\n\n\t// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n\txor0 = v[b] ^ v[c];\n\txor1 = v[b+1u] ^ v[c+1u];\n\tv[b] = (xor1 >> 31u) ^ (xor0 << 1u);\n\tv[b+1u] = (xor0 >> 31u) ^ (xor1 << 1u);\n}\n\nvoid main() {\n\tint i;\n\tuvec4 u_work0 = work[0u];\n\tuvec4 u_work1 = work[1u];\n\tuint uv_x = uint(uv_pos.x * workload);\n\tuint uv_y = uint(uv_pos.y * workload);\n\tuint x_pos = uv_x % 256u;\n\tuint y_pos = uv_y % 256u;\n\tuint x_index = (uv_x - x_pos) / 256u;\n\tuint y_index = (uv_y - y_pos) / 256u;\n\n\t// First 2 work bytes are the x,y pos within the 256x256 area, the next\n\t// two bytes are modified from the random generated value, XOR'd with\n\t// the x,y area index of where this pixel is located\n\tm[0u] = (x_pos ^ (y_pos << 8u) ^ ((u_work0.b ^ x_index) << 16u) ^ ((u_work0.a ^ y_index) << 24u));\n\n\t// Remaining bytes are un-modified from the random generated value\n\tm[1u] = (u_work1.r ^ (u_work1.g << 8u) ^ (u_work1.b << 16u) ^ (u_work1.a << 24u));\n\n\t// Block hash\n\tfor (uint i = 0u; i < 8u; i = i + 1u) {\n\t\tm[i+2u] = blockhash[i];\n\t}\n\n\t// twelve rounds of mixing\n\tfor(uint i = 0u; i < 12u; i = i + 1u) {\n\t\tB2B_G(0u, 8u, 16u, 24u, SIGMA82[i * 16u + 0u], SIGMA82[i * 16u + 1u]);\n\t\tB2B_G(2u, 10u, 18u, 26u, SIGMA82[i * 16u + 2u], SIGMA82[i * 16u + 3u]);\n\t\tB2B_G(4u, 12u, 20u, 28u, SIGMA82[i * 16u + 4u], SIGMA82[i * 16u + 5u]);\n\t\tB2B_G(6u, 14u, 22u, 30u, SIGMA82[i * 16u + 6u], SIGMA82[i * 16u + 7u]);\n\t\tB2B_G(0u, 10u, 20u, 30u, SIGMA82[i * 16u + 8u], SIGMA82[i * 16u + 9u]);\n\t\tB2B_G(2u, 12u, 22u, 24u, SIGMA82[i * 16u + 10u], SIGMA82[i * 16u + 11u]);\n\t\tB2B_G(4u, 14u, 16u, 26u, SIGMA82[i * 16u + 12u], SIGMA82[i * 16u + 13u]);\n\t\tB2B_G(6u, 8u, 18u, 28u, SIGMA82[i * 16u + 14u], SIGMA82[i * 16u + 15u]);\n\t}\n\n\t// Pixel data is multipled by threshold test result (0 or 1)\n\t// First 4 bytes insignificant, only calculate digest of second 4 bytes\n\tif ((BLAKE2B_IV32_1 ^ v[1u] ^ v[17u]) > threshold) {\n\t\tfragColor = vec4(\n\t\t\tfloat(x_index + 1u)/255.0, // +1 to distinguish from 0 (unsuccessful) pixels\n\t\t\tfloat(y_index + 1u)/255.0, // Same as previous\n\t\t\tfloat(x_pos)/255.0, // Return the 2 custom bytes used in work value\n\t\t\tfloat(y_pos)/255.0 // Second custom byte\n\t\t);\n\t} else {\n \t\tdiscard;\n\t}\n}`;\n /** Used to set canvas size. Must be a multiple of 256. */\n static #WORKLOAD = 256 * Math.max(1, Math.floor(navigator.hardwareConcurrency));\n static #hexify(arr) {\n let out = '';\n for (let i = arr.length - 1; i >= 0; i--) {\n out += arr[i].toString(16).padStart(2, '0');\n }\n return out;\n }\n static #gl;\n static #program;\n static #vertexShader;\n static #fragmentShader;\n static #positionBuffer;\n static #uvBuffer;\n static #uboBuffer;\n static #workBuffer;\n static #query;\n static #pixels;\n // Vertex Positions, 2 triangles\n static #positions = new Float32Array([\n -1, -1, 0, -1, 1, 0, 1, 1, 0,\n 1, -1, 0, 1, 1, 0, -1, -1, 0\n ]);\n // Texture Positions\n static #uvPosArray = new Float32Array([\n 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1\n ]);\n // Compile\n static {\n this.#gl = new OffscreenCanvas(this.#WORKLOAD, this.#WORKLOAD).getContext('webgl2');\n if (this.#gl == null)\n throw new Error('WebGL 2 is required');\n this.#gl.clearColor(0, 0, 0, 1);\n this.#program = this.#gl.createProgram();\n if (this.#program == null)\n throw new Error('Failed to create shader program');\n this.#vertexShader = this.#gl.createShader(this.#gl.VERTEX_SHADER);\n if (this.#vertexShader == null)\n throw new Error('Failed to create vertex shader');\n this.#gl.shaderSource(this.#vertexShader, this.#vsSource);\n this.#gl.compileShader(this.#vertexShader);\n if (!this.#gl.getShaderParameter(this.#vertexShader, this.#gl.COMPILE_STATUS))\n throw new Error(this.#gl.getShaderInfoLog(this.#vertexShader) ?? `Failed to compile vertex shader`);\n this.#fragmentShader = this.#gl.createShader(this.#gl.FRAGMENT_SHADER);\n if (this.#fragmentShader == null)\n throw new Error('Failed to create fragment shader');\n this.#gl.shaderSource(this.#fragmentShader, this.#fsSource);\n this.#gl.compileShader(this.#fragmentShader);\n if (!this.#gl.getShaderParameter(this.#fragmentShader, this.#gl.COMPILE_STATUS))\n throw new Error(this.#gl.getShaderInfoLog(this.#fragmentShader) ?? `Failed to compile fragment shader`);\n this.#gl.attachShader(this.#program, this.#vertexShader);\n this.#gl.attachShader(this.#program, this.#fragmentShader);\n this.#gl.linkProgram(this.#program);\n if (!this.#gl.getProgramParameter(this.#program, this.#gl.LINK_STATUS))\n throw new Error(this.#gl.getProgramInfoLog(this.#program) ?? `Failed to link program`);\n // Construct simple 2D geometry\n this.#gl.useProgram(this.#program);\n const triangleArray = this.#gl.createVertexArray();\n this.#gl.bindVertexArray(triangleArray);\n this.#positionBuffer = this.#gl.createBuffer();\n this.#gl.bindBuffer(this.#gl.ARRAY_BUFFER, this.#positionBuffer);\n this.#gl.bufferData(this.#gl.ARRAY_BUFFER, this.#positions, this.#gl.STATIC_DRAW);\n this.#gl.vertexAttribPointer(0, 3, this.#gl.FLOAT, false, 0, 0);\n this.#gl.enableVertexAttribArray(0);\n this.#uvBuffer = this.#gl.createBuffer();\n this.#gl.bindBuffer(this.#gl.ARRAY_BUFFER, this.#uvBuffer);\n this.#gl.bufferData(this.#gl.ARRAY_BUFFER, this.#uvPosArray, this.#gl.STATIC_DRAW);\n this.#gl.vertexAttribPointer(1, 2, this.#gl.FLOAT, false, 0, 0);\n this.#gl.enableVertexAttribArray(1);\n this.#uboBuffer = this.#gl.createBuffer();\n this.#gl.bindBuffer(this.#gl.UNIFORM_BUFFER, this.#uboBuffer);\n this.#gl.bufferData(this.#gl.UNIFORM_BUFFER, 144, this.#gl.DYNAMIC_DRAW);\n this.#gl.bindBuffer(this.#gl.UNIFORM_BUFFER, null);\n this.#gl.bindBufferBase(this.#gl.UNIFORM_BUFFER, 0, this.#uboBuffer);\n this.#gl.uniformBlockBinding(this.#program, this.#gl.getUniformBlockIndex(this.#program, 'UBO'), 0);\n this.#workBuffer = this.#gl.createBuffer();\n this.#gl.bindBuffer(this.#gl.UNIFORM_BUFFER, this.#workBuffer);\n this.#gl.bufferData(this.#gl.UNIFORM_BUFFER, 32, this.#gl.STREAM_DRAW);\n this.#gl.bindBuffer(this.#gl.UNIFORM_BUFFER, null);\n this.#gl.bindBufferBase(this.#gl.UNIFORM_BUFFER, 1, this.#workBuffer);\n this.#gl.uniformBlockBinding(this.#program, this.#gl.getUniformBlockIndex(this.#program, 'WORK'), 1);\n this.#pixels = new Uint8Array(this.#gl.drawingBufferWidth * this.#gl.drawingBufferHeight * 4);\n this.#query = this.#gl.createQuery();\n }\n static #calculate(hashHex, callback, threshold) {\n if (Pow.#gl == null)\n throw new Error('WebGL 2 is required');\n if (!/^[A-F-a-f0-9]{64}$/.test(hashHex))\n throw new Error(`invalid_hash ${hashHex}`);\n if (typeof threshold !== 'number')\n throw new TypeError(`Invalid threshold ${threshold}`);\n if (this.#gl == null)\n throw new Error('WebGL 2 is required');\n // Set up uniform buffer object\n const uboView = new DataView(new ArrayBuffer(144));\n for (let i = 0; i < 64; i += 8) {\n const uint32 = hashHex.slice(i, i + 8);\n uboView.setUint32(i * 2, parseInt(uint32, 16));\n }\n uboView.setUint32(128, threshold, true);\n uboView.setFloat32(132, Pow.#WORKLOAD - 1, true);\n Pow.#gl.bindBuffer(Pow.#gl.UNIFORM_BUFFER, Pow.#uboBuffer);\n Pow.#gl.bufferSubData(Pow.#gl.UNIFORM_BUFFER, 0, uboView);\n Pow.#gl.bindBuffer(Pow.#gl.UNIFORM_BUFFER, null);\n // Draw output until success or progressCallback says to stop\n const work = new Uint8Array(8);\n let start;\n const draw = () => {\n start = performance.now();\n if (Pow.#gl == null)\n throw new Error('WebGL 2 is required');\n if (Pow.#query == null)\n throw new Error('WebGL 2 is required to run queries');\n Pow.#gl.clear(Pow.#gl.COLOR_BUFFER_BIT);\n // Upload work buffer\n crypto.getRandomValues(work);\n Pow.#gl.bindBuffer(Pow.#gl.UNIFORM_BUFFER, Pow.#workBuffer);\n Pow.#gl.bufferSubData(Pow.#gl.UNIFORM_BUFFER, 0, Uint32Array.from(work));\n Pow.#gl.bindBuffer(Pow.#gl.UNIFORM_BUFFER, null);\n Pow.#gl.beginQuery(Pow.#gl.ANY_SAMPLES_PASSED_CONSERVATIVE, Pow.#query);\n Pow.#gl.drawArrays(Pow.#gl.TRIANGLES, 0, 6);\n Pow.#gl.endQuery(Pow.#gl.ANY_SAMPLES_PASSED_CONSERVATIVE);\n requestAnimationFrame(checkQueryResult);\n };\n function checkQueryResult() {\n if (Pow.#gl == null)\n throw new Error('WebGL 2 is required to check query results');\n if (Pow.#query == null)\n throw new Error('Query not found');\n console.log(`checking (${performance.now() - start} ms)`);\n if (Pow.#gl.getQueryParameter(Pow.#query, Pow.#gl.QUERY_RESULT_AVAILABLE)) {\n console.log(`AVAILABLE (${performance.now() - start} ms)`);\n const anySamplesPassed = Pow.#gl.getQueryParameter(Pow.#query, Pow.#gl.QUERY_RESULT);\n if (anySamplesPassed) {\n // A valid nonce was found\n readBackResult();\n }\n else {\n console.log(`not found (${performance.now() - start} ms)`);\n // No valid nonce found, start the next draw call\n requestAnimationFrame(draw);\n }\n }\n else {\n console.log(`not ready (${performance.now() - start} ms)`);\n // Query result not yet available, check again in the next frame\n requestAnimationFrame(checkQueryResult);\n }\n }\n function readBackResult() {\n if (Pow.#gl == null)\n throw new Error('WebGL 2 is required to check read results');\n Pow.#gl.readPixels(0, 0, Pow.#gl.drawingBufferWidth, Pow.#gl.drawingBufferHeight, Pow.#gl.RGBA, Pow.#gl.UNSIGNED_BYTE, Pow.#pixels);\n // Check the pixels for any success\n for (let i = 0; i < Pow.#pixels.length; i += 4) {\n if (Pow.#pixels[i] !== 0) {\n console.log(`FOUND (${performance.now() - start} ms)`);\n const hex = Pow.#hexify(work.subarray(4, 8)) + Pow.#hexify([\n Pow.#pixels[i + 2],\n Pow.#pixels[i + 3],\n work[2] ^ (Pow.#pixels[i] - 1),\n work[3] ^ (Pow.#pixels[i + 1] - 1)\n ]);\n // Return the work value with the custom bits\n typeof callback === 'function' && callback(hex);\n return;\n }\n }\n }\n draw();\n }\n}\nexport default `\n\tconst WorkerInterface = ${WorkerInterface}\n\tconst Pow = ${Pow}\n`;\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\n// BLAKE2b hashing implementation derived from nano-webgl-pow by Ben Green (https://github.com/numtel/nano-webgl-pow)\n/// \nimport { WorkerInterface } from '../pool.js';\nexport class PowGpu extends WorkerInterface {\n static {\n PowGpu.listen();\n }\n /**\n * Calculates proof-of-work as described by the Nano cryptocurrency protocol.\n *\n * @param {any[]} data - Array of hashes and minimum thresholds\n * @returns Promise for proof-of-work attached to original array objects\n */\n static async work(data) {\n return new Promise(async (resolve, reject) => {\n for (const d of data) {\n try {\n d.work = await this.find(d.hash, d.threshold);\n }\n catch (err) {\n reject(err);\n }\n }\n resolve(data);\n });\n }\n /**\n * Finds a nonce that satisfies the Nano proof-of-work requirements.\n *\n * @param {string} hash - Hexadecimal hash of previous block, or public key for new accounts\n * @param {number} [threshold=0xfffffff8] - Difficulty of proof-of-work calculation\n */\n static async find(hash, threshold = 0xfffffff8) {\n return new Promise(async (resolve) => {\n await this.#calculate(hash, resolve, threshold);\n });\n }\n // WebGPU Compute Shader\n static #shader = `\n\t\tstruct UBO {\n\t\t\tblockhash: array, 2>,\n\t\t\tthreshold: u32\n\t\t};\n\t\t@group(0) @binding(0) var ubo: UBO;\n\n\t\tstruct WORK {\n\t\t\tnonce: vec2,\n\t\t\tfound: atomic\n\t\t};\n\t\t@group(0) @binding(1) var work: WORK;\n\n\t\t/**\n\t\t* Defined separately from uint v[32] below as the original value is required\n\t\t* to calculate the second uint32 of the digest for threshold comparison\n\t\t*/\n\t\tconst BLAKE2B_IV32_1: u32 = 0x6A09E667u;\n\n\t\t/**\n\t\t* These are offsets into the input data buffer for each mixing step.\n\t\t* They are multiplied by 2 from the original SIGMA values in\n\t\t* the C reference implementation, which refered to uint64s.\n\t\t*/\n\t\tconst SIGMA82: array = array(\n\t\t\t0u,2u,4u,6u,8u,10u,12u,14u,16u,18u,20u,22u,24u,26u,28u,30u,\n\t\t\t28u,20u,8u,16u,18u,30u,26u,12u,2u,24u,0u,4u,22u,14u,10u,6u,\n\t\t\t22u,16u,24u,0u,10u,4u,30u,26u,20u,28u,6u,12u,14u,2u,18u,8u,\n\t\t\t14u,18u,6u,2u,26u,24u,22u,28u,4u,12u,10u,20u,8u,0u,30u,16u,\n\t\t\t18u,0u,10u,14u,4u,8u,20u,30u,28u,2u,22u,24u,12u,16u,6u,26u,\n\t\t\t4u,24u,12u,20u,0u,22u,16u,6u,8u,26u,14u,10u,30u,28u,2u,18u,\n\t\t\t24u,10u,2u,30u,28u,26u,8u,20u,0u,14u,12u,6u,18u,4u,16u,22u,\n\t\t\t26u,22u,14u,28u,24u,2u,6u,18u,10u,0u,30u,8u,16u,12u,4u,20u,\n\t\t\t12u,30u,28u,18u,22u,6u,0u,16u,24u,4u,26u,14u,2u,8u,20u,10u,\n\t\t\t20u,4u,16u,8u,14u,12u,2u,10u,30u,22u,18u,28u,6u,24u,26u,0u,\n\t\t\t0u,2u,4u,6u,8u,10u,12u,14u,16u,18u,20u,22u,24u,26u,28u,30u,\n\t\t\t28u,20u,8u,16u,18u,30u,26u,12u,2u,24u,0u,4u,22u,14u,10u,6u\n\t\t);\n\n\t\t/**\n\t\t* 64-bit unsigned addition within the compression buffer\n\t\t* Sets v[i,i+1] += b\n\t\t* LSb is the Least-Significant (32) Bits of b\n\t\t* MSb is the Most-Significant (32) Bits of b\n\t\t* If LSb overflows, increment MSb operand\n\t\t*/\n\t\tfn add_uint64 (v: ptr>, i: u32, LSb: u32, MSb: u32) {\n\t\t\tvar o0: u32 = (*v)[i] + LSb;\n\t\t\tvar o1: u32 = (*v)[i+1u] + MSb;\n\t\t\tif ((*v)[i] > 0xFFFFFFFFu - LSb) {\n\t\t\t\to1 = o1 + 1u;\n\t\t\t}\n\t\t\t(*v)[i] = o0;\n\t\t\t(*v)[i+1u] = o1;\n\t\t}\n\n\t\t/**\n\t\t* G Mixing function\n\t\t*/\n\t\tfn G (v: ptr>, m: ptr>, a: u32, b: u32, c: u32, d: u32, ix: u32, iy: u32) {\n\t\t\tadd_uint64(v, a, (*v)[b], (*v)[b+1u]);\n\t\t\tadd_uint64(v, a, (*m)[ix], (*m)[ix+1u]);\n\n\t\t\t// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n\t\t\tvar xor0: u32 = (*v)[d] ^ (*v)[a];\n\t\t\tvar xor1: u32 = (*v)[d+1u] ^ (*v)[a+1u];\n\t\t\t(*v)[d] = xor1;\n\t\t\t(*v)[d+1u] = xor0;\n\n\t\t\tadd_uint64(v, c, (*v)[d], (*v)[d+1u]);\n\n\t\t\t// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n\t\t\txor0 = (*v)[b] ^ (*v)[c];\n\t\t\txor1 = (*v)[b+1u] ^ (*v)[c+1u];\n\t\t\t(*v)[b] = (xor0 >> 24u) ^ (xor1 << 8u);\n\t\t\t(*v)[b+1u] = (xor1 >> 24u) ^ (xor0 << 8u);\n\n\t\t\tadd_uint64(v, a, (*v)[b], (*v)[b+1u]);\n\t\t\tadd_uint64(v, a, (*m)[iy], (*m)[iy+1u]);\n\n\t\t\t// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n\t\t\txor0 = (*v)[d] ^ (*v)[a];\n\t\t\txor1 = (*v)[d+1u] ^ (*v)[a+1u];\n\t\t\t(*v)[d] = (xor0 >> 16u) ^ (xor1 << 16u);\n\t\t\t(*v)[d+1u] = (xor1 >> 16u) ^ (xor0 << 16u);\n\n\t\t\tadd_uint64(v, c, (*v)[d], (*v)[d+1u]);\n\n\t\t\t// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n\t\t\txor0 = (*v)[b] ^ (*v)[c];\n\t\t\txor1 = (*v)[b+1u] ^ (*v)[c+1u];\n\t\t\t(*v)[b] = (xor1 >> 31u) ^ (xor0 << 1u);\n\t\t\t(*v)[b+1u] = (xor0 >> 31u) ^ (xor1 << 1u);\n\t\t}\n\n\t\t/**\n\t\t* Main compute function\n\t\t*\n\t\t* 8-byte work is split into two 4-byte u32\n\t\t* First 4 bytes will be iterated by shader\n\t\t* Last 4 bytes are defined by index of each thread\n\t\t*/\n\t\t@compute @workgroup_size(256)\n\t\tfn main(\n\t\t\t@builtin(workgroup_id) workgroup_id: vec3,\n\t\t\t@builtin(local_invocation_id) local_id: vec3\n\t\t) {\n\t\t\tvar id: u32 = ((workgroup_id.x & 0xff) << 24) |\n\t\t\t\t\t\t\t\t\t\t((workgroup_id.y & 0xff) << 16) |\n\t\t\t\t\t\t\t\t\t\t((workgroup_id.z & 0xff) << 8) |\n\t\t\t\t\t\t\t\t\t\t(local_id.x & 0xff);\n\t\t\tvar m: array;\n\t\t\tm[0u] = id;\n\t\t\tm[1u] = id;\n\t\t\tm[2u] = ubo.blockhash[0u].x;\n\t\t\tm[3u] = ubo.blockhash[0u].y;\n\t\t\tm[4u] = ubo.blockhash[0u].z;\n\t\t\tm[5u] = ubo.blockhash[0u].w;\n\t\t\tm[6u] = ubo.blockhash[1u].x;\n\t\t\tm[7u] = ubo.blockhash[1u].y;\n\t\t\tm[8u] = ubo.blockhash[1u].z;\n\t\t\tm[9u] = ubo.blockhash[1u].w;\n\n\n\t\t\t/**\n\t\t\t* Compression buffer, intialized to 2 instances of the initialization vector\n\t\t\t* The following values have been modified from the BLAKE2B_IV:\n\t\t\t* OUTLEN is constant 8 bytes\n\t\t\t* v[0u] ^= 0x01010000u ^ uint(OUTLEN);\n\t\t\t* INLEN is constant 40 bytes: work value (8) + block hash (32)\n\t\t\t* v[24u] ^= uint(INLEN);\n\t\t\t* It's always the \"last\" compression at this INLEN\n\t\t\t* v[28u] = ~v[28u];\n\t\t\t* v[29u] = ~v[29u];\n\t\t\t*/\n\t\t\tvar v = array(\n\t\t\t\t0xF2BDC900u, 0x6A09E667u, 0x84CAA73Bu, 0xBB67AE85u,\n\t\t\t\t0xFE94F82Bu, 0x3C6EF372u, 0x5F1D36F1u, 0xA54FF53Au,\n\t\t\t\t0xADE682D1u, 0x510E527Fu, 0x2B3E6C1Fu, 0x9B05688Cu,\n\t\t\t\t0xFB41BD6Bu, 0x1F83D9ABu, 0x137E2179u, 0x5BE0CD19u,\n\t\t\t\t0xF3BCC908u, 0x6A09E667u, 0x84CAA73Bu, 0xBB67AE85u,\n\t\t\t\t0xFE94F82Bu, 0x3C6EF372u, 0x5F1D36F1u, 0xA54FF53Au,\n\t\t\t\t0xADE682F9u, 0x510E527Fu, 0x2B3E6C1Fu, 0x9B05688Cu,\n\t\t\t\t0x04BE4294u, 0xE07C2654u, 0x137E2179u, 0x5BE0CD19u\n\t\t\t);\n\n\t\t\t/**\n\t\t\t* Iterate and hash until nonce found\n\t\t\t*/\n\t\t\tfor (var j: u32 = id; j < id + 1u; j = j + 1u) {\n\t\t\t\tif (atomicLoad(&work.found) != 0u) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tm[0u] = j;\n\n\t\t\t\t// twelve rounds of mixing\n\t\t\t\tfor (var i: u32 = 0u; i < 12u; i = i + 1u) {\n\t\t\t\t\tG(&v, &m, 0u, 8u, 16u, 24u, SIGMA82[i * 16u + 0u], SIGMA82[i * 16u + 1u]);\n\t\t\t\t\tG(&v, &m, 2u, 10u, 18u, 26u, SIGMA82[i * 16u + 2u], SIGMA82[i * 16u + 3u]);\n\t\t\t\t\tG(&v, &m, 4u, 12u, 20u, 28u, SIGMA82[i * 16u + 4u], SIGMA82[i * 16u + 5u]);\n\t\t\t\t\tG(&v, &m, 6u, 14u, 22u, 30u, SIGMA82[i * 16u + 6u], SIGMA82[i * 16u + 7u]);\n\t\t\t\t\tG(&v, &m, 0u, 10u, 20u, 30u, SIGMA82[i * 16u + 8u], SIGMA82[i * 16u + 9u]);\n\t\t\t\t\tG(&v, &m, 2u, 12u, 22u, 24u, SIGMA82[i * 16u + 10u], SIGMA82[i * 16u + 11u]);\n\t\t\t\t\tG(&v, &m, 4u, 14u, 16u, 26u, SIGMA82[i * 16u + 12u], SIGMA82[i * 16u + 13u]);\n\t\t\t\t\tG(&v, &m, 6u, 8u, 18u, 28u, SIGMA82[i * 16u + 14u], SIGMA82[i * 16u + 15u]);\n\t\t\t\t}\n\n\t\t\t\t// Store the result directly into work array\n\t\t\t\tif ((BLAKE2B_IV32_1 ^ v[1u] ^ v[17u]) > ubo.threshold) {\n\t\t\t\t\tatomicStore(&work.found, 1u);\n\t\t\t\t\twork.nonce.x = id;\n\t\t\t\t\twork.nonce.y = j;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t`;\n // Initialize WebGPU\n static #device = null;\n static #gpuBuffer;\n static #cpuBuffer;\n static #bindGroupLayout;\n static #pipeline;\n // Initialize WebGPU\n static {\n // Request device and adapter\n if (navigator.gpu == null) {\n throw new Error('WebGPU is not supported in this browser.');\n }\n navigator.gpu.requestAdapter()\n .then(adapter => {\n if (adapter == null) {\n throw new Error('WebGPU adapter refused by browser.');\n }\n adapter.requestDevice()\n .then(device => {\n this.#device = device;\n // Create buffers for writing GPU calculations and reading from Javascript\n this.#gpuBuffer = this.#device.createBuffer({\n size: 16,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC\n });\n this.#cpuBuffer = this.#device.createBuffer({\n size: 16,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ\n });\n // Create binding group data structure and use it later once UBO is known\n this.#bindGroupLayout = this.#device.createBindGroupLayout({\n entries: [\n {\n binding: 0,\n visibility: GPUShaderStage.COMPUTE,\n buffer: {\n type: 'uniform'\n },\n },\n {\n binding: 1,\n visibility: GPUShaderStage.COMPUTE,\n buffer: {\n type: 'storage'\n },\n }\n ]\n });\n // Create pipeline to connect compute shader to binding layout\n this.#pipeline = this.#device.createComputePipeline({\n layout: this.#device.createPipelineLayout({\n bindGroupLayouts: [this.#bindGroupLayout]\n }),\n compute: {\n entryPoint: 'main',\n module: this.#device.createShaderModule({\n code: this.#shader\n })\n }\n });\n });\n })\n .catch(err => { throw new Error(err.message); });\n }\n static async #calculate(hashHex, callback, threshold) {\n if (!/^[A-Fa-f0-9]{64}$/.test(hashHex))\n throw new Error(`Invalid hash ${hashHex}`);\n if (typeof threshold !== 'number')\n throw new TypeError(`Invalid threshold ${threshold}`);\n // Ensure WebGPU is initialized else restart calculation\n if (PowGpu.#device == null) {\n setTimeout(async () => { await this.#calculate(hashHex, callback, threshold); }, 100);\n return;\n }\n // Set up uniform buffer object\n const uboView = new DataView(new ArrayBuffer(48));\n for (let i = 0; i < 64; i += 8) {\n const uint32 = hashHex.slice(i, i + 8);\n uboView.setUint32(i / 2, parseInt(uint32, 16));\n }\n uboView.setUint32(32, threshold, true);\n const uboBuffer = PowGpu.#device.createBuffer({\n size: uboView.byteLength,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n PowGpu.#device.queue.writeBuffer(uboBuffer, 0, uboView);\n // Work buffer\n const bindGroup = PowGpu.#device.createBindGroup({\n layout: PowGpu.#bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: {\n buffer: uboBuffer,\n },\n },\n {\n binding: 1,\n resource: {\n buffer: PowGpu.#gpuBuffer,\n },\n },\n ],\n });\n // Create command encoder to issue commands to GPU and initiate computation\n const commandEncoder = PowGpu.#device.createCommandEncoder();\n const passEncoder = commandEncoder.beginComputePass();\n // Issue commands and end compute pass structure\n passEncoder.setPipeline(PowGpu.#pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.dispatchWorkgroups(256, 256, 256);\n passEncoder.end();\n // Copy 8-byte nonce and 4-byte found flag from GPU to CPU for reading\n commandEncoder.copyBufferToBuffer(PowGpu.#gpuBuffer, 0, PowGpu.#cpuBuffer, 0, 12);\n // End computation by passing array of command buffers to command queue for execution\n PowGpu.#device.queue.submit([commandEncoder.finish()]);\n // Read results back to Javascript and then unmap buffer after reading\n await PowGpu.#cpuBuffer.mapAsync(GPUMapMode.READ);\n await PowGpu.#device.queue.onSubmittedWorkDone();\n const data = new DataView(PowGpu.#cpuBuffer.getMappedRange());\n const nonce = data.getBigUint64(0, true);\n const found = !!data.getUint32(8);\n console.log(new Uint32Array(data.buffer));\n PowGpu.#cpuBuffer.unmap();\n console.log(`found: ${found}`);\n console.log(`nonce: ${nonce}`);\n if (found) {\n const hex = nonce.toString(16).padStart(16, '0');\n typeof callback === 'function' && callback(hex);\n return;\n }\n else {\n console.warn(`PoW ended but 'found' is false for nonce: ${nonce}`);\n }\n }\n}\nexport default `\n\tconst WorkerInterface = ${WorkerInterface}\n\tconst PowGpu = ${PowGpu}\n`;\n", "// SPDX-FileCopyrightText: 2024 Chris Duncan \n// SPDX-License-Identifier: GPL-3.0-or-later\nimport { default as Bip44Ckd } from './workers/bip44-ckd.js';\nimport { default as NanoNaCl } from './workers/nano-nacl.js';\nimport { default as Pow } from './workers/powgl.js';\nimport { default as PowGpu } from './workers/powgpu.js';\nexport { Bip44Ckd, NanoNaCl, Pow, PowGpu };\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n", "/* eslint-disable no-continue */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-param-reassign */\n/* eslint-disable no-prototype-builtins */\n\nconst errorClasses = {};\nconst deserializers = {};\n\nexport const addCustomErrorDeserializer = (name: string, deserializer: (obj: any) => any): void => {\n deserializers[name] = deserializer;\n};\n\nexport interface LedgerErrorConstructor\n extends ErrorConstructor {\n new (message?: string, fields?: F, options?: any): Error;\n (message?: string, fields?: F, options?: any): Error;\n readonly prototype: Error;\n}\n\nexport const createCustomErrorClass = <\n F extends { [key: string]: unknown },\n T extends LedgerErrorConstructor = LedgerErrorConstructor,\n>(\n name: string,\n): T => {\n class CustomErrorClass extends Error {\n cause?: Error;\n constructor(message?: string, fields?: F, options?: any) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n super(message || name, options);\n // Set the prototype explicitly. See https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, CustomErrorClass.prototype);\n this.name = name;\n if (fields) {\n for (const k in fields) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this[k] = fields[k];\n }\n }\n if (options && isObject(options) && \"cause\" in options && !(\"cause\" in this)) {\n // .cause was specified but the superconstructor\n // did not create an instance property.\n const cause = options.cause;\n this.cause = cause;\n if (\"stack\" in cause) {\n this.stack = this.stack + \"\\nCAUSE: \" + cause.stack;\n }\n }\n }\n }\n\n errorClasses[name] = CustomErrorClass;\n\n return CustomErrorClass as unknown as T;\n};\n\nfunction isObject(value) {\n return typeof value === \"object\";\n}\n\n// inspired from https://github.com/programble/errio/blob/master/index.js\nexport const deserializeError = (object: any): Error | undefined => {\n if (object && typeof object === \"object\") {\n try {\n if (typeof object.message === \"string\") {\n const msg = JSON.parse(object.message);\n if (msg.message && msg.name) {\n object = msg;\n }\n }\n } catch (e) {\n // nothing\n }\n\n let error;\n if (typeof object.name === \"string\") {\n const { name } = object;\n const des = deserializers[name];\n if (des) {\n error = des(object);\n } else {\n let constructor = name === \"Error\" ? Error : errorClasses[name];\n\n if (!constructor) {\n console.warn(\"deserializing an unknown class '\" + name + \"'\");\n constructor = createCustomErrorClass(name);\n }\n\n error = Object.create(constructor.prototype);\n try {\n for (const prop in object) {\n if (object.hasOwnProperty(prop)) {\n error[prop] = object[prop];\n }\n }\n } catch (e) {\n // sometimes setting a property can fail (e.g. .name)\n }\n }\n } else {\n if (typeof object.message === \"string\") {\n error = new Error(object.message);\n }\n }\n\n if (error && !error.stack && Error.captureStackTrace) {\n Error.captureStackTrace(error, deserializeError);\n }\n return error;\n }\n return new Error(String(object));\n};\n\n// inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js\nexport const serializeError = (\n value: undefined | To | string | (() => unknown),\n): undefined | To | string => {\n if (!value) return value;\n if (typeof value === \"object\") {\n return destroyCircular(value, []);\n }\n if (typeof value === \"function\") {\n return `[Function: ${value.name || \"anonymous\"}]`;\n }\n return value;\n};\n\ninterface To {\n name?: string;\n message?: string;\n stack?: string;\n}\n\n// https://www.npmjs.com/package/destroy-circular\nfunction destroyCircular(from: To, seen: Array): To {\n const to: To = {};\n seen.push(from);\n for (const key of Object.keys(from)) {\n const value = from[key];\n if (typeof value === \"function\") {\n continue;\n }\n if (!value || typeof value !== \"object\") {\n to[key] = value;\n continue;\n }\n if (seen.indexOf(from[key]) === -1) {\n to[key] = destroyCircular(from[key], seen.slice(0));\n continue;\n }\n to[key] = \"[Circular]\";\n }\n if (typeof from.name === \"string\") {\n to.name = from.name;\n }\n if (typeof from.message === \"string\") {\n to.message = from.message;\n }\n if (typeof from.stack === \"string\") {\n to.stack = from.stack;\n }\n return to;\n}\n", "import {\n serializeError,\n deserializeError,\n createCustomErrorClass,\n addCustomErrorDeserializer,\n LedgerErrorConstructor,\n} from \"./helpers\";\n\nexport { serializeError, deserializeError, createCustomErrorClass, addCustomErrorDeserializer };\n\nexport const AccountNameRequiredError = createCustomErrorClass(\"AccountNameRequired\");\nexport const AccountNotSupported = createCustomErrorClass(\"AccountNotSupported\");\nexport const AccountAwaitingSendPendingOperations = createCustomErrorClass(\n \"AccountAwaitingSendPendingOperations\",\n);\nexport const AmountRequired = createCustomErrorClass(\"AmountRequired\");\nexport const BluetoothRequired = createCustomErrorClass(\"BluetoothRequired\");\nexport const BtcUnmatchedApp = createCustomErrorClass(\"BtcUnmatchedApp\");\nexport const CantOpenDevice = createCustomErrorClass(\"CantOpenDevice\");\nexport const CashAddrNotSupported = createCustomErrorClass(\"CashAddrNotSupported\");\nexport const ClaimRewardsFeesWarning = createCustomErrorClass(\"ClaimRewardsFeesWarning\");\nexport const CurrencyNotSupported = createCustomErrorClass<\n { currencyName: string },\n LedgerErrorConstructor<{ currencyName: string }>\n>(\"CurrencyNotSupported\");\nexport const DeviceAppVerifyNotSupported = createCustomErrorClass(\"DeviceAppVerifyNotSupported\");\nexport const DeviceGenuineSocketEarlyClose = createCustomErrorClass(\n \"DeviceGenuineSocketEarlyClose\",\n);\nexport const DeviceNotGenuineError = createCustomErrorClass(\"DeviceNotGenuine\");\nexport const DeviceOnDashboardExpected = createCustomErrorClass(\"DeviceOnDashboardExpected\");\nexport const DeviceOnDashboardUnexpected = createCustomErrorClass(\"DeviceOnDashboardUnexpected\");\nexport const DeviceInOSUExpected = createCustomErrorClass(\"DeviceInOSUExpected\");\nexport const DeviceHalted = createCustomErrorClass(\"DeviceHalted\");\nexport const DeviceNameInvalid = createCustomErrorClass(\"DeviceNameInvalid\");\nexport const DeviceSocketFail = createCustomErrorClass(\"DeviceSocketFail\");\nexport const DeviceSocketNoBulkStatus = createCustomErrorClass(\"DeviceSocketNoBulkStatus\");\nexport const DeviceNeedsRestart = createCustomErrorClass(\"DeviceSocketNoBulkStatus\");\nexport const UnresponsiveDeviceError = createCustomErrorClass(\"UnresponsiveDeviceError\");\nexport const DisconnectedDevice = createCustomErrorClass(\"DisconnectedDevice\");\nexport const DisconnectedDeviceDuringOperation = createCustomErrorClass(\n \"DisconnectedDeviceDuringOperation\",\n);\nexport const DeviceExtractOnboardingStateError = createCustomErrorClass(\n \"DeviceExtractOnboardingStateError\",\n);\nexport const DeviceOnboardingStatePollingError = createCustomErrorClass(\n \"DeviceOnboardingStatePollingError\",\n);\nexport const EnpointConfigError = createCustomErrorClass(\"EnpointConfig\");\nexport const EthAppPleaseEnableContractData = createCustomErrorClass(\n \"EthAppPleaseEnableContractData\",\n);\nexport const FeeEstimationFailed = createCustomErrorClass(\"FeeEstimationFailed\");\nexport const FirmwareNotRecognized = createCustomErrorClass(\"FirmwareNotRecognized\");\nexport const HardResetFail = createCustomErrorClass(\"HardResetFail\");\nexport const InvalidXRPTag = createCustomErrorClass(\"InvalidXRPTag\");\nexport const InvalidAddress = createCustomErrorClass(\"InvalidAddress\");\nexport const InvalidNonce = createCustomErrorClass(\"InvalidNonce\");\nexport const InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass(\n \"InvalidAddressBecauseDestinationIsAlsoSource\",\n);\nexport const LatestMCUInstalledError = createCustomErrorClass(\"LatestMCUInstalledError\");\nexport const UnknownMCU = createCustomErrorClass(\"UnknownMCU\");\nexport const LedgerAPIError = createCustomErrorClass(\"LedgerAPIError\");\nexport const LedgerAPIErrorWithMessage = createCustomErrorClass(\"LedgerAPIErrorWithMessage\");\nexport const LedgerAPINotAvailable = createCustomErrorClass(\"LedgerAPINotAvailable\");\nexport const ManagerAppAlreadyInstalledError = createCustomErrorClass(\"ManagerAppAlreadyInstalled\");\nexport const ManagerAppRelyOnBTCError = createCustomErrorClass(\"ManagerAppRelyOnBTC\");\nexport const ManagerAppDepInstallRequired = createCustomErrorClass(\"ManagerAppDepInstallRequired\");\nexport const ManagerAppDepUninstallRequired = createCustomErrorClass(\n \"ManagerAppDepUninstallRequired\",\n);\nexport const ManagerDeviceLockedError = createCustomErrorClass(\"ManagerDeviceLocked\");\nexport const ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass(\n \"ManagerFirmwareNotEnoughSpace\",\n);\nexport const ManagerNotEnoughSpaceError = createCustomErrorClass(\"ManagerNotEnoughSpace\");\nexport const ManagerUninstallBTCDep = createCustomErrorClass(\"ManagerUninstallBTCDep\");\nexport const NetworkDown = createCustomErrorClass(\"NetworkDown\");\nexport const NetworkError = createCustomErrorClass(\"NetworkError\");\nexport const NoAddressesFound = createCustomErrorClass(\"NoAddressesFound\");\nexport const NotEnoughBalance = createCustomErrorClass(\"NotEnoughBalance\");\nexport const NotEnoughBalanceSwap = createCustomErrorClass(\"NotEnoughBalanceSwap\");\nexport const NotEnoughBalanceToDelegate = createCustomErrorClass(\"NotEnoughBalanceToDelegate\");\nexport const NotEnoughBalanceInParentAccount = createCustomErrorClass(\n \"NotEnoughBalanceInParentAccount\",\n);\nexport const NotEnoughSpendableBalance = createCustomErrorClass(\"NotEnoughSpendableBalance\");\nexport const NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass(\n \"NotEnoughBalanceBecauseDestinationNotCreated\",\n);\nexport const NoAccessToCamera = createCustomErrorClass(\"NoAccessToCamera\");\nexport const NotEnoughGas = createCustomErrorClass(\"NotEnoughGas\");\n// Error message specifically for the PTX swap flow\nexport const NotEnoughGasSwap = createCustomErrorClass(\"NotEnoughGasSwap\");\nexport const TronEmptyAccount = createCustomErrorClass(\"TronEmptyAccount\");\nexport const MaybeKeepTronAccountAlive = createCustomErrorClass(\"MaybeKeepTronAccountAlive\");\nexport const NotSupportedLegacyAddress = createCustomErrorClass(\"NotSupportedLegacyAddress\");\nexport const GasLessThanEstimate = createCustomErrorClass(\"GasLessThanEstimate\");\nexport const PriorityFeeTooLow = createCustomErrorClass(\"PriorityFeeTooLow\");\nexport const PriorityFeeTooHigh = createCustomErrorClass(\"PriorityFeeTooHigh\");\nexport const PriorityFeeHigherThanMaxFee = createCustomErrorClass(\"PriorityFeeHigherThanMaxFee\");\nexport const MaxFeeTooLow = createCustomErrorClass(\"MaxFeeTooLow\");\nexport const PasswordsDontMatchError = createCustomErrorClass(\"PasswordsDontMatch\");\nexport const PasswordIncorrectError = createCustomErrorClass(\"PasswordIncorrect\");\nexport const RecommendSubAccountsToEmpty = createCustomErrorClass(\"RecommendSubAccountsToEmpty\");\nexport const RecommendUndelegation = createCustomErrorClass(\"RecommendUndelegation\");\nexport const TimeoutTagged = createCustomErrorClass(\"TimeoutTagged\");\nexport const UnexpectedBootloader = createCustomErrorClass(\"UnexpectedBootloader\");\nexport const MCUNotGenuineToDashboard = createCustomErrorClass(\"MCUNotGenuineToDashboard\");\nexport const RecipientRequired = createCustomErrorClass(\"RecipientRequired\");\nexport const UnavailableTezosOriginatedAccountReceive = createCustomErrorClass(\n \"UnavailableTezosOriginatedAccountReceive\",\n);\nexport const UnavailableTezosOriginatedAccountSend = createCustomErrorClass(\n \"UnavailableTezosOriginatedAccountSend\",\n);\nexport const UpdateFetchFileFail = createCustomErrorClass(\"UpdateFetchFileFail\");\nexport const UpdateIncorrectHash = createCustomErrorClass(\"UpdateIncorrectHash\");\nexport const UpdateIncorrectSig = createCustomErrorClass(\"UpdateIncorrectSig\");\nexport const UpdateYourApp = createCustomErrorClass(\"UpdateYourApp\");\nexport const UserRefusedDeviceNameChange = createCustomErrorClass(\"UserRefusedDeviceNameChange\");\nexport const UserRefusedAddress = createCustomErrorClass(\"UserRefusedAddress\");\nexport const UserRefusedFirmwareUpdate = createCustomErrorClass(\"UserRefusedFirmwareUpdate\");\nexport const UserRefusedAllowManager = createCustomErrorClass(\"UserRefusedAllowManager\");\nexport const UserRefusedOnDevice = createCustomErrorClass(\"UserRefusedOnDevice\"); // TODO rename because it's just for transaction refusal\nexport const PinNotSet = createCustomErrorClass(\"PinNotSet\");\nexport const ExpertModeRequired = createCustomErrorClass(\"ExpertModeRequired\");\nexport const TransportOpenUserCancelled = createCustomErrorClass(\"TransportOpenUserCancelled\");\nexport const TransportInterfaceNotAvailable = createCustomErrorClass(\n \"TransportInterfaceNotAvailable\",\n);\nexport const TransportRaceCondition = createCustomErrorClass(\"TransportRaceCondition\");\nexport const TransportWebUSBGestureRequired = createCustomErrorClass(\n \"TransportWebUSBGestureRequired\",\n);\nexport const TransactionHasBeenValidatedError = createCustomErrorClass(\n \"TransactionHasBeenValidatedError\",\n);\nexport const TransportExchangeTimeoutError = createCustomErrorClass(\n \"TransportExchangeTimeoutError\",\n);\nexport const DeviceShouldStayInApp = createCustomErrorClass(\"DeviceShouldStayInApp\");\nexport const WebsocketConnectionError = createCustomErrorClass(\"WebsocketConnectionError\");\nexport const WebsocketConnectionFailed = createCustomErrorClass(\"WebsocketConnectionFailed\");\nexport const WrongDeviceForAccount = createCustomErrorClass(\"WrongDeviceForAccount\");\nexport const WrongDeviceForAccountPayout = createCustomErrorClass(\"WrongDeviceForAccountPayout\");\nexport const WrongDeviceForAccountRefund = createCustomErrorClass(\"WrongDeviceForAccountRefund\");\nexport const WrongAppForCurrency = createCustomErrorClass(\"WrongAppForCurrency\");\n\nexport const ETHAddressNonEIP = createCustomErrorClass(\"ETHAddressNonEIP\");\nexport const CantScanQRCode = createCustomErrorClass(\"CantScanQRCode\");\nexport const FeeNotLoaded = createCustomErrorClass(\"FeeNotLoaded\");\nexport const FeeNotLoadedSwap = createCustomErrorClass(\"FeeNotLoadedSwap\");\nexport const FeeRequired = createCustomErrorClass(\"FeeRequired\");\nexport const FeeTooHigh = createCustomErrorClass(\"FeeTooHigh\");\nexport const PendingOperation = createCustomErrorClass(\"PendingOperation\");\nexport const SyncError = createCustomErrorClass(\"SyncError\");\nexport const PairingFailed = createCustomErrorClass(\"PairingFailed\");\nexport const PeerRemovedPairing = createCustomErrorClass(\"PeerRemovedPairing\");\nexport const GenuineCheckFailed = createCustomErrorClass(\"GenuineCheckFailed\");\ntype NetworkType = {\n status: number;\n url: string | undefined;\n method: string;\n};\nexport const LedgerAPI4xx = createCustomErrorClass<\n NetworkType,\n LedgerErrorConstructor\n>(\"LedgerAPI4xx\");\nexport const LedgerAPI5xx = createCustomErrorClass<\n NetworkType,\n LedgerErrorConstructor\n>(\"LedgerAPI5xx\");\nexport const FirmwareOrAppUpdateRequired = createCustomErrorClass(\"FirmwareOrAppUpdateRequired\");\n\n// SpeedUp / Cancel EVM tx\nexport const ReplacementTransactionUnderpriced = createCustomErrorClass(\n \"ReplacementTransactionUnderpriced\",\n);\n\n// Bitcoin family\nexport const OpReturnDataSizeLimit = createCustomErrorClass(\"OpReturnSizeLimit\");\nexport const DustLimit = createCustomErrorClass(\"DustLimit\");\n\n// Language\nexport const LanguageNotFound = createCustomErrorClass(\"LanguageNotFound\");\n\n// db stuff, no need to translate\nexport const NoDBPathGiven = createCustomErrorClass(\"NoDBPathGiven\");\nexport const DBWrongPassword = createCustomErrorClass(\"DBWrongPassword\");\nexport const DBNotReset = createCustomErrorClass(\"DBNotReset\");\n\nexport const SequenceNumberError = createCustomErrorClass(\"SequenceNumberError\");\nexport const DisabledTransactionBroadcastError = createCustomErrorClass(\n \"DisabledTransactionBroadcastError\",\n);\n\n// Represents the type of all the classes created with createCustomErrorClass\nexport type CustomErrorClassType = ReturnType;\n\n/**\n * Type of a Transport error used to represent all equivalent errors coming from all possible implementation of Transport\n */\nexport enum HwTransportErrorType {\n Unknown = \"Unknown\",\n LocationServicesDisabled = \"LocationServicesDisabled\",\n LocationServicesUnauthorized = \"LocationServicesUnauthorized\",\n BluetoothScanStartFailed = \"BluetoothScanStartFailed\",\n}\n\n/**\n * Represents an error coming from the usage of any Transport implementation.\n *\n * Needed to map a specific implementation error into an error that\n * can be managed by any code unaware of the specific Transport implementation\n * that was used.\n */\nexport class HwTransportError extends Error {\n type: HwTransportErrorType;\n\n constructor(type: HwTransportErrorType, message: string) {\n super(message);\n this.name = \"HwTransportError\";\n this.type = type;\n\n // Needed as long as we target < ES6\n Object.setPrototypeOf(this, HwTransportError.prototype);\n }\n}\n\n/**\n * TransportError is used for any generic transport errors.\n * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason.\n */\nexport class TransportError extends Error {\n id: string;\n constructor(message: string, id: string) {\n const name = \"TransportError\";\n super(message || name);\n this.name = name;\n this.message = message;\n this.stack = new Error(message).stack;\n this.id = id;\n }\n}\n\naddCustomErrorDeserializer(\"TransportError\", e => new TransportError(e.message, e.id));\n\nexport const StatusCodes = {\n ACCESS_CONDITION_NOT_FULFILLED: 0x9804,\n ALGORITHM_NOT_SUPPORTED: 0x9484,\n CLA_NOT_SUPPORTED: 0x6e00,\n CODE_BLOCKED: 0x9840,\n CODE_NOT_INITIALIZED: 0x9802,\n COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981,\n CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985,\n CONTRADICTION_INVALIDATION: 0x9810,\n CONTRADICTION_SECRET_CODE_STATUS: 0x9808,\n DEVICE_IN_RECOVERY_MODE: 0x662f,\n CUSTOM_IMAGE_EMPTY: 0x662e,\n FILE_ALREADY_EXISTS: 0x6a89,\n FILE_NOT_FOUND: 0x9404,\n GP_AUTH_FAILED: 0x6300,\n HALTED: 0x6faa,\n INCONSISTENT_FILE: 0x9408,\n INCORRECT_DATA: 0x6a80,\n INCORRECT_LENGTH: 0x6700,\n INCORRECT_P1_P2: 0x6b00,\n INS_NOT_SUPPORTED: 0x6d00,\n DEVICE_NOT_ONBOARDED: 0x6d07,\n DEVICE_NOT_ONBOARDED_2: 0x6611,\n INVALID_KCV: 0x9485,\n INVALID_OFFSET: 0x9402,\n LICENSING: 0x6f42,\n LOCKED_DEVICE: 0x5515,\n MAX_VALUE_REACHED: 0x9850,\n MEMORY_PROBLEM: 0x9240,\n MISSING_CRITICAL_PARAMETER: 0x6800,\n NO_EF_SELECTED: 0x9400,\n NOT_ENOUGH_MEMORY_SPACE: 0x6a84,\n OK: 0x9000,\n PIN_REMAINING_ATTEMPTS: 0x63c0,\n REFERENCED_DATA_NOT_FOUND: 0x6a88,\n SECURITY_STATUS_NOT_SATISFIED: 0x6982,\n TECHNICAL_PROBLEM: 0x6f00,\n UNKNOWN_APDU: 0x6d02,\n USER_REFUSED_ON_DEVICE: 0x5501,\n NOT_ENOUGH_SPACE: 0x5102,\n APP_NOT_FOUND_OR_INVALID_CONTEXT: 0x5123,\n INVALID_APP_NAME_LENGTH: 0x670a,\n GEN_AES_KEY_FAILED: 0x5419,\n INTERNAL_CRYPTO_OPERATION_FAILED: 0x541a,\n INTERNAL_COMPUTE_AES_CMAC_FAILED: 0x541b,\n ENCRYPT_APP_STORAGE_FAILED: 0x541c,\n INVALID_BACKUP_STATE: 0x6642,\n PIN_NOT_SET: 0x5502,\n INVALID_BACKUP_LENGTH: 0x6733,\n INVALID_RESTORE_STATE: 0x6643,\n INVALID_CHUNK_LENGTH: 0x6734,\n INVALID_BACKUP_HEADER: 0x684a,\n\n // Not documented:\n TRUSTCHAIN_WRONG_SEED: 0xb007,\n};\n\nexport function getAltStatusMessage(code: number): string | undefined | null {\n switch (code) {\n // improve text of most common errors\n case 0x6700:\n return \"Incorrect length\";\n case 0x6800:\n return \"Missing critical parameter\";\n case 0x6982:\n return \"Security not satisfied (dongle locked or have invalid access rights)\";\n case 0x6985:\n return \"Condition of use not satisfied (denied by the user?)\";\n case 0x6a80:\n return \"Invalid data received\";\n case 0x6b00:\n return \"Invalid parameter received\";\n case 0x5515:\n return \"Locked device\";\n }\n if (0x6f00 <= code && code <= 0x6fff) {\n return \"Internal error, please report\";\n }\n}\n\n/**\n * Error thrown when a device returned a non success status.\n * the error.statusCode is one of the `StatusCodes` exported by this library.\n */\nexport class TransportStatusError extends Error {\n statusCode: number;\n statusText: string;\n\n /**\n * @param statusCode The error status code coming from a Transport implementation\n * @param options containing:\n * - canBeMappedToChildError: enable the mapping of TransportStatusError to an error extending/inheriting from it\n * . Ex: LockedDeviceError. Default to true.\n */\n constructor(\n statusCode: number,\n { canBeMappedToChildError = true }: { canBeMappedToChildError?: boolean } = {},\n ) {\n const statusText =\n Object.keys(StatusCodes).find(k => StatusCodes[k] === statusCode) || \"UNKNOWN_ERROR\";\n const smsg = getAltStatusMessage(statusCode) || statusText;\n const statusCodeStr = statusCode.toString(16);\n const message = `Ledger device: ${smsg} (0x${statusCodeStr})`;\n\n super(message);\n this.name = \"TransportStatusError\";\n\n this.statusCode = statusCode;\n this.statusText = statusText;\n\n Object.setPrototypeOf(this, TransportStatusError.prototype);\n\n // Maps to a LockedDeviceError\n if (canBeMappedToChildError && statusCode === StatusCodes.LOCKED_DEVICE) {\n return new LockedDeviceError(message);\n }\n }\n}\n\nexport class LockedDeviceError extends TransportStatusError {\n constructor(message?: string) {\n super(StatusCodes.LOCKED_DEVICE, { canBeMappedToChildError: false });\n if (message) {\n this.message = message;\n }\n this.name = \"LockedDeviceError\";\n Object.setPrototypeOf(this, LockedDeviceError.prototype);\n }\n}\n\n// Represents the type of the class TransportStatusError and its children\nexport type TransportStatusErrorClassType = typeof TransportStatusError | typeof LockedDeviceError;\n\naddCustomErrorDeserializer(\"TransportStatusError\", e => new TransportStatusError(e.statusCode));\n", "export type TraceContext = Record;\nexport type LogData = any;\nexport type LogType = string;\n\n/**\n * A Log object\n */\nexport interface Log {\n /**\n * A namespaced identifier of the log (not a level like \"debug\", \"error\" but more like \"apdu\", \"hw\", etc...)\n */\n type: LogType;\n message?: string;\n /**\n * Data associated to the log event\n */\n data?: LogData;\n /**\n * Context data, coming for example from the caller's parent, to enable a simple tracing system\n */\n context?: TraceContext;\n /**\n * Unique id among all logs\n */\n id: string;\n /*\n * Date when the log occurred\n */\n date: Date;\n}\n\nexport type Unsubscribe = () => void;\nexport type Subscriber = (arg0: Log) => void;\n\nlet id = 0;\nconst subscribers: Subscriber[] = [];\n\n/**\n * Logs something\n *\n * @param type a namespaced identifier of the log (it is not a level like \"debug\", \"error\" but more like \"apdu-in\", \"apdu-out\", etc...)\n * @param message a clear message of the log associated to the type\n */\nexport const log = (type: LogType, message?: string, data?: LogData) => {\n const obj: Log = {\n type,\n id: String(++id),\n date: new Date(),\n };\n if (message) obj.message = message;\n if (data) obj.data = data;\n dispatch(obj);\n};\n\n/**\n * A simple tracer function, only expanding the existing log function\n *\n * Its goal is to capture more context than a log function.\n * This is simple for now, but can be improved later.\n *\n * @param context Anything representing the context where the log occurred\n */\nexport const trace = ({\n type,\n message,\n data,\n context,\n}: {\n type: LogType;\n message?: string;\n data?: LogData;\n context?: TraceContext;\n}) => {\n const obj: Log = {\n type,\n id: String(++id),\n date: new Date(),\n };\n\n if (message) obj.message = message;\n if (data) obj.data = data;\n if (context) obj.context = context;\n\n dispatch(obj);\n};\n\n/**\n * A simple tracer class, that can be used to avoid repetition when using the `trace` function\n *\n * Its goal is to capture more context than a log function.\n * This is simple for now, but can be improved later.\n *\n * @param type A given type (not level) for the current local tracer (\"hw\", \"withDevice\", etc.)\n * @param context Anything representing the context where the log occurred\n */\nexport class LocalTracer {\n constructor(\n private type: LogType,\n private context?: TraceContext,\n ) {}\n\n trace(message: string, data?: TraceContext) {\n trace({\n type: this.type,\n message,\n data,\n context: this.context,\n });\n }\n\n getContext(): TraceContext | undefined {\n return this.context;\n }\n\n setContext(context?: TraceContext) {\n this.context = context;\n }\n\n updateContext(contextToAdd: TraceContext) {\n this.context = { ...this.context, ...contextToAdd };\n }\n\n getType(): LogType {\n return this.type;\n }\n\n setType(type: LogType) {\n this.type = type;\n }\n\n /**\n * Create a new instance of the LocalTracer with an updated `type`\n *\n * It does not mutate the calling instance, but returns a new LocalTracer,\n * following a simple builder pattern.\n */\n withType(type: LogType): LocalTracer {\n return new LocalTracer(type, this.context);\n }\n\n /**\n * Create a new instance of the LocalTracer with a new `context`\n *\n * It does not mutate the calling instance, but returns a new LocalTracer,\n * following a simple builder pattern.\n *\n * @param context A TraceContext, that can undefined to reset the context\n */\n withContext(context?: TraceContext): LocalTracer {\n return new LocalTracer(this.type, context);\n }\n\n /**\n * Create a new instance of the LocalTracer with an updated `context`,\n * on which an additional context is merged with the existing one.\n *\n * It does not mutate the calling instance, but returns a new LocalTracer,\n * following a simple builder pattern.\n */\n withUpdatedContext(contextToAdd: TraceContext): LocalTracer {\n return new LocalTracer(this.type, { ...this.context, ...contextToAdd });\n }\n}\n\n/**\n * Adds a subscribers to the emitted logs.\n *\n * @param cb that is called for each future log() with the Log object\n * @return a function that can be called to unsubscribe the listener\n */\nexport const listen = (cb: Subscriber): Unsubscribe => {\n subscribers.push(cb);\n return () => {\n const i = subscribers.indexOf(cb);\n\n if (i !== -1) {\n // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952\n subscribers[i] = subscribers[subscribers.length - 1];\n subscribers.pop();\n }\n };\n};\n\nfunction dispatch(log: Log) {\n for (let i = 0; i < subscribers.length; i++) {\n try {\n subscribers[i](log);\n } catch (e) {\n console.error(e);\n }\n }\n}\n\n// for debug purpose\n\ndeclare global {\n interface Window {\n __ledgerLogsListen: any;\n }\n}\n\nif (typeof window !== \"undefined\") {\n window.__ledgerLogsListen = listen;\n}\n", "import EventEmitter from \"events\";\nimport type { DeviceModel } from \"@ledgerhq/devices\";\nimport {\n TransportRaceCondition,\n TransportError,\n StatusCodes,\n getAltStatusMessage,\n TransportStatusError,\n} from \"@ledgerhq/errors\";\nimport { LocalTracer, TraceContext, LogType } from \"@ledgerhq/logs\";\nexport { TransportError, TransportStatusError, StatusCodes, getAltStatusMessage };\n\nconst DEFAULT_LOG_TYPE = \"transport\";\n\n/**\n */\nexport type Subscription = {\n unsubscribe: () => void;\n};\n\n/**\n */\nexport type Device = any; // Should be a union type of all possible Device object's shape\n\nexport type DescriptorEventType = \"add\" | \"remove\";\n/**\n * A \"descriptor\" is a parameter that is specific to the implementation, and can be an ID, file path, or URL.\n * type: add or remove event\n * descriptor: a parameter that can be passed to open(descriptor)\n * deviceModel: device info on the model (is it a nano s, nano x, ...)\n * device: transport specific device info\n */\nexport interface DescriptorEvent {\n type: DescriptorEventType;\n descriptor: Descriptor;\n deviceModel?: DeviceModel | null | undefined;\n device?: Device;\n}\n\n/**\n * Observer generic type, following the Observer pattern\n */\nexport type Observer = Readonly<{\n next: (event: EventType) => unknown;\n error: (e: EventError) => unknown;\n complete: () => unknown;\n}>;\n\n/**\n * The Transport class defines a generic interface for communicating with a Ledger hardware wallet.\n * There are different kind of transports based on the technology (channels like U2F, HID, Bluetooth, Webusb) and environment (Node, Web,...).\n * It is an abstract class that needs to be implemented.\n */\nexport default class Transport {\n exchangeTimeout = 30000;\n unresponsiveTimeout = 15000;\n deviceModel: DeviceModel | null | undefined = null;\n tracer: LocalTracer;\n\n constructor({ context, logType }: { context?: TraceContext; logType?: LogType } = {}) {\n this.tracer = new LocalTracer(logType ?? DEFAULT_LOG_TYPE, context);\n }\n\n /**\n * Check if the transport is supported on the current platform/browser.\n * @returns {Promise} A promise that resolves with a boolean indicating support.\n */\n static readonly isSupported: () => Promise;\n\n /**\n * List all available descriptors for the transport.\n * For a better granularity, checkout `listen()`.\n *\n * @returns {Promise>} A promise that resolves with an array of descriptors.\n * @example\n * TransportFoo.list().then(descriptors => ...)\n */\n static readonly list: () => Promise>;\n\n /**\n * Listen for device events for the transport. The method takes an observer of DescriptorEvent and returns a Subscription.\n * A DescriptorEvent is an object containing a \"descriptor\" and a \"type\" field. The \"type\" field can be \"add\" or \"remove\", and the \"descriptor\" field can be passed to the \"open\" method.\n * The \"listen\" method will first emit all currently connected devices and then will emit events as they occur, such as when a USB device is plugged in or a Bluetooth device becomes discoverable.\n * @param {Observer>} observer - An object with \"next\", \"error\", and \"complete\" functions, following the observer pattern.\n * @returns {Subscription} A Subscription object on which you can call \".unsubscribe()\" to stop listening to descriptors.\n * @example\n const sub = TransportFoo.listen({\n next: e => {\n if (e.type===\"add\") {\n sub.unsubscribe();\n const transport = await TransportFoo.open(e.descriptor);\n ...\n }\n },\n error: error => {},\n complete: () => {}\n })\n */\n static readonly listen: (observer: Observer>) => Subscription;\n\n /**\n * Attempt to create a Transport instance with a specific descriptor.\n * @param {any} descriptor - The descriptor to open the transport with.\n * @param {number} timeout - An optional timeout for the transport connection.\n * @param {TraceContext} context Optional tracing/log context\n * @returns {Promise} A promise that resolves with a Transport instance.\n * @example\n TransportFoo.open(descriptor).then(transport => ...)\n */\n static readonly open: (\n descriptor?: any,\n timeoutMs?: number,\n context?: TraceContext,\n ) => Promise;\n\n /**\n * Send data to the device using a low level API.\n * It's recommended to use the \"send\" method for a higher level API.\n * @param {Buffer} apdu - The data to send.\n * @param {Object} options - Contains optional options for the exchange function\n * - abortTimeoutMs: stop the exchange after a given timeout. Another timeout exists\n * to detect unresponsive device (see `unresponsiveTimeout`). This timeout aborts the exchange.\n * @returns {Promise} A promise that resolves with the response data from the device.\n */\n exchange(\n _apdu: Buffer,\n { abortTimeoutMs: _abortTimeoutMs }: { abortTimeoutMs?: number } = {},\n ): Promise {\n throw new Error(\"exchange not implemented\");\n }\n\n /**\n * Send apdus in batch to the device using a low level API.\n * The default implementation is to call exchange for each apdu.\n * @param {Array} apdus - array of apdus to send.\n * @param {Observer} observer - an observer that will receive the response of each apdu.\n * @returns {Subscription} A Subscription object on which you can call \".unsubscribe()\" to stop sending apdus.\n */\n exchangeBulk(apdus: Buffer[], observer: Observer): Subscription {\n let unsubscribed = false;\n const unsubscribe = () => {\n unsubscribed = true;\n };\n\n const main = async () => {\n if (unsubscribed) return;\n for (const apdu of apdus) {\n const r = await this.exchange(apdu);\n if (unsubscribed) return;\n const status = r.readUInt16BE(r.length - 2);\n if (status !== StatusCodes.OK) {\n throw new TransportStatusError(status);\n }\n observer.next(r);\n }\n };\n\n main().then(\n () => !unsubscribed && observer.complete(),\n e => !unsubscribed && observer.error(e),\n );\n\n return { unsubscribe };\n }\n\n /**\n * Set the \"scramble key\" for the next data exchanges with the device.\n * Each app can have a different scramble key and it is set internally during instantiation.\n * @param {string} key - The scramble key to set.\n * deprecated This method is no longer needed for modern transports and should be migrated away from.\n * no @ before deprecated as it breaks documentationjs on version 14.0.2\n * https://github.com/documentationjs/documentation/issues/1596\n */\n setScrambleKey(_key: string) {}\n\n /**\n * Close the connection with the device.\n *\n * Note: for certain transports (hw-transport-node-hid-singleton for ex), once the promise resolved,\n * the transport instance is actually still cached, and the device is disconnected only after a defined timeout.\n * But for the consumer of the Transport, this does not matter and it can consider the transport to be closed.\n *\n * @returns {Promise} A promise that resolves when the transport is closed.\n */\n close(): Promise {\n return Promise.resolve();\n }\n\n _events = new EventEmitter();\n\n /**\n * Listen for an event on the transport instance.\n * Transport implementations may have specific events. Common events include:\n * \"disconnect\" : triggered when the transport is disconnected.\n * @param {string} eventName - The name of the event to listen for.\n * @param {(...args: Array) => any} cb - The callback function to be invoked when the event occurs.\n */\n on(eventName: string, cb: (...args: Array) => any): void {\n this._events.on(eventName, cb);\n }\n\n /**\n * Stop listening to an event on an instance of transport.\n */\n off(eventName: string, cb: (...args: Array) => any): void {\n this._events.removeListener(eventName, cb);\n }\n\n emit(event: string, ...args: any): void {\n this._events.emit(event, ...args);\n }\n\n /**\n * Enable or not logs of the binary exchange\n */\n setDebugMode() {\n console.warn(\n \"setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore.\",\n );\n }\n\n /**\n * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F)\n */\n setExchangeTimeout(exchangeTimeout: number): void {\n this.exchangeTimeout = exchangeTimeout;\n }\n\n /**\n * Define the delay before emitting \"unresponsive\" on an exchange that does not respond\n */\n setExchangeUnresponsiveTimeout(unresponsiveTimeout: number): void {\n this.unresponsiveTimeout = unresponsiveTimeout;\n }\n\n /**\n * Send data to the device using the higher level API.\n *\n * @param {number} cla - The instruction class for the command.\n * @param {number} ins - The instruction code for the command.\n * @param {number} p1 - The first parameter for the instruction.\n * @param {number} p2 - The second parameter for the instruction.\n * @param {Buffer} data - The data to be sent. Defaults to an empty buffer.\n * @param {Array} statusList - A list of acceptable status codes for the response. Defaults to [StatusCodes.OK].\n * @param {Object} options - Contains optional options for the exchange function\n * - abortTimeoutMs: stop the send after a given timeout. Another timeout exists\n * to detect unresponsive device (see `unresponsiveTimeout`). This timeout aborts the exchange.\n * @returns {Promise} A promise that resolves with the response data from the device.\n */\n send = async (\n cla: number,\n ins: number,\n p1: number,\n p2: number,\n data: Buffer = Buffer.alloc(0),\n statusList: Array = [StatusCodes.OK],\n { abortTimeoutMs }: { abortTimeoutMs?: number } = {},\n ): Promise => {\n const tracer = this.tracer.withUpdatedContext({ function: \"send\" });\n\n if (data.length >= 256) {\n tracer.trace(\"data.length exceeded 256 bytes limit\", { dataLength: data.length });\n throw new TransportError(\n \"data.length exceed 256 bytes limit. Got: \" + data.length,\n \"DataLengthTooBig\",\n );\n }\n\n tracer.trace(\"Starting an exchange\", { abortTimeoutMs });\n const response = await this.exchange(\n // The size of the data is added in 1 byte just before `data`\n Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data]),\n { abortTimeoutMs },\n );\n tracer.trace(\"Received response from exchange\");\n const sw = response.readUInt16BE(response.length - 2);\n\n if (!statusList.some(s => s === sw)) {\n throw new TransportStatusError(sw);\n }\n\n return response;\n };\n\n /**\n * create() allows to open the first descriptor available or\n * throw if there is none or if timeout is reached.\n * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase)\n * @example\n TransportFoo.create().then(transport => ...)\n */\n static create(openTimeout = 3000, listenTimeout?: number): Promise {\n return new Promise((resolve, reject) => {\n let found = false;\n const sub = this.listen({\n next: e => {\n found = true;\n if (sub) sub.unsubscribe();\n if (listenTimeoutId) clearTimeout(listenTimeoutId);\n this.open(e.descriptor, openTimeout).then(resolve, reject);\n },\n error: e => {\n if (listenTimeoutId) clearTimeout(listenTimeoutId);\n reject(e);\n },\n complete: () => {\n if (listenTimeoutId) clearTimeout(listenTimeoutId);\n\n if (!found) {\n reject(new TransportError(this.ErrorMessage_NoDeviceFound, \"NoDeviceFound\"));\n }\n },\n });\n const listenTimeoutId = listenTimeout\n ? setTimeout(() => {\n sub.unsubscribe();\n reject(new TransportError(this.ErrorMessage_ListenTimeout, \"ListenTimeout\"));\n }, listenTimeout)\n : null;\n });\n }\n\n // Blocks other exchange to happen concurrently\n exchangeBusyPromise: Promise | null | undefined;\n\n /**\n * Wrapper to make an exchange \"atomic\" (blocking any other exchange)\n *\n * It also handles \"unresponsiveness\" by emitting \"unresponsive\" and \"responsive\" events.\n *\n * @param f The exchange job, using the transport to run\n * @returns a Promise resolving with the output of the given job\n */\n async exchangeAtomicImpl(f: () => Promise): Promise {\n const tracer = this.tracer.withUpdatedContext({\n function: \"exchangeAtomicImpl\",\n unresponsiveTimeout: this.unresponsiveTimeout,\n });\n\n if (this.exchangeBusyPromise) {\n tracer.trace(\"Atomic exchange is already busy\");\n throw new TransportRaceCondition(\n \"An action was already pending on the Ledger device. Please deny or reconnect.\",\n );\n }\n\n // Sets the atomic guard\n let resolveBusy;\n const busyPromise: Promise = new Promise(r => {\n resolveBusy = r;\n });\n this.exchangeBusyPromise = busyPromise;\n\n // The device unresponsiveness handler\n let unresponsiveReached = false;\n const timeout = setTimeout(() => {\n tracer.trace(`Timeout reached, emitting Transport event \"unresponsive\"`, {\n unresponsiveTimeout: this.unresponsiveTimeout,\n });\n unresponsiveReached = true;\n this.emit(\"unresponsive\");\n }, this.unresponsiveTimeout);\n\n try {\n const res = await f();\n\n if (unresponsiveReached) {\n tracer.trace(\"Device was unresponsive, emitting responsive\");\n this.emit(\"responsive\");\n }\n\n return res;\n } finally {\n tracer.trace(\"Finalize, clearing busy guard\");\n\n clearTimeout(timeout);\n if (resolveBusy) resolveBusy();\n this.exchangeBusyPromise = null;\n }\n }\n\n decorateAppAPIMethods(self: Record, methods: Array, scrambleKey: string) {\n for (const methodName of methods) {\n self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey);\n }\n }\n\n _appAPIlock: string | null = null;\n\n decorateAppAPIMethod(\n methodName: string,\n f: (...args: A) => Promise,\n ctx: any,\n scrambleKey: string,\n ): (...args: A) => Promise {\n return async (...args) => {\n const { _appAPIlock } = this;\n\n if (_appAPIlock) {\n return Promise.reject(\n new TransportError(\"Ledger Device is busy (lock \" + _appAPIlock + \")\", \"TransportLocked\"),\n );\n }\n\n try {\n this._appAPIlock = methodName;\n this.setScrambleKey(scrambleKey);\n return await f.apply(ctx, args);\n } finally {\n this._appAPIlock = null;\n }\n };\n }\n\n /**\n * Sets the context used by the logging/tracing mechanism\n *\n * Useful when re-using (cached) the same Transport instance,\n * but with a new tracing context.\n *\n * @param context A TraceContext, that can undefined to reset the context\n */\n setTraceContext(context?: TraceContext) {\n this.tracer = this.tracer.withContext(context);\n }\n\n /**\n * Updates the context used by the logging/tracing mechanism\n *\n * The update only overrides the key-value that are already defined in the current context.\n *\n * @param contextToAdd A TraceContext that will be added to the current context\n */\n updateTraceContext(contextToAdd: TraceContext) {\n this.tracer.updateContext(contextToAdd);\n }\n\n /**\n * Gets the tracing context of the transport instance\n */\n getTraceContext(): TraceContext | undefined {\n return this.tracer.getContext();\n }\n\n static ErrorMessage_ListenTimeout = \"No Ledger device found (timeout)\";\n static ErrorMessage_NoDeviceFound = \"No Ledger device found\";\n}\n", "// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "const {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "const numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "const SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "const parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "const parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "const SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "const parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // Otherwise it can be determined by checking the high version\n\n if (highVersion.patch) {\n // anything higher than a patch bump would result in the wrong version\n return 'patch'\n }\n\n if (highVersion.minor) {\n // anything higher than a minor bump would result in the wrong version\n return 'minor'\n }\n\n // bumping major/minor/patch all have same result\n return 'major'\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are preleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "const SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "const SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "const SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "const parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "const compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "const compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "const SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "const compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "const compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "const compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "const compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "const compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "const compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "const compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "const eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "const SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "class LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "const SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "const Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "const Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "const Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "const SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "const outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "const Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "const Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "import semver from \"semver\";\n\n/**\n * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II)\n *\n ** Model\n * Ledger Nano S : 0x10\n * Ledger Blue : 0x00\n * Ledger Nano X : 0x40\n *\n ** Interface support bitfield\n * Generic HID : 0x01\n * Keyboard HID : 0x02\n * U2F : 0x04\n * CCID : 0x08\n * WebUSB : 0x10\n */\nexport const IIGenericHID = 0x01;\nexport const IIKeyboardHID = 0x02;\nexport const IIU2F = 0x04;\nexport const IICCID = 0x08;\nexport const IIWebUSB = 0x10;\n\nexport enum DeviceModelId {\n /** Ledger Blue */\n blue = \"blue\",\n /** Ledger Nano S */\n nanoS = \"nanoS\",\n /** Ledger Nano S Plus */\n nanoSP = \"nanoSP\",\n /** Ledger Nano X */\n nanoX = \"nanoX\",\n /** Ledger Stax */\n stax = \"stax\",\n /** Ledger Flex (\"europa\" is the internal name) */\n europa = \"europa\", // DO NOT CHANGE TO FLEX or handle all migration issues, things will break\n}\n\nconst devices: { [key in DeviceModelId]: DeviceModel } = {\n [DeviceModelId.blue]: {\n id: DeviceModelId.blue,\n productName: \"Ledger\u00A0Blue\",\n productIdMM: 0x00,\n legacyUsbProductId: 0x0000,\n usbOnly: true,\n memorySize: 480 * 1024,\n masks: [0x31000000, 0x31010000],\n getBlockSize: (_firwareVersion: string): number => 4 * 1024,\n },\n [DeviceModelId.nanoS]: {\n id: DeviceModelId.nanoS,\n productName: \"Ledger\u00A0Nano\u00A0S\",\n productIdMM: 0x10,\n legacyUsbProductId: 0x0001,\n usbOnly: true,\n memorySize: 320 * 1024,\n masks: [0x31100000],\n getBlockSize: (firmwareVersion: string): number =>\n semver.lt(semver.coerce(firmwareVersion) ?? \"\", \"2.0.0\") ? 4 * 1024 : 2 * 1024,\n },\n [DeviceModelId.nanoX]: {\n id: DeviceModelId.nanoX,\n productName: \"Ledger\u00A0Nano\u00A0X\",\n productIdMM: 0x40,\n legacyUsbProductId: 0x0004,\n usbOnly: false,\n memorySize: 2 * 1024 * 1024,\n masks: [0x33000000],\n getBlockSize: (_firwareVersion: string): number => 4 * 1024,\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-0004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-0004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-0004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-0004-0003-4c6564676572\",\n },\n ],\n },\n [DeviceModelId.nanoSP]: {\n id: DeviceModelId.nanoSP,\n productName: \"Ledger Nano S Plus\",\n productIdMM: 0x50,\n legacyUsbProductId: 0x0005,\n usbOnly: true,\n memorySize: 1533 * 1024,\n masks: [0x33100000],\n getBlockSize: (_firmwareVersion: string): number => 32,\n },\n [DeviceModelId.stax]: {\n id: DeviceModelId.stax,\n productName: \"Ledger\u00A0Stax\",\n productIdMM: 0x60,\n legacyUsbProductId: 0x0006,\n usbOnly: false,\n memorySize: 1533 * 1024,\n masks: [0x33200000],\n getBlockSize: (_firmwareVersion: string): number => 32,\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-6004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-6004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-6004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-6004-0003-4c6564676572\",\n },\n ],\n },\n [DeviceModelId.europa]: {\n id: DeviceModelId.europa,\n productName: \"Ledger\u00A0Flex\",\n productIdMM: 0x70,\n legacyUsbProductId: 0x0007,\n usbOnly: false,\n memorySize: 1533 * 1024,\n masks: [0x33300000],\n getBlockSize: (_firmwareVersion: string): number => 32,\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-3004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-3004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-3004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-3004-0003-4c6564676572\",\n },\n ],\n },\n};\n\nconst productMap = {\n Blue: DeviceModelId.blue,\n \"Nano S\": DeviceModelId.nanoS,\n \"Nano S Plus\": DeviceModelId.nanoSP,\n \"Nano X\": DeviceModelId.nanoX,\n Stax: DeviceModelId.stax,\n Europa: DeviceModelId.europa,\n};\n\nconst devicesList: DeviceModel[] = Object.values(devices);\n\n/**\n *\n */\nexport const ledgerUSBVendorId = 0x2c97;\n\n/**\n *\n */\nexport const getDeviceModel = (id: DeviceModelId): DeviceModel => {\n const info = devices[id];\n if (!info) throw new Error(\"device '\" + id + \"' does not exist\");\n return info;\n};\n\n/**\n * Given a `targetId`, return the deviceModel associated to it,\n * based on the first two bytes.\n */\nexport const identifyTargetId = (targetId: number): DeviceModel | null | undefined => {\n const deviceModel = devicesList.find(({ masks }) =>\n masks.find(mask => (targetId & 0xffff0000) === mask),\n );\n\n return deviceModel;\n};\n\n/**\n * From a given USB product id, return the deviceModel associated to it.\n *\n * The mapping from the product id is only based on the 2 most significant bytes.\n * For example, Stax is defined with a product id of 0x60ii, a product id 0x6011 would be mapped to it.\n */\nexport const identifyUSBProductId = (usbProductId: number): DeviceModel | null | undefined => {\n const legacy = devicesList.find(d => d.legacyUsbProductId === usbProductId);\n if (legacy) return legacy;\n const mm = usbProductId >> 8;\n const deviceModel = devicesList.find(d => d.productIdMM === mm);\n return deviceModel;\n};\n\nexport const identifyProductName = (productName: string): DeviceModel | null | undefined => {\n const deviceModel = devicesList.find(d => d.id === productMap[productName]);\n return deviceModel;\n};\n\nconst bluetoothServices: string[] = [];\nconst serviceUuidToInfos: Record = {};\n\nfor (const id in devices) {\n const deviceModel = devices[id];\n const { bluetoothSpec } = deviceModel;\n if (bluetoothSpec) {\n for (let i = 0; i < bluetoothSpec.length; i++) {\n const spec = bluetoothSpec[i];\n bluetoothServices.push(spec.serviceUuid);\n serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[\n spec.serviceUuid.replace(/-/g, \"\")\n ] = {\n deviceModel,\n ...spec,\n };\n }\n }\n}\n\n/**\n *\n */\nexport const getBluetoothServiceUuids = (): string[] => bluetoothServices;\n\n/**\n *\n */\nexport const getInfosForServiceUuid = (uuid: string): BluetoothInfos | undefined =>\n serviceUuidToInfos[uuid.toLowerCase()];\n\n/**\n *\n */\nexport interface DeviceModel {\n id: DeviceModelId;\n productName: string;\n productIdMM: number;\n legacyUsbProductId: number;\n usbOnly: boolean;\n memorySize: number;\n masks: number[];\n // blockSize: number, // THIS FIELD IS DEPRECATED, use getBlockSize\n getBlockSize: (firmwareVersion: string) => number;\n bluetoothSpec?: {\n serviceUuid: string;\n writeUuid: string;\n writeCmdUuid: string;\n notifyUuid: string;\n }[];\n}\n\n/**\n *\n */\nexport interface BluetoothInfos {\n deviceModel: DeviceModel;\n serviceUuid: string;\n writeUuid: string;\n writeCmdUuid: string;\n notifyUuid: string;\n}\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n", "/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n", "import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification, subscriber: Subscriber) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n", "import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n", "/* tslint:disable:no-empty */\nexport function noop() { }\n", "import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification(value: T) {\n return createNotification('N', value, undefined) as NextNotification;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n", "import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber\n */\nexport class Subscriber extends Subscription implements Observer {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber | Observer; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber | Observer) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver implements Observer {\n constructor(private partialObserver: Partial>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber extends Subscriber {\n constructor(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as (((value: T) => void) | undefined),\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent\n * @param subscriber The stopped subscriber\n */\nfunction handleStoppedNotification(notification: ObservableNotification, subscriber: Subscriber) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n", "/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n", "/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity(x: T): T {\n return x;\n}\n", "import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe(fn1: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction, fn3: UnaryFunction): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction,\n ...fns: UnaryFunction[]\n): UnaryFunction;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array>): UnaryFunction {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray(fns: Array>): UnaryFunction {\n if (fns.length === 0) {\n return identity as UnaryFunction;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction) => fn(prev), input as any);\n };\n}\n", "import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable\n */\nexport class Observable implements Subscribable {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator | undefined;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable, subscriber: Subscriber) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new observable\n * @nocollapse\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => {\n return new Observable(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param operator the operator defining the operation to take on the observable\n * @return a new observable with the Operator applied\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift(operator?: Operator): Observable {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * Use it when you have all these Observables, but still nothing is happening.\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {Subscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next a handler for each value emitted by the observable\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void): Promise;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable;\n pipe(op1: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction,\n ...operations: OperatorFunction[]\n ): Observable;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n */\n pipe(...operations: OperatorFunction[]): Observable {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @method toPromise\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver(value: any): value is Observer {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber(value: any): value is Subscriber {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate(\n init: (liftedSource: Observable, subscriber: Subscriber) => (() => void) | void\n): OperatorFunction {\n return (source: Observable) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber, liftedSource: Observable) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n", "import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber extends Subscriber {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n", "import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject extends Observable implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @nocollapse\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = (destination: Observer, source: Observable): AnonymousSubject => {\n return new AnonymousSubject(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift(operator: Operator): Observable {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return {Observable} Observable that the Subject casts to\n */\n asObservable(): Observable {\n const observable: any = new Observable();\n observable.source = this;\n return observable;\n }\n}\n\n/**\n * @class AnonymousSubject\n */\nexport class AnonymousSubject extends Subject {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer,\n source?: Observable\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n", "import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject extends Subject {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param bufferSize The size of the buffer to replay on subscription\n * @param windowTime The amount of time the buffered items will stay buffered\n * @param timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * Just emits 'complete', and nothing else.\n *\n * ![](empty.png)\n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n", "export const isArrayLike = ((x: any): x is ArrayLike => x && typeof x.length === 'number' && typeof x !== 'function');", "import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike {\n return isFunction(value?.then);\n}\n", "import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable {\n return isFunction(input[Symbol_observable]);\n}\n", "import { isFunction } from './isFunction';\n\nexport function isAsyncIterable(obj: any): obj is AsyncIterable {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n", "/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n", "export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n", "import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable {\n return isFunction(input?.[Symbol_iterator]);\n}\n", "import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator(readableStream: ReadableStreamLike): AsyncGenerator {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike(obj: any): obj is ReadableStreamLike {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an