{"version":3,"file":"static/js/main.e269d5bd.js","sources":["../node_modules/@coinbase/wallet-sdk/dist/CoinbaseWalletSDK.js","../node_modules/@coinbase/wallet-sdk/dist/assets/wallet-logo.js","../node_modules/@coinbase/wallet-sdk/dist/core/constants.js","../node_modules/@coinbase/wallet-sdk/dist/core/error/constants.js","../node_modules/@coinbase/wallet-sdk/dist/core/error/errors.js","../node_modules/@coinbase/wallet-sdk/dist/core/error/index.js","../node_modules/@coinbase/wallet-sdk/dist/core/error/serialize.js","../node_modules/@coinbase/wallet-sdk/dist/core/error/utils.js","../node_modules/@coinbase/wallet-sdk/dist/core/type.js","../node_modules/@coinbase/wallet-sdk/dist/core/util.js","../node_modules/@coinbase/wallet-sdk/dist/index.js","../node_modules/@coinbase/wallet-sdk/dist/lib/Cipher.js","../node_modules/@coinbase/wallet-sdk/dist/lib/ScopedLocalStorage.js","../node_modules/@coinbase/wallet-sdk/dist/lib/cssReset-css.js","../node_modules/@coinbase/wallet-sdk/dist/lib/cssReset.js","../node_modules/@coinbase/wallet-sdk/dist/provider/CoinbaseWalletProvider.js","../node_modules/@coinbase/wallet-sdk/dist/provider/DiagnosticLogger.js","../node_modules/@coinbase/wallet-sdk/dist/provider/FilterPolyfill.js","../node_modules/@coinbase/wallet-sdk/dist/provider/SubscriptionManager.js","../node_modules/@coinbase/wallet-sdk/dist/relay/RelayAbstract.js","../node_modules/@coinbase/wallet-sdk/dist/relay/RelayEventManager.js","../node_modules/@coinbase/wallet-sdk/dist/relay/Session.js","../node_modules/@coinbase/wallet-sdk/dist/relay/mobile/MobileRelay.js","../node_modules/@coinbase/wallet-sdk/dist/relay/mobile/MobileRelayUI.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/WalletLinkRelay.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/connection/WalletLinkConnection.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/connection/WalletLinkHTTP.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/connection/WalletLinkWebSocket.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/type/Web3Response.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/WalletLinkRelayUI.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/ConnectContent/ConnectContent-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/ConnectContent/ConnectContent.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/ConnectDialog/ConnectDialog-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/ConnectDialog/ConnectDialog.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/LinkFlow/LinkFlow.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/QRCode.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/RedirectDialog/RedirectDialog-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/RedirectDialog/RedirectDialog.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/Snackbar/Snackbar-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/Snackbar/Snackbar.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/Snackbar/index.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/Spinner/Spinner-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/Spinner/Spinner.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/TryExtensionContent/TryExtensionContent-css.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/TryExtensionContent/TryExtensionContent.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/ArrowLeftIcon.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/CloseIcon.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/CoinbaseWalletRound.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/LaptopIcon.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/QRCodeIcon.js","../node_modules/@coinbase/wallet-sdk/dist/relay/walletlink/ui/components/icons/SafeIcon.js","../node_modules/@coinbase/wallet-sdk/dist/vendor-js/eth-eip712-util/abi.js","../node_modules/@coinbase/wallet-sdk/dist/vendor-js/eth-eip712-util/index.js","../node_modules/@coinbase/wallet-sdk/dist/vendor-js/eth-eip712-util/util.js","../node_modules/@coinbase/wallet-sdk/dist/vendor-js/qrcode-svg/index.js","../node_modules/@coinbase/wallet-sdk/dist/version.js","../node_modules/@coinbase/wallet-sdk/node_modules/eventemitter3/index.js","../../../index.ts","../node_modules/@metamask/utils/src/assert.ts","../node_modules/@metamask/utils/src/base64.ts","../node_modules/@metamask/utils/src/bytes.ts","../node_modules/@metamask/utils/src/checksum.ts","../node_modules/@metamask/utils/src/coercers.ts","../node_modules/@metamask/utils/src/collections.ts","../node_modules/@metamask/utils/src/hex.ts","../node_modules/@metamask/utils/src/index.ts","../node_modules/@metamask/utils/src/json.ts","../node_modules/@metamask/utils/src/logging.ts","../node_modules/@metamask/utils/src/misc.ts","../node_modules/@metamask/utils/src/number.ts","../node_modules/@metamask/utils/src/time.ts","../node_modules/@metamask/utils/src/versions.ts","../node_modules/@stablelib/binary/binary.ts","../node_modules/@stablelib/chacha/chacha.ts","../node_modules/@stablelib/chacha20poly1305/chacha20poly1305.ts","../node_modules/@stablelib/constant-time/constant-time.ts","../node_modules/@stablelib/ed25519/ed25519.ts","../node_modules/@stablelib/hash/hash.ts","../node_modules/@stablelib/hkdf/hkdf.ts","../node_modules/@stablelib/hmac/hmac.ts","../node_modules/@stablelib/int/int.ts","../node_modules/@stablelib/poly1305/poly1305.ts","../node_modules/@stablelib/random/random.ts","../node_modules/@stablelib/random/source/browser.ts","../node_modules/@stablelib/random/source/node.ts","../node_modules/@stablelib/random/source/system.ts","../node_modules/@stablelib/sha256/sha256.ts","../node_modules/@stablelib/sha512/sha512.ts","../node_modules/@stablelib/wipe/wipe.ts","../node_modules/@stablelib/x25519/x25519.ts","../../crypto.ts","../../env.ts","../../index.ts","../node_modules/@walletconnect/environment/node_modules/tslib/tslib.es6.js","../../events.ts","../../../../src/constants/heartbeat.ts","../../../../src/constants/index.ts","../../heartbeat.ts","../../../../src/types/heartbeat.ts","../../../../src/types/index.ts","../node_modules/@walletconnect/heartbeat/node_modules/tslib/tslib.es6.js","../../../../src/constants/misc.ts","../../../../src/constants/time.ts","../../../../src/types/watch.ts","../../../../src/utils/convert.ts","../../../../src/utils/delay.ts","../../../../src/utils/index.ts","../../watch.ts","../node_modules/@walletconnect/time/node_modules/tslib/tslib.es6.js","../node_modules/async-mutex/lib/Mutex.js","../node_modules/async-mutex/lib/Semaphore.js","../node_modules/async-mutex/lib/index.js","../node_modules/async-mutex/lib/withTimeout.js","../node_modules/base64-js/index.js","../node_modules/bn.js/lib/bn.js","../node_modules/buffer/index.js","../node_modules/clsx/dist/clsx.m.js","../node_modules/cross-fetch/dist/browser-ponyfill.js","../node_modules/dayjs/dayjs.min.js","../node_modules/dayjs/plugin/relativeTime.js","../node_modules/dayjs/plugin/updateLocale.js","../node_modules/debug/src/browser.js","../node_modules/debug/src/common.js","../node_modules/decode-uri-component/index.js","../node_modules/dijkstrajs/dijkstra.js","../node_modules/encode-utf8/index.js","../node_modules/eth-block-tracker/src/BaseBlockTracker.ts","../node_modules/eth-block-tracker/src/PollingBlockTracker.ts","../node_modules/eth-block-tracker/src/SubscribeBlockTracker.ts","../node_modules/eth-block-tracker/src/index.ts","../node_modules/eth-block-tracker/src/logging-utils.ts","../node_modules/eth-block-tracker/node_modules/pify/index.js","../node_modules/eth-json-rpc-filters/base-filter-history.js","../node_modules/eth-json-rpc-filters/base-filter.js","../node_modules/eth-json-rpc-filters/block-filter.js","../node_modules/eth-json-rpc-filters/getBlocksForRange.js","../node_modules/eth-json-rpc-filters/hexUtils.js","../node_modules/eth-json-rpc-filters/index.js","../node_modules/eth-json-rpc-filters/log-filter.js","../node_modules/eth-json-rpc-filters/node_modules/pify/index.js","../node_modules/eth-json-rpc-filters/subscriptionManager.js","../node_modules/eth-json-rpc-filters/tx-filter.js","../node_modules/eth-query/index.js","../../src/classes.ts","../../src/error-constants.ts","../../src/errors.ts","../../src/index.ts","../../src/utils.ts","../node_modules/events/events.js","../node_modules/fast-safe-stringify/index.js","../node_modules/filter-obj/index.js","../node_modules/ieee754/index.js","../node_modules/inherits/inherits_browser.js","../node_modules/isomorphic-unfetch/browser.js","../../src/JsonRpcEngine.ts","../../src/createAsyncMiddleware.ts","../../src/createScaffoldMiddleware.ts","../../src/getUniqueId.ts","../../src/idRemapMiddleware.ts","../../src/mergeMiddleware.ts","../index.ts","../node_modules/json-rpc-random-id/index.js","../node_modules/keccak/js.js","../node_modules/keccak/lib/api/index.js","../node_modules/keccak/lib/api/keccak.js","../node_modules/keccak/lib/api/shake.js","../node_modules/keccak/lib/keccak-state-unroll.js","../node_modules/keccak/lib/keccak.js","../node_modules/lodash.isequal/index.js","../node_modules/ms/index.js","../node_modules/preact/src/constants.js","../node_modules/preact/src/util.js","../node_modules/preact/src/options.js","../node_modules/preact/src/create-element.js","../node_modules/preact/src/component.js","../node_modules/preact/src/diff/props.js","../node_modules/preact/src/create-context.js","../node_modules/preact/src/diff/children.js","../node_modules/preact/src/diff/index.js","../node_modules/preact/src/render.js","../node_modules/preact/src/clone-element.js","../node_modules/preact/src/diff/catch-error.js","../node_modules/preact/hooks/src/index.js","../node_modules/proxy-compare/src/index.ts","../node_modules/qrcode/lib/browser.js","../node_modules/qrcode/lib/can-promise.js","../node_modules/qrcode/lib/core/alignment-pattern.js","../node_modules/qrcode/lib/core/alphanumeric-data.js","../node_modules/qrcode/lib/core/bit-buffer.js","../node_modules/qrcode/lib/core/bit-matrix.js","../node_modules/qrcode/lib/core/byte-data.js","../node_modules/qrcode/lib/core/error-correction-code.js","../node_modules/qrcode/lib/core/error-correction-level.js","../node_modules/qrcode/lib/core/finder-pattern.js","../node_modules/qrcode/lib/core/format-info.js","../node_modules/qrcode/lib/core/galois-field.js","../node_modules/qrcode/lib/core/kanji-data.js","../node_modules/qrcode/lib/core/mask-pattern.js","../node_modules/qrcode/lib/core/mode.js","../node_modules/qrcode/lib/core/numeric-data.js","../node_modules/qrcode/lib/core/polynomial.js","../node_modules/qrcode/lib/core/qrcode.js","../node_modules/qrcode/lib/core/reed-solomon-encoder.js","../node_modules/qrcode/lib/core/regex.js","../node_modules/qrcode/lib/core/segments.js","../node_modules/qrcode/lib/core/utils.js","../node_modules/qrcode/lib/core/version-check.js","../node_modules/qrcode/lib/core/version.js","../node_modules/qrcode/lib/renderer/canvas.js","../node_modules/qrcode/lib/renderer/svg-tag.js","../node_modules/qrcode/lib/renderer/utils.js","../node_modules/query-string/index.js","../node_modules/quick-format-unescaped/index.js","../node_modules/react-device-detect/dist/lib.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/readable-stream/errors-browser.js","../node_modules/readable-stream/lib/_stream_duplex.js","../node_modules/readable-stream/lib/_stream_passthrough.js","../node_modules/readable-stream/lib/_stream_readable.js","../node_modules/readable-stream/lib/_stream_transform.js","../node_modules/readable-stream/lib/_stream_writable.js","../node_modules/readable-stream/lib/internal/streams/async_iterator.js","../node_modules/readable-stream/lib/internal/streams/buffer_list.js","../node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../node_modules/readable-stream/lib/internal/streams/from-browser.js","../node_modules/readable-stream/lib/internal/streams/pipeline.js","../node_modules/readable-stream/lib/internal/streams/state.js","../node_modules/readable-stream/lib/internal/streams/stream-browser.js","../node_modules/readable-stream/readable-browser.js","../node_modules/safe-buffer/index.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/semver/classes/comparator.js","../node_modules/semver/classes/range.js","../node_modules/semver/classes/semver.js","../node_modules/semver/functions/clean.js","../node_modules/semver/functions/cmp.js","../node_modules/semver/functions/coerce.js","../node_modules/semver/functions/compare-build.js","../node_modules/semver/functions/compare-loose.js","../node_modules/semver/functions/compare.js","../node_modules/semver/functions/diff.js","../node_modules/semver/functions/eq.js","../node_modules/semver/functions/gt.js","../node_modules/semver/functions/gte.js","../node_modules/semver/functions/inc.js","../node_modules/semver/functions/lt.js","../node_modules/semver/functions/lte.js","../node_modules/semver/functions/major.js","../node_modules/semver/functions/minor.js","../node_modules/semver/functions/neq.js","../node_modules/semver/functions/parse.js","../node_modules/semver/functions/patch.js","../node_modules/semver/functions/prerelease.js","../node_modules/semver/functions/rcompare.js","../node_modules/semver/functions/rsort.js","../node_modules/semver/functions/satisfies.js","../node_modules/semver/functions/sort.js","../node_modules/semver/functions/valid.js","../node_modules/semver/index.js","../node_modules/semver/internal/constants.js","../node_modules/semver/internal/debug.js","../node_modules/semver/internal/identifiers.js","../node_modules/semver/internal/parse-options.js","../node_modules/semver/internal/re.js","../node_modules/semver/node_modules/lru-cache/index.js","../node_modules/semver/node_modules/yallist/iterator.js","../node_modules/semver/node_modules/yallist/yallist.js","../node_modules/semver/ranges/gtr.js","../node_modules/semver/ranges/intersects.js","../node_modules/semver/ranges/ltr.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/outside.js","../node_modules/semver/ranges/simplify.js","../node_modules/semver/ranges/subset.js","../node_modules/semver/ranges/to-comparators.js","../node_modules/semver/ranges/valid.js","../node_modules/sha.js/hash.js","../node_modules/sha.js/index.js","../node_modules/sha.js/sha.js","../node_modules/sha.js/sha1.js","../node_modules/sha.js/sha224.js","../node_modules/sha.js/sha256.js","../node_modules/sha.js/sha384.js","../node_modules/sha.js/sha512.js","../node_modules/split-on-first/index.js","../node_modules/strict-uri-encode/index.js","../node_modules/string_decoder/lib/string_decoder.js","../node_modules/ua-parser-js/dist/ua-parser.min.js","../node_modules/unfetch/src/index.mjs","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/use-sync-external-store/shim/index.js","../node_modules/util-deprecate/browser.js","../node_modules/ws/browser.js","../node_modules/xtend/immutable.js","../node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js","../node_modules/pino/browser.js","../node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js","../../../../../src/utils/DateUtil.ts","../../../../../src/utils/NetworkUtil.ts","../node_modules/bignumber.js/bignumber.mjs","../../../../../src/utils/NumberUtil.ts","../../../../../src/utils/ConstantsUtil.ts","../../../../../src/utils/CoreHelperUtil.ts","../../../../../src/utils/FetchUtil.ts","../../../../../src/controllers/OptionsController.ts","../../../../../src/controllers/BlockchainApiController.ts","../../../../../src/controllers/SnackController.ts","../../../../../src/controllers/AccountController.ts","../../../../../src/utils/StorageUtil.ts","../../../../../src/controllers/AssetController.ts","../../../../../src/controllers/ThemeController.ts","../../../../../src/controllers/ConnectorController.ts","../../../../../src/controllers/PublicStateController.ts","../../../../../src/controllers/EventsController.ts","../../../../../src/controllers/NetworkController.ts","../../../../../src/controllers/ApiController.ts","../../../../../src/controllers/RouterController.ts","../../../../../src/controllers/ModalController.ts","../../../../../src/controllers/OnRampController.ts","../../../../../src/controllers/TransactionsController.ts","../../../../../src/controllers/ConnectionController.ts","../../../../../src/controllers/SendController.ts","../../../../../src/utils/AssetUtil.ts","../../../../../src/utils/RouterUtil.ts","../../../../../../src/modal/w3m-modal/styles.ts","../../../../../../src/modal/w3m-modal/index.ts","../node_modules/@web3modal/scaffold/node_modules/@lit/reactive-element/src/css-tag.ts","../node_modules/@web3modal/scaffold/node_modules/@lit/reactive-element/src/reactive-element.ts","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/lit-html.ts","../node_modules/@web3modal/scaffold/node_modules/@lit/reactive-element/src/decorators/property.ts","../node_modules/@web3modal/scaffold/node_modules/@lit/reactive-element/src/decorators/state.ts","../node_modules/@web3modal/scaffold/node_modules/lit-element/src/lit-element.ts","../node_modules/@web3modal/ui/node_modules/@lit/reactive-element/src/css-tag.ts","../node_modules/@web3modal/ui/node_modules/@lit/reactive-element/src/reactive-element.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/lit-html.ts","../node_modules/@web3modal/ui/node_modules/lit-element/src/lit-element.ts","../../../../../../src/assets/svg/convert-input-mask-bottom.ts","../../../../../../src/assets/svg/convert-input-mask-top.ts","../../../../../src/utils/ThemeUtil.ts","../../../../../src/utils/WebComponentsUtil.ts","../../../../../../src/components/wui-card/styles.ts","../../../../../../src/components/wui-card/index.ts","../node_modules/@web3modal/ui/node_modules/@lit/reactive-element/src/decorators/property.ts","../node_modules/@web3modal/ui/node_modules/@lit/reactive-element/src/decorators/state.ts","../../../../../../src/components/wui-icon/styles.ts","../../../../../../src/assets/svg/all-wallets.ts","../../../../../../src/assets/svg/arrow-bottom-circle.ts","../../../../../../src/assets/svg/app-store.ts","../../../../../../src/assets/svg/apple.ts","../../../../../../src/assets/svg/arrow-bottom.ts","../../../../../../src/assets/svg/arrow-left.ts","../../../../../../src/assets/svg/arrow-right.ts","../../../../../../src/assets/svg/arrow-top.ts","../../../../../../src/assets/svg/browser.ts","../../../../../../src/assets/svg/checkmark.ts","../../../../../../src/assets/svg/chevron-bottom.ts","../../../../../../src/assets/svg/chevron-left.ts","../../../../../../src/assets/svg/chevron-right.ts","../../../../../../src/assets/svg/chevron-top.ts","../../../../../../src/assets/svg/chrome-store.ts","../../../../../../src/assets/svg/clock.ts","../../../../../../src/assets/svg/close.ts","../../../../../../src/assets/svg/coinPlaceholder.ts","../../../../../../src/assets/svg/compass.ts","../../../../../../src/assets/svg/copy.ts","../../../../../../src/assets/svg/add.ts","../../../../../../src/assets/svg/cursor.ts","../../../../../../src/assets/svg/desktop.ts","../../../../../../src/assets/svg/disconnect.ts","../../../../../../src/assets/svg/discord.ts","../../../../../../src/assets/svg/etherscan.ts","../../../../../../src/assets/svg/extension.ts","../../../../../../src/assets/svg/external-link.ts","../../../../../../src/assets/svg/facebook.ts","../../../../../../src/assets/svg/filters.ts","../../../../../../src/assets/svg/github.ts","../../../../../../src/assets/svg/google.ts","../../../../../../src/assets/svg/help-circle.ts","../../../../../../src/assets/svg/info-circle.ts","../../../../../../src/assets/svg/mail.ts","../../../../../../src/assets/svg/mobile.ts","../../../../../../src/assets/svg/network-placeholder.ts","../../../../../../src/assets/svg/nftPlaceholder.ts","../../../../../../src/assets/svg/off.ts","../../../../../../src/assets/svg/play-store.ts","../../../../../../src/assets/svg/qr-code.ts","../../../../../../src/assets/svg/refresh.ts","../../../../../../src/assets/svg/search.ts","../../../../../../src/assets/svg/send.ts","../../../../../../src/assets/svg/swapHorizontal.ts","../../../../../../src/assets/svg/swapHorizontalBold.ts","../../../../../../src/assets/svg/swapHorizontalMedium.ts","../../../../../../src/assets/svg/swapHorizontalRoundedBold.ts","../../../../../../src/assets/svg/swapVertical.ts","../../../../../../src/assets/svg/telegram.ts","../../../../../../src/assets/svg/twitch.ts","../../../../../../src/assets/svg/twitter.ts","../../../../../../src/assets/svg/twitterIcon.ts","../../../../../../src/assets/svg/verify.ts","../../../../../../src/assets/svg/verify-filled.ts","../../../../../../src/assets/svg/wallet-placeholder.ts","../../../../../../src/assets/svg/wallet.ts","../../../../../../src/assets/svg/walletconnect.ts","../../../../../../src/assets/svg/warning-circle.ts","../../../../../../src/assets/svg/recycle-horizontal.ts","../../../../../../src/assets/svg/bank.ts","../../../../../../src/assets/svg/card.ts","../../../../../../src/assets/svg/plus.ts","../../../../../../src/assets/svg/cursor-transparent.ts","../../../../../../src/components/wui-icon/index.ts","../../../../../../src/assets/svg/checkmark-bold.ts","../../../../../../src/components/wui-image/styles.ts","../../../../../../src/components/wui-image/index.ts","../../../../../../src/components/wui-loading-hexagon/styles.ts","../../../../../../src/components/wui-loading-hexagon/index.ts","../../../../../../src/components/wui-loading-spinner/styles.ts","../../../../../../src/components/wui-loading-spinner/index.ts","../../../../../../src/components/wui-loading-thumbnail/styles.ts","../../../../../../src/components/wui-loading-thumbnail/index.ts","../../../../../../src/components/wui-shimmer/styles.ts","../../../../../../src/components/wui-shimmer/index.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/directive.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/directives/class-map.ts","../../../../../../src/components/wui-text/styles.ts","../../../../../../src/components/wui-text/index.ts","../../../../../../src/assets/visual/browser.ts","../../../../../../src/assets/visual/dao.ts","../../../../../../src/assets/visual/defi.ts","../../../../../../src/assets/visual/defiAlt.ts","../../../../../../src/assets/visual/eth.ts","../../../../../../src/assets/visual/layers.ts","../../../../../../src/assets/visual/lock.ts","../../../../../../src/assets/visual/login.ts","../../../../../../src/assets/visual/network.ts","../../../../../../src/assets/visual/nft.ts","../../../../../../src/assets/visual/noun.ts","../../../../../../src/assets/visual/profile.ts","../../../../../../src/assets/visual/system.ts","../../../../../../src/assets/visual/coinbase.ts","../../../../../../src/assets/visual/moonpay.ts","../../../../../../src/assets/visual/stripe.ts","../../../../../../src/assets/visual/paypal.ts","../../../../../../src/assets/visual/onramp-card.ts","../../../../../../src/assets/visual/google.ts","../../../../../../src/assets/visual/pencil.ts","../../../../../../src/assets/visual/lightbulb.ts","../../../../../../src/components/wui-visual/styles.ts","../../../../../../src/components/wui-visual/index.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/directives/if-defined.ts","../../../../../src/utils/UiHelperUtil.ts","../../../../../../src/layout/wui-flex/styles.ts","../../../../../../src/layout/wui-flex/index.ts","../../../../../../src/composites/wui-avatar/styles.ts","../../../../../../src/composites/wui-avatar/index.ts","../../../../../../src/composites/wui-icon-box/styles.ts","../../../../../../src/composites/wui-icon-box/index.ts","../../../../../../src/composites/wui-account-button/styles.ts","../../../../../../src/composites/wui-account-button/index.ts","../../../../../../src/composites/wui-wallet-image/styles.ts","../../../../../../src/composites/wui-wallet-image/index.ts","../../../../../../src/composites/wui-all-wallets-image/styles.ts","../../../../../../src/composites/wui-all-wallets-image/index.ts","../../../../../../src/composites/wui-button/styles.ts","../../../../../../src/composites/wui-button/index.ts","../../../../../../src/assets/svg/networkMd.ts","../../../../../../src/composites/wui-card-select-loader/styles.ts","../../../../../../src/composites/wui-card-select-loader/index.ts","../../../../../../src/assets/svg/networkSm.ts","../../../../../../src/assets/svg/networkLg.ts","../../../../../../src/composites/wui-network-image/styles.ts","../../../../../../src/composites/wui-network-image/index.ts","../../../../../../src/composites/wui-card-select/styles.ts","../../../../../../src/composites/wui-card-select/index.ts","../../../../../../src/composites/wui-chip/styles.ts","../../../../../../src/composites/wui-chip/index.ts","../../../../../../src/composites/wui-connect-button/styles.ts","../../../../../../src/composites/wui-connect-button/index.ts","../../../../../../src/composites/wui-cta-button/styles.ts","../../../../../../src/composites/wui-cta-button/index.ts","../../../../../../src/composites/wui-details-group/styles.ts","../../../../../../src/composites/wui-details-group/index.ts","../../../../../../src/composites/wui-details-group-item/styles.ts","../../../../../../src/composites/wui-details-group-item/index.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/directive-helpers.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/async-directive.ts","../node_modules/@web3modal/ui/node_modules/lit-html/src/directives/ref.ts","../../../../../../src/composites/wui-input-text/styles.ts","../../../../../../src/composites/wui-input-text/index.ts","../../../../../../src/composites/wui-email-input/styles.ts","../../../../../../src/composites/wui-email-input/index.ts","../../../../../../src/composites/wui-icon-link/styles.ts","../../../../../../src/composites/wui-icon-link/index.ts","../../../../../../src/composites/wui-input-element/styles.ts","../../../../../../src/composites/wui-input-element/index.ts","../../../../../../src/composites/wui-input-numeric/styles.ts","../../../../../../src/composites/wui-input-numeric/index.ts","../../../../../../src/composites/wui-link/styles.ts","../../../../../../src/composites/wui-link/index.ts","../../../../../../src/composites/wui-list-item/styles.ts","../../../../../../src/composites/wui-list-item/index.ts","../../../../../src/utils/TypeUtil.ts","../../../../../../src/composites/wui-transaction-visual/styles.ts","../../../../../../src/composites/wui-transaction-visual/index.ts","../../../../../../src/composites/wui-transaction-list-item/styles.ts","../../../../../../src/composites/wui-transaction-list-item/index.ts","../../../../../../src/composites/wui-transaction-list-item-loader/styles.ts","../../../../../../src/composites/wui-transaction-list-item-loader/index.ts","../../../../../../src/composites/wui-tag/styles.ts","../../../../../../src/composites/wui-tag/index.ts","../../../../../../src/composites/wui-list-wallet/styles.ts","../../../../../../src/composites/wui-list-wallet/index.ts","../../../../../../src/composites/wui-logo/styles.ts","../../../../../../src/composites/wui-logo/index.ts","../../../../../../src/composites/wui-logo-select/styles.ts","../../../../../../src/composites/wui-logo-select/index.ts","../../../../../../src/composites/wui-network-button/styles.ts","../../../../../../src/composites/wui-network-button/index.ts","../../../../../../src/composites/wui-otp/styles.ts","../../../../../../src/composites/wui-otp/index.ts","../../../../../src/utils/QrCode.ts","../../../../../../src/composites/wui-qr-code/styles.ts","../../../../../../src/composites/wui-qr-code/index.ts","../../../../../../src/composites/wui-search-bar/styles.ts","../../../../../../src/composites/wui-search-bar/index.ts","../../../../../../src/composites/wui-snackbar/styles.ts","../../../../../../src/composites/wui-snackbar/index.ts","../../../../../../src/composites/wui-tabs/styles.ts","../../../../../../src/composites/wui-tabs/index.ts","../../../../../../src/composites/wui-token-button/styles.ts","../../../../../../src/composites/wui-token-button/index.ts","../../../../../../src/composites/wui-tooltip/styles.ts","../../../../../../src/composites/wui-tooltip/index.ts","../../../../../../src/composites/wui-token-list-item/styles.ts","../../../../../../src/composites/wui-token-list-item/index.ts","../../../../../../src/composites/wui-visual-thumbnail/styles.ts","../../../../../../src/composites/wui-visual-thumbnail/index.ts","../../../../../../src/composites/wui-notice-card/styles.ts","../../../../../../src/composites/wui-notice-card/index.ts","../../../../../../src/composites/wui-list-accordion/styles.ts","../../../../../../src/composites/wui-list-accordion/index.ts","../../../../../../src/composites/wui-list-content/styles.ts","../../../../../../src/composites/wui-list-content/index.ts","../../../../../../src/composites/wui-list-network/styles.ts","../../../../../../src/composites/wui-list-network/index.ts","../../../../../../src/composites/wui-list-wallet-transaction/styles.ts","../../../../../../src/composites/wui-list-wallet-transaction/index.ts","../../../../../../src/composites/wui-onramp-activity-item/styles.ts","../../../../../../src/composites/wui-onramp-activity-item/index.ts","../../../../../../src/composites/wui-onramp-provider-item/styles.ts","../../../../../../src/composites/wui-onramp-provider-item/index.ts","../../../../../../src/composites/wui-promo/styles.ts","../../../../../../src/composites/wui-promo/index.ts","../../../../../../src/composites/wui-tooltip-select/styles.ts","../../../../../../src/composites/wui-tooltip-select/index.ts","../../../../../../src/composites/wui-balance/styles.ts","../../../../../../src/composites/wui-balance/index.ts","../../../../../../src/composites/wui-profile-button/styles.ts","../../../../../../src/composites/wui-profile-button/index.ts","../../../../../../src/composites/wui-chip-button/styles.ts","../../../../../../src/composites/wui-chip-button/index.ts","../../../../../../src/composites/wui-compatible-network/styles.ts","../../../../../../src/composites/wui-compatible-network/index.ts","../../../../../../src/composites/wui-banner/styles.ts","../../../../../../src/composites/wui-banner/index.ts","../../../../../../src/composites/wui-list-token/styles.ts","../../../../../../src/composites/wui-list-token/index.ts","../../../../../../src/composites/wui-list-description/styles.ts","../../../../../../src/composites/wui-list-description/index.ts","../../../../../../src/composites/wui-input-amount/styles.ts","../../../../../../src/composites/wui-input-amount/index.ts","../../../../../../src/composites/wui-preview-item/styles.ts","../../../../../../src/composites/wui-preview-item/index.ts","../../../../../../src/layout/wui-grid/styles.ts","../../../../../../src/layout/wui-grid/index.ts","../../../../../../src/layout/wui-separator/styles.ts","../../../../../../src/layout/wui-separator/index.ts","../../../../../src/utils/TransactionUtil.ts","../../src/error.ts","../../src/struct.ts","../../src/structs/utilities.ts","../../src/structs/types.ts","../../src/structs/coercions.ts","../../src/structs/refinements.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/valtio/esm/vanilla.mjs","../node_modules/valtio/esm/vanilla/utils.mjs","../webpack/bootstrap","../webpack/runtime/amd options","../webpack/runtime/compat get default export","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/node module decorator","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","components/ui/UIButton.jsx","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/directives/if-defined.ts","../../../../../../src/modal/w3m-account-button/index.ts","../../../../../../src/modal/w3m-button/styles.ts","../../../../../../src/modal/w3m-button/index.ts","../../../../../../src/modal/w3m-connect-button/index.ts","../../../../../../src/modal/w3m-network-button/styles.ts","../../../../../../src/modal/w3m-network-button/index.ts","../../../../../../src/modal/w3m-router/styles.ts","../../../../../../src/modal/w3m-router/index.ts","../../../../../../src/modal/w3m-onramp-widget/styles.ts","../../../../../../src/modal/w3m-onramp-widget/index.ts","../../../../../../src/views/w3m-account-settings-view/styles.ts","../../../../src/W3mFrameConstants.ts","../node_modules/zod/lib/index.mjs","../../../../src/W3mFrameSchema.ts","../../../../src/W3mFrameStorage.ts","../../../../src/W3mFrameHelpers.ts","../../../../src/W3mFrame.ts","../../../../src/W3mFrameProvider.ts","../../../../../../src/views/w3m-account-settings-view/index.ts","../../../../../../src/views/w3m-account-view/index.ts","../../../../../../src/views/w3m-all-wallets-view/index.ts","../../../../../../src/views/w3m-buy-in-progress-view/styles.ts","../../../../../../src/views/w3m-buy-in-progress-view/index.ts","../../../../../../src/views/w3m-connect-view/styles.ts","../../../../src/ConstantsUtil.ts","../../../../src/PresetsUtil.ts","../../../../src/HelpersUtil.ts","../../../../../../src/views/w3m-connect-view/index.ts","../../../../../../src/utils/w3m-connecting-widget/styles.ts","../../../../../../src/utils/w3m-connecting-widget/index.ts","../../../../../../src/views/w3m-connecting-external-view/index.ts","../../../../../../src/views/w3m-connecting-wc-view/index.ts","../../../../../../src/views/w3m-downloads-view/index.ts","../../../../../../src/views/w3m-get-wallet-view/index.ts","../../../../../../src/views/w3m-network-switch-view/styles.ts","../../../../../../src/views/w3m-network-switch-view/index.ts","../../../../../../src/views/w3m-networks-view/styles.ts","../../../../../../src/views/w3m-networks-view/index.ts","../../../../../../src/views/w3m-onramp-activity-view/styles.ts","../../../../../../src/views/w3m-onramp-activity-view/index.ts","../../../../../../src/views/w3m-onramp-fiat-select-view/styles.ts","../../../../../../src/views/w3m-onramp-fiat-select-view/index.ts","../../../../../../src/views/w3m-onramp-providers-view/index.ts","../../../../../../src/views/w3m-onramp-tokens-select-view/styles.ts","../../../../../../src/views/w3m-onramp-tokens-select-view/index.ts","../../../../../../src/views/w3m-transactions-view/styles.ts","../../../../../../src/views/w3m-transactions-view/index.ts","../../../../../../src/views/w3m-what-is-a-network-view/index.ts","../../../../../../src/views/w3m-what-is-a-wallet-view/index.ts","../../../../../../src/views/w3m-what-is-a-buy-view/index.ts","../../../../../../src/utils/w3m-email-otp-widget/styles.ts","../../../../../../src/utils/w3m-email-otp-widget/index.ts","../../../../../../src/views/w3m-email-verify-otp-view/index.ts","../../../../../../src/views/w3m-email-verify-device-view/styles.ts","../../../../../../src/views/w3m-email-verify-device-view/index.ts","../../../../../../src/views/w3m-approve-transaction-view/styles.ts","../../../../../../src/views/w3m-approve-transaction-view/index.ts","../../../../../../src/views/w3m-upgrade-wallet-view/index.ts","../../../../../../src/views/w3m-upgrade-to-smart-account-view/index.ts","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/directive-helpers.ts","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/directive.ts","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/async-directive.ts","../node_modules/@web3modal/scaffold/node_modules/lit-html/src/directives/ref.ts","../../../../../../src/views/w3m-update-email-wallet-view/styles.ts","../../../../../../src/views/w3m-update-email-wallet-view/index.ts","../../../../../../src/views/w3m-update-email-primary-otp-view/index.ts","../../../../../../src/views/w3m-update-email-secondary-otp-view/index.ts","../../../../../../src/views/w3m-unsupported-chain-view/styles.ts","../../../../../../src/views/w3m-unsupported-chain-view/index.ts","../../../../../../src/views/w3m-wallet-receive-view/styles.ts","../../../../../../src/views/w3m-wallet-receive-view/index.ts","../../../../../../src/views/w3m-wallet-compatible-networks-view/styles.ts","../../../../../../src/views/w3m-wallet-compatible-networks-view/index.ts","../../../../../../src/views/w3m-wallet-send-view/styles.ts","../../../../../../src/views/w3m-wallet-send-view/index.ts","../../../../../../src/views/w3m-wallet-send-select-token-view/styles.ts","../../../../../../src/views/w3m-wallet-send-select-token-view/index.ts","../../../../../../src/views/w3m-wallet-send-preview-view/styles.ts","../../../../../../src/views/w3m-wallet-send-preview-view/index.ts","../../../../../../src/partials/w3m-all-wallets-list/styles.ts","../../../../../src/utils/markWalletsAsInstalled.ts","../../../../../../src/partials/w3m-all-wallets-list/index.ts","../../../../../../src/partials/w3m-all-wallets-search/styles.ts","../../../../../../src/partials/w3m-all-wallets-search/index.ts","../../../../../../src/partials/w3m-connecting-header/index.ts","../../../../../../src/partials/w3m-connecting-wc-browser/index.ts","../../../../../../src/partials/w3m-connecting-wc-desktop/index.ts","../../../../../../src/partials/w3m-connecting-wc-mobile/index.ts","../../../../../../src/partials/w3m-connecting-wc-qrcode/styles.ts","../../../../../../src/partials/w3m-connecting-wc-qrcode/index.ts","../../../../../../src/partials/w3m-connecting-wc-unsupported/index.ts","../../../../../../src/partials/w3m-connecting-wc-web/index.ts","../../../../../../src/partials/w3m-convert-details/styles.ts","../../../../../../src/partials/w3m-convert-details/index.ts","../../../../../../src/partials/w3m-convert-input/styles.ts","../../../../../../src/partials/w3m-convert-input/index.ts","../../../../../../src/partials/w3m-header/styles.ts","../../../../../../src/partials/w3m-header/index.ts","../../../../../../src/partials/w3m-help-widget/index.ts","../../../../../../src/partials/w3m-swap-input/styles.ts","../../../../../../src/partials/w3m-swap-input/index.ts","../../../../../../src/partials/w3m-legal-footer/styles.ts","../../../../../../src/partials/w3m-legal-footer/index.ts","../../../../../../src/partials/w3m-mobile-download-links/styles.ts","../../../../../../src/partials/w3m-mobile-download-links/index.ts","../../../../../../src/partials/w3m-onramp-providers-footer/styles.ts","../../../../../../src/partials/w3m-onramp-providers-footer/index.ts","../../../../../../src/partials/w3m-snackbar/styles.ts","../../../../../../src/partials/w3m-snackbar/index.ts","../../../../../../src/partials/w3m-email-login-widget/styles.ts","../../../../../../src/partials/w3m-email-login-widget/index.ts","../../../../../../src/partials/w3m-account-default-widget/styles.ts","../../../../../../src/partials/w3m-account-default-widget/index.ts","../../../../../../src/partials/w3m-account-wallet-features-widget/styles.ts","../../../../../../src/partials/w3m-account-wallet-features-widget/index.ts","../../../../../../src/partials/w3m-account-activity-widget/styles.ts","../../../../../../src/partials/w3m-account-activity-widget/index.ts","../../../../../../src/partials/w3m-account-nfts-widget/styles.ts","../../../../../../src/partials/w3m-account-nfts-widget/index.ts","../../../../../../src/partials/w3m-account-tokens-widget/styles.ts","../../../../../../src/partials/w3m-account-tokens-widget/index.ts","../../../../../../src/partials/w3m-activity-list/styles.ts","../../../../../../src/partials/w3m-activity-list/index.ts","../../../../../../src/partials/w3m-input-token/styles.ts","../../../../../../src/partials/w3m-input-token/index.ts","../../../../../../src/partials/w3m-input-address/styles.ts","../../../../../../src/partials/w3m-input-address/index.ts","../../../../../../src/partials/w3m-wallet-send-details/styles.ts","../../../../../../src/partials/w3m-wallet-send-details/index.ts","../../../../src/client.ts","../node_modules/uint8arrays/esm/src/util/as-uint8array.js","../node_modules/uint8arrays/esm/src/alloc.js","../node_modules/uint8arrays/esm/src/concat.js","../node_modules/multiformats/esm/vendor/base-x.js","../node_modules/multiformats/esm/src/bytes.js","../node_modules/multiformats/esm/src/bases/base.js","../node_modules/multiformats/esm/src/bases/identity.js","../node_modules/multiformats/esm/src/bases/base2.js","../node_modules/multiformats/esm/src/bases/base8.js","../node_modules/multiformats/esm/src/bases/base10.js","../node_modules/multiformats/esm/src/bases/base16.js","../node_modules/multiformats/esm/src/bases/base32.js","../node_modules/multiformats/esm/src/bases/base36.js","../node_modules/multiformats/esm/src/bases/base58.js","../node_modules/multiformats/esm/src/bases/base64.js","../node_modules/multiformats/esm/src/bases/base256emoji.js","../node_modules/multiformats/esm/vendor/varint.js","../node_modules/multiformats/esm/src/varint.js","../node_modules/multiformats/esm/src/hashes/digest.js","../node_modules/multiformats/esm/src/hashes/hasher.js","../node_modules/multiformats/esm/src/hashes/sha2-browser.js","../node_modules/multiformats/esm/src/hashes/identity.js","../node_modules/multiformats/esm/src/codecs/raw.js","../node_modules/multiformats/esm/src/codecs/json.js","../node_modules/multiformats/esm/src/cid.js","../node_modules/multiformats/esm/src/basics.js","../node_modules/uint8arrays/esm/src/util/bases.js","../node_modules/uint8arrays/esm/src/from-string.js","../node_modules/uint8arrays/esm/src/to-string.js","../node_modules/detect-browser/es/index.js","../../jsonrpc.ts","../node_modules/destr/dist/index.mjs","../node_modules/unstorage/dist/shared/unstorage.8581f561.mjs","../node_modules/unstorage/dist/index.mjs","../node_modules/idb-keyval/dist/index.js","../../constants.ts","../../utils.ts","../../api.ts","../../error.ts","../../format.ts","../../misc.ts","../../provider.ts","../../url.ts","../../validators.ts","../../http.ts","../node_modules/node_modules/lodash/lodash.js","../node_modules/@walletconnect/universal-provider/src/constants/values.ts","../node_modules/@walletconnect/universal-provider/src/constants/events.ts","../node_modules/ethers/node_modules/@noble/hashes/src/_assert.ts","../node_modules/ethers/node_modules/@noble/hashes/src/_u64.ts","../node_modules/ethers/node_modules/@noble/hashes/src/crypto.ts","../node_modules/ethers/node_modules/@noble/hashes/src/utils.ts","../node_modules/ethers/node_modules/@noble/hashes/src/sha3.ts","../node_modules/ethers/src.ts/_version.ts","../node_modules/ethers/src.ts/utils/properties.ts","../node_modules/ethers/src.ts/utils/errors.ts","../node_modules/ethers/src.ts/utils/data.ts","../node_modules/ethers/src.ts/crypto/keccak.ts","../node_modules/ethers/src.ts/address/address.ts","../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js","../node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js","../node_modules/@babel/runtime/helpers/esm/assertClassBrand.js","../node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js","../node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet2.js","../node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet2.js","../node_modules/ethers/src.ts/utils/utf8.ts","../node_modules/ethers/src.ts/utils/geturl-browser.ts","../node_modules/ethers/src.ts/utils/fetch.ts","../node_modules/ethers/src.ts/utils/base64-browser.ts","../node_modules/ethers/src.ts/providers/community.ts","../node_modules/ethers/src.ts/transaction/accesslist.ts","../node_modules/ethers/src.ts/utils/maths.ts","../node_modules/ethers/src.ts/providers/plugins-network.ts","../node_modules/ethers/src.ts/providers/network.ts","../node_modules/ethers/src.ts/abi/coders/abstract-coder.ts","../node_modules/ethers/src.ts/abi/typed.ts","../node_modules/ethers/src.ts/abi/coders/address.ts","../node_modules/ethers/src.ts/abi/coders/anonymous.ts","../node_modules/ethers/src.ts/abi/coders/array.ts","../node_modules/ethers/src.ts/abi/coders/boolean.ts","../node_modules/ethers/src.ts/abi/coders/bytes.ts","../node_modules/ethers/src.ts/abi/coders/fixed-bytes.ts","../node_modules/ethers/src.ts/abi/coders/null.ts","../node_modules/ethers/src.ts/abi/coders/number.ts","../node_modules/ethers/src.ts/abi/coders/string.ts","../node_modules/ethers/src.ts/abi/coders/tuple.ts","../node_modules/ethers/src.ts/hash/id.ts","../node_modules/ethers/src.ts/abi/fragments.ts","../node_modules/ethers/src.ts/abi/abi-coder.ts","../node_modules/ethers/src.ts/address/checks.ts","../node_modules/ethers/src.ts/hash/typed-data.ts","../node_modules/ethers/src.ts/constants/addresses.ts","../node_modules/ethers/src.ts/abi/interface.ts","../node_modules/ethers/src.ts/providers/provider.ts","../node_modules/ethers/src.ts/utils/events.ts","../node_modules/ethers/src.ts/contract/wrappers.ts","../node_modules/ethers/src.ts/contract/contract.ts","../node_modules/@adraffy/ens-normalize/dist/index.mjs","../node_modules/ethers/src.ts/hash/namehash.ts","../node_modules/ethers/node_modules/@noble/hashes/src/_sha2.ts","../node_modules/ethers/node_modules/@noble/hashes/src/sha256.ts","../node_modules/ethers/node_modules/@noble/hashes/src/sha512.ts","../node_modules/ethers/src.ts/crypto/crypto-browser.ts","../node_modules/ethers/src.ts/crypto/sha2.ts","../node_modules/ethers/src.ts/constants/hashes.ts","../node_modules/ethers/src.ts/crypto/signature.ts","../node_modules/ethers/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/ethers/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/ethers/node_modules/@noble/hashes/src/hmac.ts","../node_modules/ethers/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/ethers/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/ethers/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/ethers/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/ethers/src.ts/crypto/signing-key.ts","../node_modules/ethers/src.ts/utils/rlp-decode.ts","../node_modules/ethers/src.ts/utils/rlp-encode.ts","../node_modules/ethers/src.ts/transaction/address.ts","../node_modules/ethers/src.ts/transaction/transaction.ts","../node_modules/ethers/src.ts/utils/base58.ts","../node_modules/ethers/src.ts/providers/ens-resolver.ts","../node_modules/ethers/src.ts/providers/format.ts","../node_modules/ethers/src.ts/address/contract-address.ts","../node_modules/ethers/src.ts/providers/subscriber-polling.ts","../node_modules/ethers/src.ts/providers/abstract-provider.ts","../node_modules/ethers/src.ts/providers/abstract-signer.ts","../node_modules/ethers/src.ts/providers/subscriber-filterid.ts","../node_modules/ethers/src.ts/providers/provider-jsonrpc.ts","../node_modules/ethers/src.ts/providers/ws-browser.ts","../node_modules/ethers/src.ts/providers/provider-socket.ts","../node_modules/ethers/src.ts/providers/provider-websocket.ts","../node_modules/ethers/src.ts/providers/provider-infura.ts","../node_modules/ethers/src.ts/utils/fixednumber.ts","../node_modules/ethers/src.ts/utils/units.ts","../../../../src/EthersConstantsUtil.ts","../../../../src/EthersHelpersUtil.ts","../../../../src/EthersStoreUtil.ts","../node_modules/valtio/esm/react.mjs","../../../../exports/react.tsx","config.js","components/ConnectWallet.jsx","assets/icons/close.svg","providers/PopupContextProvider.jsx","../node_modules/uuid/dist/esm-browser/native.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/ethers/src.ts/providers/provider-browser.ts","components/MintNFT.jsx","providers/Web3Modal.jsx","../../../../../src/utils/defaultConfig.ts","components/Eligibility.jsx","components/NFTLevels.jsx","components/FuturePhases.jsx","pages/Home.jsx","components/ui/SimpleModal.jsx","pages/HomeMobile.jsx","components/Navbar.js","App.js","reportWebVitals.js","../node_modules/@sentry/src/version.ts","../node_modules/@sentry/src/worldwide.ts","../node_modules/@sentry/src/constants.ts","../node_modules/@sentry/src/carrier.ts","../node_modules/@sentry/src/is.ts","../node_modules/@sentry/src/browser.ts","../node_modules/@sentry/src/debug-build.ts","../node_modules/@sentry/src/logger.ts","../node_modules/@sentry/src/string.ts","../node_modules/@sentry/src/object.ts","../node_modules/@sentry/src/misc.ts","../node_modules/@sentry/src/propagationContext.ts","../node_modules/@sentry/src/time.ts","../node_modules/@sentry/src/session.ts","../node_modules/@sentry/src/utils/spanOnScope.ts","../node_modules/@sentry/src/scope.ts","../node_modules/@sentry/src/asyncContext/stackStrategy.ts","../node_modules/@sentry/src/defaultScopes.ts","../node_modules/@sentry/src/asyncContext/index.ts","../node_modules/@sentry/src/currentScopes.ts","../node_modules/@sentry/src/stacktrace.ts","../node_modules/@sentry/src/normalize.ts","../node_modules/@sentry/src/memo.ts","../node_modules/@sentry/src/syncpromise.ts","../node_modules/@sentry/src/eventProcessors.ts","../node_modules/@sentry/src/baggage.ts","../node_modules/@sentry/src/semanticAttributes.ts","../node_modules/@sentry/src/tracing.ts","../node_modules/@sentry/src/metrics/metric-summary.ts","../node_modules/@sentry/src/tracing/spanstatus.ts","../node_modules/@sentry/src/utils/spanUtils.ts","../node_modules/@sentry/src/tracing/dynamicSamplingContext.ts","../node_modules/@sentry/src/utils/applyScopeDataToEvent.ts","../node_modules/@sentry/src/utils/prepareEvent.ts","../node_modules/@sentry/src/exports.ts","../node_modules/@sentry/src/integration.ts","../node_modules/@sentry/src/integrations/inboundfilters.ts","../node_modules/@sentry/src/integrations/functiontostring.ts","../node_modules/@sentry/src/integrations/dedupe.ts","../node_modules/@sentry/src/sdk.ts","../node_modules/@sentry/src/supports.ts","../node_modules/@sentry/src/instrument/handlers.ts","../node_modules/@sentry/src/vendor/supportsHistory.ts","../node_modules/@sentry-internal/src/types.ts","../node_modules/@sentry-internal/src/instrument/history.ts","../node_modules/@sentry/src/dsn.ts","../node_modules/@sentry/src/envelope.ts","../node_modules/@sentry/src/error.ts","../node_modules/@sentry/src/api.ts","../node_modules/@sentry/src/utils/parseSampleRate.ts","../node_modules/@sentry/src/baseclient.ts","../node_modules/@sentry/src/utils/sdkMetadata.ts","../node_modules/src/debug-build.ts","../node_modules/src/eventbuilder.ts","../node_modules/src/helpers.ts","../node_modules/src/client.ts","../node_modules/@sentry/src/env.ts","../node_modules/src/userfeedback.ts","../node_modules/@sentry/src/clientreport.ts","../node_modules/@sentry-internal/src/instrument/dom.ts","../node_modules/@sentry-internal/src/instrument/xhr.ts","../node_modules/@sentry/src/breadcrumbs.ts","../node_modules/@sentry/src/instrument/console.ts","../node_modules/@sentry/src/instrument/fetch.ts","../node_modules/@sentry/src/severity.ts","../node_modules/@sentry/src/url.ts","../node_modules/src/integrations/breadcrumbs.ts","../node_modules/src/integrations/browserapierrors.ts","../node_modules/@sentry/src/instrument/globalError.ts","../node_modules/@sentry/src/instrument/globalUnhandledRejection.ts","../node_modules/src/integrations/globalhandlers.ts","../node_modules/src/integrations/httpcontext.ts","../node_modules/@sentry/src/aggregate-errors.ts","../node_modules/src/integrations/linkederrors.ts","../node_modules/src/stack-parsers.ts","../node_modules/@sentry-internal/src/debug-build.ts","../node_modules/@sentry-internal/src/getNativeImplementation.ts","../node_modules/@sentry/src/promisebuffer.ts","../node_modules/@sentry/src/ratelimit.ts","../node_modules/@sentry/src/transports/base.ts","../node_modules/src/transports/fetch.ts","../node_modules/src/sdk.ts","../node_modules/@sentry/src/utils/hasTracingEnabled.ts","../node_modules/@sentry/src/tracing/sentryNonRecordingSpan.ts","../node_modules/@sentry/src/tracing/measurement.ts","../node_modules/@sentry/src/tracing/utils.ts","../node_modules/@sentry/src/tracing/sentrySpan.ts","../node_modules/@sentry/src/tracing/logSpans.ts","../node_modules/@sentry/src/tracing/trace.ts","../node_modules/@sentry/src/tracing/sampling.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/bindReporter.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/getNavigationEntry.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/getActivationStart.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/initMetric.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/generateUniqueID.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/observe.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/onHidden.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/runOnce.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/getVisibilityWatcher.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/whenActivated.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/onFCP.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/getCLS.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/getFID.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/getINP.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/getLCP.ts","../node_modules/@sentry-internal/src/metrics/web-vitals/onTTFB.ts","../node_modules/@sentry-internal/src/metrics/instrument.ts","../node_modules/@sentry-internal/src/metrics/utils.ts","../node_modules/@sentry-internal/src/metrics/browserMetrics.ts","../node_modules/@sentry-internal/src/metrics/inp.ts","../node_modules/@sentry/src/tracing/idleSpan.ts","../node_modules/@sentry/src/tracing/errors.ts","../node_modules/@sentry/src/fetch.ts","../node_modules/src/tracing/request.ts","../node_modules/src/tracing/browserTracingIntegration.ts","../node_modules/@sentry/src/buildPolyfills/_optionalChain.ts","../node_modules/@sentry/src/utils/isSentryRequestUrl.ts","../node_modules/@sentry/src/node.ts","../node_modules/@sentry/src/isBrowser.ts","../node_modules/src/constants.ts","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","../node_modules/@sentry/src/buildPolyfills/_nullishCoalesce.ts","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","../node_modules/src/types/rrweb.ts","../node_modules/src/util/timestamp.ts","../node_modules/src/coreHandlers/util/addBreadcrumbEvent.ts","../node_modules/src/coreHandlers/util/domUtils.ts","../node_modules/src/coreHandlers/util/onWindowOpen.ts","../node_modules/src/coreHandlers/handleClick.ts","../node_modules/src/util/createBreadcrumb.ts","../../node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/src/coreHandlers/util/getAttributesToRecord.ts","../node_modules/src/coreHandlers/handleDom.ts","../node_modules/src/coreHandlers/handleKeyboardEvent.ts","../node_modules/src/util/createPerformanceEntries.ts","../replay-worker/build/npm/esm/worker.ts","../node_modules/src/util/log.ts","../node_modules/src/eventBuffer/error.ts","../node_modules/src/eventBuffer/EventBufferArray.ts","../node_modules/src/eventBuffer/WorkerHandler.ts","../node_modules/src/eventBuffer/EventBufferCompressionWorker.ts","../node_modules/src/eventBuffer/EventBufferProxy.ts","../node_modules/src/eventBuffer/index.ts","../replay-worker/build/npm/esm/index.js","../node_modules/src/util/hasSessionStorage.ts","../node_modules/src/session/clearSession.ts","../node_modules/src/util/isSampled.ts","../node_modules/src/session/Session.ts","../node_modules/src/session/saveSession.ts","../node_modules/src/session/createSession.ts","../node_modules/src/util/isExpired.ts","../node_modules/src/util/isSessionExpired.ts","../node_modules/src/session/shouldRefreshSession.ts","../node_modules/src/session/loadOrCreateSession.ts","../node_modules/src/session/fetchSession.ts","../node_modules/src/util/addEvent.ts","../node_modules/src/util/eventUtils.ts","../node_modules/src/coreHandlers/handleAfterSendEvent.ts","../node_modules/src/coreHandlers/handleBeforeSendEvent.ts","../node_modules/src/coreHandlers/handleBreadcrumbs.ts","../node_modules/src/coreHandlers/handleGlobalEvent.ts","../node_modules/src/coreHandlers/util/addFeedbackBreadcrumb.ts","../node_modules/src/util/isRrwebError.ts","../node_modules/src/coreHandlers/util/shouldSampleForBufferEvent.ts","../node_modules/src/util/createPerformanceSpans.ts","../node_modules/src/coreHandlers/handleHistory.ts","../node_modules/src/coreHandlers/util/addNetworkBreadcrumb.ts","../node_modules/src/util/shouldFilterRequest.ts","../node_modules/src/coreHandlers/util/networkUtils.ts","../node_modules/src/coreHandlers/util/fetchUtils.ts","../node_modules/src/coreHandlers/util/xhrUtils.ts","../node_modules/src/coreHandlers/handleNetworkBreadcrumbs.ts","../node_modules/src/util/addGlobalListeners.ts","../node_modules/src/util/addMemoryEntry.ts","../node_modules/src/util/handleRecordingEmit.ts","../node_modules/src/util/sendReplayRequest.ts","../node_modules/src/util/prepareRecordingData.ts","../node_modules/src/util/prepareReplayEvent.ts","../node_modules/src/util/createReplayEnvelope.ts","../node_modules/src/util/sendReplay.ts","../node_modules/src/util/throttle.ts","../node_modules/src/replay.ts","../node_modules/src/util/debounce.ts","../node_modules/src/coreHandlers/performanceObserver.ts","../node_modules/src/util/getPrivacyOptions.ts","../node_modules/src/integration.ts","../node_modules/src/util/maskAttribute.ts","index.js","../node_modules/src/tracing/backgroundtab.ts"],"sourceRoot":"","sourcesContent":["\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CoinbaseWalletSDK = void 0;\nconst wallet_logo_1 = require(\"./assets/wallet-logo\");\nconst constants_1 = require(\"./core/constants\");\nconst util_1 = require(\"./core/util\");\nconst ScopedLocalStorage_1 = require(\"./lib/ScopedLocalStorage\");\nconst CoinbaseWalletProvider_1 = require(\"./provider/CoinbaseWalletProvider\");\nconst MobileRelay_1 = require(\"./relay/mobile/MobileRelay\");\nconst MobileRelayUI_1 = require(\"./relay/mobile/MobileRelayUI\");\nconst RelayEventManager_1 = require(\"./relay/RelayEventManager\");\nconst WalletLinkRelayUI_1 = require(\"./relay/walletlink/ui/WalletLinkRelayUI\");\nconst WalletLinkRelay_1 = require(\"./relay/walletlink/WalletLinkRelay\");\nconst version_1 = require(\"./version\");\nclass CoinbaseWalletSDK {\n /**\n * Constructor\n * @param options Coinbase Wallet SDK constructor options\n */\n constructor(options) {\n var _a, _b, _c;\n this._appName = '';\n this._appLogoUrl = null;\n this._relay = null;\n this._relayEventManager = null;\n const linkAPIUrl = options.linkAPIUrl || constants_1.LINK_API_URL;\n if (typeof options.overrideIsMetaMask === 'undefined') {\n this._overrideIsMetaMask = false;\n }\n else {\n this._overrideIsMetaMask = options.overrideIsMetaMask;\n }\n this._overrideIsCoinbaseWallet = (_a = options.overrideIsCoinbaseWallet) !== null && _a !== void 0 ? _a : true;\n this._overrideIsCoinbaseBrowser = (_b = options.overrideIsCoinbaseBrowser) !== null && _b !== void 0 ? _b : false;\n this._diagnosticLogger = options.diagnosticLogger;\n this._reloadOnDisconnect = (_c = options.reloadOnDisconnect) !== null && _c !== void 0 ? _c : true;\n const url = new URL(linkAPIUrl);\n const origin = `${url.protocol}//${url.host}`;\n this._storage = new ScopedLocalStorage_1.ScopedLocalStorage(`-walletlink:${origin}`); // needs migration to preserve local states\n this._storage.setItem('version', CoinbaseWalletSDK.VERSION);\n if (this.walletExtension || this.coinbaseBrowser) {\n return;\n }\n this._relayEventManager = new RelayEventManager_1.RelayEventManager();\n const isMobile = (0, util_1.isMobileWeb)();\n const uiConstructor = options.uiConstructor ||\n ((opts) => (isMobile ? new MobileRelayUI_1.MobileRelayUI(opts) : new WalletLinkRelayUI_1.WalletLinkRelayUI(opts)));\n const relayOption = {\n linkAPIUrl,\n version: version_1.LIB_VERSION,\n darkMode: !!options.darkMode,\n uiConstructor,\n storage: this._storage,\n relayEventManager: this._relayEventManager,\n diagnosticLogger: this._diagnosticLogger,\n reloadOnDisconnect: this._reloadOnDisconnect,\n enableMobileWalletLink: options.enableMobileWalletLink,\n };\n this._relay = isMobile ? new MobileRelay_1.MobileRelay(relayOption) : new WalletLinkRelay_1.WalletLinkRelay(relayOption);\n this.setAppInfo(options.appName, options.appLogoUrl);\n if (options.headlessMode)\n return;\n this._relay.attachUI();\n }\n /**\n * Create a Web3 Provider object\n * @param jsonRpcUrl Ethereum JSON RPC URL (Default: \"\")\n * @param chainId Ethereum Chain ID (Default: 1)\n * @returns A Web3 Provider\n */\n makeWeb3Provider(jsonRpcUrl = '', chainId = 1) {\n const extension = this.walletExtension;\n if (extension) {\n if (!this.isCipherProvider(extension)) {\n extension.setProviderInfo(jsonRpcUrl, chainId);\n }\n if (this._reloadOnDisconnect === false &&\n typeof extension.disableReloadOnDisconnect === 'function')\n extension.disableReloadOnDisconnect();\n return extension;\n }\n const dappBrowser = this.coinbaseBrowser;\n if (dappBrowser) {\n return dappBrowser;\n }\n const relay = this._relay;\n if (!relay || !this._relayEventManager || !this._storage) {\n throw new Error('Relay not initialized, should never happen');\n }\n if (!jsonRpcUrl)\n relay.setConnectDisabled(true);\n return new CoinbaseWalletProvider_1.CoinbaseWalletProvider({\n relayProvider: () => Promise.resolve(relay),\n relayEventManager: this._relayEventManager,\n storage: this._storage,\n jsonRpcUrl,\n chainId,\n qrUrl: this.getQrUrl(),\n diagnosticLogger: this._diagnosticLogger,\n overrideIsMetaMask: this._overrideIsMetaMask,\n overrideIsCoinbaseWallet: this._overrideIsCoinbaseWallet,\n overrideIsCoinbaseBrowser: this._overrideIsCoinbaseBrowser,\n });\n }\n /**\n * Set application information\n * @param appName Application name\n * @param appLogoUrl Application logo image URL\n */\n setAppInfo(appName, appLogoUrl) {\n var _a;\n this._appName = appName || 'DApp';\n this._appLogoUrl = appLogoUrl || (0, util_1.getFavicon)();\n const extension = this.walletExtension;\n if (extension) {\n if (!this.isCipherProvider(extension)) {\n extension.setAppInfo(this._appName, this._appLogoUrl);\n }\n }\n else {\n (_a = this._relay) === null || _a === void 0 ? void 0 : _a.setAppInfo(this._appName, this._appLogoUrl);\n }\n }\n /**\n * Disconnect. After disconnecting, this will reload the web page to ensure\n * all potential stale state is cleared.\n */\n disconnect() {\n var _a;\n const extension = this === null || this === void 0 ? void 0 : this.walletExtension;\n if (extension) {\n void extension.close();\n }\n else {\n (_a = this._relay) === null || _a === void 0 ? void 0 : _a.resetAndReload();\n }\n }\n /**\n * Return QR URL for mobile wallet connection, will return null if extension is installed\n */\n getQrUrl() {\n var _a, _b;\n return (_b = (_a = this._relay) === null || _a === void 0 ? void 0 : _a.getQRCodeUrl()) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Official Coinbase Wallet logo for developers to use on their frontend\n * @param type Type of wallet logo: \"standard\" | \"circle\" | \"text\" | \"textWithLogo\" | \"textLight\" | \"textWithLogoLight\"\n * @param width Width of the logo (Optional)\n * @returns SVG Data URI\n */\n getCoinbaseWalletLogo(type, width = 240) {\n return (0, wallet_logo_1.walletLogo)(type, width);\n }\n get walletExtension() {\n var _a;\n return (_a = window.coinbaseWalletExtension) !== null && _a !== void 0 ? _a : window.walletLinkExtension;\n }\n get coinbaseBrowser() {\n var _a, _b;\n try {\n // Coinbase DApp browser does not inject into iframes so grab provider from top frame if it exists\n const ethereum = (_a = window.ethereum) !== null && _a !== void 0 ? _a : (_b = window.top) === null || _b === void 0 ? void 0 : _b.ethereum;\n if (!ethereum) {\n return undefined;\n }\n if ('isCoinbaseBrowser' in ethereum && ethereum.isCoinbaseBrowser) {\n return ethereum;\n }\n return undefined;\n }\n catch (e) {\n return undefined;\n }\n }\n isCipherProvider(provider) {\n // @ts-expect-error isCipher walletlink property\n return typeof provider.isCipher === 'boolean' && provider.isCipher;\n }\n}\nexports.CoinbaseWalletSDK = CoinbaseWalletSDK;\nCoinbaseWalletSDK.VERSION = version_1.LIB_VERSION;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.walletLogo = void 0;\nconst walletLogo = (type, width) => {\n let height;\n switch (type) {\n case 'standard':\n height = width;\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;\n case 'circle':\n height = width;\n return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;\n case 'text':\n height = (0.1 * width).toFixed(2);\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;\n case 'textWithLogo':\n height = (0.25 * width).toFixed(2);\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;\n case 'textLight':\n height = (0.1 * width).toFixed(2);\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;\n case 'textWithLogoLight':\n height = (0.25 * width).toFixed(2);\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;\n default:\n height = width;\n return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;\n }\n};\nexports.walletLogo = walletLogo;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LINK_API_URL = void 0;\nexports.LINK_API_URL = 'https://www.walletlink.org';\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.errorValues = exports.standardErrorCodes = void 0;\nexports.standardErrorCodes = {\n rpc: {\n invalidInput: -32000,\n resourceNotFound: -32001,\n resourceUnavailable: -32002,\n transactionRejected: -32003,\n methodNotSupported: -32004,\n limitExceeded: -32005,\n parse: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internal: -32603,\n },\n provider: {\n userRejectedRequest: 4001,\n unauthorized: 4100,\n unsupportedMethod: 4200,\n disconnected: 4900,\n chainDisconnected: 4901,\n unsupportedChain: 4902,\n },\n};\nexports.errorValues = {\n '-32700': {\n standard: 'JSON RPC 2.0',\n message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n },\n '-32600': {\n standard: 'JSON RPC 2.0',\n message: 'The JSON sent is not a valid Request object.',\n },\n '-32601': {\n standard: 'JSON RPC 2.0',\n message: 'The method does not exist / is not available.',\n },\n '-32602': {\n standard: 'JSON RPC 2.0',\n message: 'Invalid method parameter(s).',\n },\n '-32603': {\n standard: 'JSON RPC 2.0',\n message: 'Internal JSON-RPC error.',\n },\n '-32000': {\n standard: 'EIP-1474',\n message: 'Invalid input.',\n },\n '-32001': {\n standard: 'EIP-1474',\n message: 'Resource not found.',\n },\n '-32002': {\n standard: 'EIP-1474',\n message: 'Resource unavailable.',\n },\n '-32003': {\n standard: 'EIP-1474',\n message: 'Transaction rejected.',\n },\n '-32004': {\n standard: 'EIP-1474',\n message: 'Method not supported.',\n },\n '-32005': {\n standard: 'EIP-1474',\n message: 'Request limit exceeded.',\n },\n '4001': {\n standard: 'EIP-1193',\n message: 'User rejected the request.',\n },\n '4100': {\n standard: 'EIP-1193',\n message: 'The requested account and/or method has not been authorized by the user.',\n },\n '4200': {\n standard: 'EIP-1193',\n message: 'The requested method is not supported by this Ethereum provider.',\n },\n '4900': {\n standard: 'EIP-1193',\n message: 'The provider is disconnected from all chains.',\n },\n '4901': {\n standard: 'EIP-1193',\n message: 'The provider is disconnected from the specified chain.',\n },\n '4902': {\n standard: 'EIP-3085',\n message: 'Unrecognized chain ID.',\n },\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.standardErrors = void 0;\nconst constants_1 = require(\"./constants\");\nconst utils_1 = require(\"./utils\");\nexports.standardErrors = {\n rpc: {\n parse: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.parse, arg),\n invalidRequest: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.invalidRequest, arg),\n invalidParams: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.invalidParams, arg),\n methodNotFound: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.methodNotFound, arg),\n internal: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.internal, arg),\n server: (opts) => {\n if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {\n throw new Error('Ethereum RPC Server errors must provide single object argument.');\n }\n const { code } = opts;\n if (!Number.isInteger(code) || code > -32005 || code < -32099) {\n throw new Error('\"code\" must be an integer such that: -32099 <= code <= -32005');\n }\n return getEthJsonRpcError(code, opts);\n },\n invalidInput: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.invalidInput, arg),\n resourceNotFound: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.resourceNotFound, arg),\n resourceUnavailable: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.resourceUnavailable, arg),\n transactionRejected: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.transactionRejected, arg),\n methodNotSupported: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.methodNotSupported, arg),\n limitExceeded: (arg) => getEthJsonRpcError(constants_1.standardErrorCodes.rpc.limitExceeded, arg),\n },\n provider: {\n userRejectedRequest: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.userRejectedRequest, arg);\n },\n unauthorized: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.unauthorized, arg);\n },\n unsupportedMethod: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.unsupportedMethod, arg);\n },\n disconnected: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.disconnected, arg);\n },\n chainDisconnected: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.chainDisconnected, arg);\n },\n unsupportedChain: (arg) => {\n return getEthProviderError(constants_1.standardErrorCodes.provider.unsupportedChain, arg);\n },\n custom: (opts) => {\n if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {\n throw new Error('Ethereum Provider custom errors must provide single object argument.');\n }\n const { code, message, data } = opts;\n if (!message || typeof message !== 'string') {\n throw new Error('\"message\" must be a nonempty string');\n }\n return new EthereumProviderError(code, message, data);\n },\n },\n};\n// Internal\nfunction getEthJsonRpcError(code, arg) {\n const [message, data] = parseOpts(arg);\n return new EthereumRpcError(code, message || (0, utils_1.getMessageFromCode)(code), data);\n}\nfunction getEthProviderError(code, arg) {\n const [message, data] = parseOpts(arg);\n return new EthereumProviderError(code, message || (0, utils_1.getMessageFromCode)(code), data);\n}\nfunction parseOpts(arg) {\n if (arg) {\n if (typeof arg === 'string') {\n return [arg];\n }\n else if (typeof arg === 'object' && !Array.isArray(arg)) {\n const { message, data } = arg;\n if (message && typeof message !== 'string') {\n throw new Error('Must specify string message.');\n }\n return [message || undefined, data];\n }\n }\n return [];\n}\nclass EthereumRpcError extends Error {\n constructor(code, message, data) {\n if (!Number.isInteger(code)) {\n throw new Error('\"code\" must be an integer.');\n }\n if (!message || typeof message !== 'string') {\n throw new Error('\"message\" must be a nonempty string.');\n }\n super(message);\n this.code = code;\n if (data !== undefined) {\n this.data = data;\n }\n }\n}\nclass EthereumProviderError extends EthereumRpcError {\n /**\n * Create an Ethereum Provider JSON-RPC error.\n * `code` must be an integer in the 1000 <= 4999 range.\n */\n constructor(code, message, data) {\n if (!isValidEthProviderCode(code)) {\n throw new Error('\"code\" must be an integer such that: 1000 <= code <= 4999');\n }\n super(code, message, data);\n }\n}\nfunction isValidEthProviderCode(code) {\n return Number.isInteger(code) && code >= 1000 && code <= 4999;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.standardErrors = exports.standardErrorCodes = exports.serializeError = exports.getMessageFromCode = exports.getErrorCode = void 0;\nconst constants_1 = require(\"./constants\");\nObject.defineProperty(exports, \"standardErrorCodes\", { enumerable: true, get: function () { return constants_1.standardErrorCodes; } });\nconst errors_1 = require(\"./errors\");\nObject.defineProperty(exports, \"standardErrors\", { enumerable: true, get: function () { return errors_1.standardErrors; } });\nconst serialize_1 = require(\"./serialize\");\nObject.defineProperty(exports, \"serializeError\", { enumerable: true, get: function () { return serialize_1.serializeError; } });\nconst utils_1 = require(\"./utils\");\nObject.defineProperty(exports, \"getErrorCode\", { enumerable: true, get: function () { return utils_1.getErrorCode; } });\nObject.defineProperty(exports, \"getMessageFromCode\", { enumerable: true, get: function () { return utils_1.getMessageFromCode; } });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.serializeError = void 0;\n// TODO: error should not depend on walletlink. revisit this.\nconst Web3Response_1 = require(\"../../relay/walletlink/type/Web3Response\");\nconst version_1 = require(\"../../version\");\nconst constants_1 = require(\"./constants\");\nconst utils_1 = require(\"./utils\");\n/**\n * Serializes an error to a format that is compatible with the Ethereum JSON RPC error format.\n * See https://docs.cloud.coinbase.com/wallet-sdk/docs/errors\n * for more information.\n */\nfunction serializeError(error, requestOrMethod) {\n const serialized = (0, utils_1.serialize)(getErrorObject(error), {\n shouldIncludeStack: true,\n });\n const docUrl = new URL('https://docs.cloud.coinbase.com/wallet-sdk/docs/errors');\n docUrl.searchParams.set('version', version_1.LIB_VERSION);\n docUrl.searchParams.set('code', serialized.code.toString());\n const method = getMethod(serialized.data, requestOrMethod);\n if (method) {\n docUrl.searchParams.set('method', method);\n }\n docUrl.searchParams.set('message', serialized.message);\n return Object.assign(Object.assign({}, serialized), { docUrl: docUrl.href });\n}\nexports.serializeError = serializeError;\n/**\n * Converts an error to a serializable object.\n */\nfunction getErrorObject(error) {\n if (typeof error === 'string') {\n return {\n message: error,\n code: constants_1.standardErrorCodes.rpc.internal,\n };\n }\n else if ((0, Web3Response_1.isErrorResponse)(error)) {\n return Object.assign(Object.assign({}, error), { message: error.errorMessage, code: error.errorCode, data: { method: error.method } });\n }\n return error;\n}\n/**\n * Gets the method name from the serialized data or the request.\n */\nfunction getMethod(serializedData, request) {\n const methodInData = serializedData === null || serializedData === void 0 ? void 0 : serializedData.method;\n if (methodInData) {\n return methodInData;\n }\n if (request === undefined) {\n return undefined;\n }\n else if (typeof request === 'string') {\n return request;\n }\n else if (!Array.isArray(request)) {\n return request.method;\n }\n else if (request.length > 0) {\n return request[0].method;\n }\n return undefined;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.serialize = exports.getErrorCode = exports.isValidCode = exports.getMessageFromCode = exports.JSON_RPC_SERVER_ERROR_MESSAGE = void 0;\nconst constants_1 = require(\"./constants\");\nconst FALLBACK_MESSAGE = 'Unspecified error message.';\nexports.JSON_RPC_SERVER_ERROR_MESSAGE = 'Unspecified server error.';\n/**\n * Gets the message for a given code, or a fallback message if the code has\n * no corresponding message.\n */\nfunction getMessageFromCode(code, fallbackMessage = FALLBACK_MESSAGE) {\n if (code && Number.isInteger(code)) {\n const codeString = code.toString();\n if (hasKey(constants_1.errorValues, codeString)) {\n return constants_1.errorValues[codeString].message;\n }\n if (isJsonRpcServerError(code)) {\n return exports.JSON_RPC_SERVER_ERROR_MESSAGE;\n }\n }\n return fallbackMessage;\n}\nexports.getMessageFromCode = getMessageFromCode;\n/**\n * Returns whether the given code is valid.\n * A code is only valid if it has a message.\n */\nfunction isValidCode(code) {\n if (!Number.isInteger(code)) {\n return false;\n }\n const codeString = code.toString();\n if (constants_1.errorValues[codeString]) {\n return true;\n }\n if (isJsonRpcServerError(code)) {\n return true;\n }\n return false;\n}\nexports.isValidCode = isValidCode;\n/**\n * Returns the error code from an error object.\n */\nfunction getErrorCode(error) {\n var _a;\n if (typeof error === 'number') {\n return error;\n }\n else if (isErrorWithCode(error)) {\n return (_a = error.code) !== null && _a !== void 0 ? _a : error.errorCode;\n }\n return undefined;\n}\nexports.getErrorCode = getErrorCode;\nfunction isErrorWithCode(error) {\n return (typeof error === 'object' &&\n error !== null &&\n (typeof error.code === 'number' ||\n typeof error.errorCode === 'number'));\n}\nfunction serialize(error, { shouldIncludeStack = false } = {}) {\n const serialized = {};\n if (error &&\n typeof error === 'object' &&\n !Array.isArray(error) &&\n hasKey(error, 'code') &&\n isValidCode(error.code)) {\n const _error = error;\n serialized.code = _error.code;\n if (_error.message && typeof _error.message === 'string') {\n serialized.message = _error.message;\n if (hasKey(_error, 'data')) {\n serialized.data = _error.data;\n }\n }\n else {\n serialized.message = getMessageFromCode(serialized.code);\n serialized.data = { originalError: assignOriginalError(error) };\n }\n }\n else {\n serialized.code = constants_1.standardErrorCodes.rpc.internal;\n serialized.message = hasStringProperty(error, 'message') ? error.message : FALLBACK_MESSAGE;\n serialized.data = { originalError: assignOriginalError(error) };\n }\n if (shouldIncludeStack) {\n serialized.stack = hasStringProperty(error, 'stack') ? error.stack : undefined;\n }\n return serialized;\n}\nexports.serialize = serialize;\n// Internal\nfunction isJsonRpcServerError(code) {\n return code >= -32099 && code <= -32000;\n}\nfunction assignOriginalError(error) {\n if (error && typeof error === 'object' && !Array.isArray(error)) {\n return Object.assign({}, error);\n }\n return error;\n}\nfunction hasKey(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nfunction hasStringProperty(obj, prop) {\n return (typeof obj === 'object' && obj !== null && prop in obj && typeof obj[prop] === 'string');\n}\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProviderType = exports.RegExpString = exports.IntNumber = exports.BigIntString = exports.AddressString = exports.HexString = exports.OpaqueType = void 0;\nfunction OpaqueType() {\n return (value) => value;\n}\nexports.OpaqueType = OpaqueType;\nexports.HexString = OpaqueType();\nexports.AddressString = OpaqueType();\nexports.BigIntString = OpaqueType();\nfunction IntNumber(num) {\n return Math.floor(num);\n}\nexports.IntNumber = IntNumber;\nexports.RegExpString = OpaqueType();\nvar ProviderType;\n(function (ProviderType) {\n ProviderType[\"CoinbaseWallet\"] = \"CoinbaseWallet\";\n ProviderType[\"MetaMask\"] = \"MetaMask\";\n ProviderType[\"Unselected\"] = \"\";\n})(ProviderType || (exports.ProviderType = ProviderType = {}));\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isMobileWeb = exports.getLocation = exports.isInIFrame = exports.createQrUrl = exports.getFavicon = exports.range = exports.isBigNumber = exports.ensureParsedJSONObject = exports.ensureBN = exports.ensureRegExpString = exports.ensureIntNumber = exports.ensureBuffer = exports.ensureAddressString = exports.ensureEvenLengthHexString = exports.ensureHexString = exports.isHexString = exports.prepend0x = exports.strip0x = exports.has0xPrefix = exports.hexStringFromIntNumber = exports.intNumberFromHexString = exports.bigIntStringFromBN = exports.hexStringFromBuffer = exports.hexStringToUint8Array = exports.uint8ArrayToHex = exports.randomBytesHex = void 0;\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nconst error_1 = require(\"./error\");\nconst type_1 = require(\"./type\");\nconst INT_STRING_REGEX = /^[0-9]*$/;\nconst HEXADECIMAL_STRING_REGEX = /^[a-f0-9]*$/;\n/**\n * @param length number of bytes\n */\nfunction randomBytesHex(length) {\n return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(length)));\n}\nexports.randomBytesHex = randomBytesHex;\nfunction uint8ArrayToHex(value) {\n return [...value].map((b) => b.toString(16).padStart(2, '0')).join('');\n}\nexports.uint8ArrayToHex = uint8ArrayToHex;\nfunction hexStringToUint8Array(hexString) {\n return new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n}\nexports.hexStringToUint8Array = hexStringToUint8Array;\nfunction hexStringFromBuffer(buf, includePrefix = false) {\n const hex = buf.toString('hex');\n return (0, type_1.HexString)(includePrefix ? `0x${hex}` : hex);\n}\nexports.hexStringFromBuffer = hexStringFromBuffer;\nfunction bigIntStringFromBN(bn) {\n return (0, type_1.BigIntString)(bn.toString(10));\n}\nexports.bigIntStringFromBN = bigIntStringFromBN;\nfunction intNumberFromHexString(hex) {\n return (0, type_1.IntNumber)(new bn_js_1.default(ensureEvenLengthHexString(hex, false), 16).toNumber());\n}\nexports.intNumberFromHexString = intNumberFromHexString;\nfunction hexStringFromIntNumber(num) {\n return (0, type_1.HexString)(`0x${new bn_js_1.default(num).toString(16)}`);\n}\nexports.hexStringFromIntNumber = hexStringFromIntNumber;\nfunction has0xPrefix(str) {\n return str.startsWith('0x') || str.startsWith('0X');\n}\nexports.has0xPrefix = has0xPrefix;\nfunction strip0x(hex) {\n if (has0xPrefix(hex)) {\n return hex.slice(2);\n }\n return hex;\n}\nexports.strip0x = strip0x;\nfunction prepend0x(hex) {\n if (has0xPrefix(hex)) {\n return `0x${hex.slice(2)}`;\n }\n return `0x${hex}`;\n}\nexports.prepend0x = prepend0x;\nfunction isHexString(hex) {\n if (typeof hex !== 'string') {\n return false;\n }\n const s = strip0x(hex).toLowerCase();\n return HEXADECIMAL_STRING_REGEX.test(s);\n}\nexports.isHexString = isHexString;\nfunction ensureHexString(hex, includePrefix = false) {\n if (typeof hex === 'string') {\n const s = strip0x(hex).toLowerCase();\n if (HEXADECIMAL_STRING_REGEX.test(s)) {\n return (0, type_1.HexString)(includePrefix ? `0x${s}` : s);\n }\n }\n throw error_1.standardErrors.rpc.invalidParams(`\"${String(hex)}\" is not a hexadecimal string`);\n}\nexports.ensureHexString = ensureHexString;\nfunction ensureEvenLengthHexString(hex, includePrefix = false) {\n let h = ensureHexString(hex, false);\n if (h.length % 2 === 1) {\n h = (0, type_1.HexString)(`0${h}`);\n }\n return includePrefix ? (0, type_1.HexString)(`0x${h}`) : h;\n}\nexports.ensureEvenLengthHexString = ensureEvenLengthHexString;\nfunction ensureAddressString(str) {\n if (typeof str === 'string') {\n const s = strip0x(str).toLowerCase();\n if (isHexString(s) && s.length === 40) {\n return (0, type_1.AddressString)(prepend0x(s));\n }\n }\n throw error_1.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(str)}`);\n}\nexports.ensureAddressString = ensureAddressString;\nfunction ensureBuffer(str) {\n if (Buffer.isBuffer(str)) {\n return str;\n }\n if (typeof str === 'string') {\n if (isHexString(str)) {\n const s = ensureEvenLengthHexString(str, false);\n return Buffer.from(s, 'hex');\n }\n return Buffer.from(str, 'utf8');\n }\n throw error_1.standardErrors.rpc.invalidParams(`Not binary data: ${String(str)}`);\n}\nexports.ensureBuffer = ensureBuffer;\nfunction ensureIntNumber(num) {\n if (typeof num === 'number' && Number.isInteger(num)) {\n return (0, type_1.IntNumber)(num);\n }\n if (typeof num === 'string') {\n if (INT_STRING_REGEX.test(num)) {\n return (0, type_1.IntNumber)(Number(num));\n }\n if (isHexString(num)) {\n return (0, type_1.IntNumber)(new bn_js_1.default(ensureEvenLengthHexString(num, false), 16).toNumber());\n }\n }\n throw error_1.standardErrors.rpc.invalidParams(`Not an integer: ${String(num)}`);\n}\nexports.ensureIntNumber = ensureIntNumber;\nfunction ensureRegExpString(regExp) {\n if (regExp instanceof RegExp) {\n return (0, type_1.RegExpString)(regExp.toString());\n }\n throw error_1.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(regExp)}`);\n}\nexports.ensureRegExpString = ensureRegExpString;\nfunction ensureBN(val) {\n if (val !== null && (bn_js_1.default.isBN(val) || isBigNumber(val))) {\n return new bn_js_1.default(val.toString(10), 10);\n }\n if (typeof val === 'number') {\n return new bn_js_1.default(ensureIntNumber(val));\n }\n if (typeof val === 'string') {\n if (INT_STRING_REGEX.test(val)) {\n return new bn_js_1.default(val, 10);\n }\n if (isHexString(val)) {\n return new bn_js_1.default(ensureEvenLengthHexString(val, false), 16);\n }\n }\n throw error_1.standardErrors.rpc.invalidParams(`Not an integer: ${String(val)}`);\n}\nexports.ensureBN = ensureBN;\nfunction ensureParsedJSONObject(val) {\n if (typeof val === 'string') {\n return JSON.parse(val);\n }\n if (typeof val === 'object') {\n return val;\n }\n throw error_1.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(val)}`);\n}\nexports.ensureParsedJSONObject = ensureParsedJSONObject;\nfunction isBigNumber(val) {\n if (val == null || typeof val.constructor !== 'function') {\n return false;\n }\n const { constructor } = val;\n return typeof constructor.config === 'function' && typeof constructor.EUCLID === 'number';\n}\nexports.isBigNumber = isBigNumber;\nfunction range(start, stop) {\n return Array.from({ length: stop - start }, (_, i) => start + i);\n}\nexports.range = range;\nfunction getFavicon() {\n const el = document.querySelector('link[sizes=\"192x192\"]') ||\n document.querySelector('link[sizes=\"180x180\"]') ||\n document.querySelector('link[rel=\"icon\"]') ||\n document.querySelector('link[rel=\"shortcut icon\"]');\n const { protocol, host } = document.location;\n const href = el ? el.getAttribute('href') : null;\n if (!href || href.startsWith('javascript:') || href.startsWith('vbscript:')) {\n return null;\n }\n if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('data:')) {\n return href;\n }\n if (href.startsWith('//')) {\n return protocol + href;\n }\n return `${protocol}//${host}${href}`;\n}\nexports.getFavicon = getFavicon;\nfunction createQrUrl(sessionId, sessionSecret, serverUrl, isParentConnection, version, chainId) {\n const sessionIdKey = isParentConnection ? 'parent-id' : 'id';\n const query = new URLSearchParams({\n [sessionIdKey]: sessionId,\n secret: sessionSecret,\n server: serverUrl,\n v: version,\n chainId: chainId.toString(),\n }).toString();\n const qrUrl = `${serverUrl}/#/link?${query}`;\n return qrUrl;\n}\nexports.createQrUrl = createQrUrl;\nfunction isInIFrame() {\n try {\n return window.frameElement !== null;\n }\n catch (e) {\n return false;\n }\n}\nexports.isInIFrame = isInIFrame;\nfunction getLocation() {\n try {\n if (isInIFrame() && window.top) {\n return window.top.location;\n }\n return window.location;\n }\n catch (e) {\n return window.location;\n }\n}\nexports.getLocation = getLocation;\nfunction isMobileWeb() {\n var _a;\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent);\n}\nexports.isMobileWeb = isMobileWeb;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CoinbaseWalletProvider = exports.CoinbaseWalletSDK = void 0;\nconst CoinbaseWalletSDK_1 = require(\"./CoinbaseWalletSDK\");\nconst CoinbaseWalletProvider_1 = require(\"./provider/CoinbaseWalletProvider\");\nvar CoinbaseWalletSDK_2 = require(\"./CoinbaseWalletSDK\");\nObject.defineProperty(exports, \"CoinbaseWalletSDK\", { enumerable: true, get: function () { return CoinbaseWalletSDK_2.CoinbaseWalletSDK; } });\nvar CoinbaseWalletProvider_2 = require(\"./provider/CoinbaseWalletProvider\");\nObject.defineProperty(exports, \"CoinbaseWalletProvider\", { enumerable: true, get: function () { return CoinbaseWalletProvider_2.CoinbaseWalletProvider; } });\nexports.default = CoinbaseWalletSDK_1.CoinbaseWalletSDK;\nif (typeof window !== 'undefined') {\n window.CoinbaseWalletSDK = CoinbaseWalletSDK_1.CoinbaseWalletSDK;\n window.CoinbaseWalletProvider = CoinbaseWalletProvider_1.CoinbaseWalletProvider;\n /**\n * @deprecated Use `window.CoinbaseWalletSDK`\n */\n window.WalletLink = CoinbaseWalletSDK_1.CoinbaseWalletSDK;\n /**\n * @deprecated Use `window.CoinbaseWalletProvider`\n */\n window.WalletLinkProvider = CoinbaseWalletProvider_1.CoinbaseWalletProvider;\n}\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Cipher = void 0;\nconst util_1 = require(\"../core/util\");\nclass Cipher {\n // @param secret hex representation of 32-byte secret\n constructor(secret) {\n this.secret = secret;\n }\n /**\n *\n * @param plainText string to be encrypted\n * returns hex string representation of bytes in the order: initialization vector (iv),\n * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes. Remaining bytes are the\n * encrypted plainText.\n */\n async encrypt(plainText) {\n const secret = this.secret;\n if (secret.length !== 64)\n throw Error(`secret must be 256 bits`);\n const ivBytes = crypto.getRandomValues(new Uint8Array(12));\n const secretKey = await crypto.subtle.importKey('raw', (0, util_1.hexStringToUint8Array)(secret), { name: 'aes-gcm' }, false, ['encrypt', 'decrypt']);\n const enc = new TextEncoder();\n // Will return encrypted plainText with auth tag (ie MAC or checksum) appended at the end\n const encryptedResult = await window.crypto.subtle.encrypt({\n name: 'AES-GCM',\n iv: ivBytes,\n }, secretKey, enc.encode(plainText));\n const tagLength = 16;\n const authTag = encryptedResult.slice(encryptedResult.byteLength - tagLength);\n const encryptedPlaintext = encryptedResult.slice(0, encryptedResult.byteLength - tagLength);\n const authTagBytes = new Uint8Array(authTag);\n const encryptedPlaintextBytes = new Uint8Array(encryptedPlaintext);\n const concatted = new Uint8Array([...ivBytes, ...authTagBytes, ...encryptedPlaintextBytes]);\n return (0, util_1.uint8ArrayToHex)(concatted);\n }\n /**\n *\n * @param cipherText hex string representation of bytes in the order: initialization vector (iv),\n * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes.\n */\n async decrypt(cipherText) {\n const secret = this.secret;\n if (secret.length !== 64)\n throw Error(`secret must be 256 bits`);\n return new Promise((resolve, reject) => {\n void (async function () {\n const secretKey = await crypto.subtle.importKey('raw', (0, util_1.hexStringToUint8Array)(secret), { name: 'aes-gcm' }, false, ['encrypt', 'decrypt']);\n const encrypted = (0, util_1.hexStringToUint8Array)(cipherText);\n const ivBytes = encrypted.slice(0, 12);\n const authTagBytes = encrypted.slice(12, 28);\n const encryptedPlaintextBytes = encrypted.slice(28);\n const concattedBytes = new Uint8Array([...encryptedPlaintextBytes, ...authTagBytes]);\n const algo = {\n name: 'AES-GCM',\n iv: new Uint8Array(ivBytes),\n };\n try {\n const decrypted = await window.crypto.subtle.decrypt(algo, secretKey, concattedBytes);\n const decoder = new TextDecoder();\n resolve(decoder.decode(decrypted));\n }\n catch (err) {\n reject(err);\n }\n })();\n });\n }\n}\nexports.Cipher = Cipher;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ScopedLocalStorage = void 0;\nclass ScopedLocalStorage {\n // eslint-disable-next-line no-useless-constructor\n constructor(scope) {\n this.scope = scope;\n }\n setItem(key, value) {\n localStorage.setItem(this.scopedKey(key), value);\n }\n getItem(key) {\n return localStorage.getItem(this.scopedKey(key));\n }\n removeItem(key) {\n localStorage.removeItem(this.scopedKey(key));\n }\n clear() {\n const prefix = this.scopedKey('');\n const keysToRemove = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (typeof key === 'string' && key.startsWith(prefix)) {\n keysToRemove.push(key);\n }\n }\n keysToRemove.forEach((key) => localStorage.removeItem(key));\n }\n scopedKey(key) {\n return `${this.scope}:${key}`;\n }\n}\nexports.ScopedLocalStorage = ScopedLocalStorage;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `@namespace svg \"http://www.w3.org/2000/svg\";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",\"Helvetica Neue\",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:\"\\\\201C\" \"\\\\201D\" \"\\\\2018\" \"\\\\2019\";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",\"Helvetica Neue\",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.injectCssReset = void 0;\nconst cssReset_css_1 = __importDefault(require(\"./cssReset-css\"));\nfunction injectCssReset() {\n const styleEl = document.createElement('style');\n styleEl.type = 'text/css';\n styleEl.appendChild(document.createTextNode(cssReset_css_1.default));\n document.documentElement.appendChild(styleEl);\n}\nexports.injectCssReset = injectCssReset;\n","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// TODO: Address linting issues\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CoinbaseWalletProvider = void 0;\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nconst eventemitter3_1 = require(\"eventemitter3\");\nconst error_1 = require(\"../core/error\");\nconst util_1 = require(\"../core/util\");\nconst MobileRelay_1 = require(\"../relay/mobile/MobileRelay\");\nconst RelayAbstract_1 = require(\"../relay/RelayAbstract\");\nconst Session_1 = require(\"../relay/Session\");\nconst Web3Response_1 = require(\"../relay/walletlink/type/Web3Response\");\nconst eth_eip712_util_1 = __importDefault(require(\"../vendor-js/eth-eip712-util\"));\nconst DiagnosticLogger_1 = require(\"./DiagnosticLogger\");\nconst FilterPolyfill_1 = require(\"./FilterPolyfill\");\nconst SubscriptionManager_1 = require(\"./SubscriptionManager\");\nconst DEFAULT_CHAIN_ID_KEY = 'DefaultChainId';\nconst DEFAULT_JSON_RPC_URL = 'DefaultJsonRpcUrl';\nclass CoinbaseWalletProvider extends eventemitter3_1.EventEmitter {\n constructor(options) {\n var _a, _b;\n super();\n this._filterPolyfill = new FilterPolyfill_1.FilterPolyfill(this);\n this._subscriptionManager = new SubscriptionManager_1.SubscriptionManager(this);\n this._relay = null;\n this._addresses = [];\n this.hasMadeFirstChainChangedEmission = false;\n this.setProviderInfo = this.setProviderInfo.bind(this);\n this.updateProviderInfo = this.updateProviderInfo.bind(this);\n this.getChainId = this.getChainId.bind(this);\n this.setAppInfo = this.setAppInfo.bind(this);\n this.enable = this.enable.bind(this);\n this.close = this.close.bind(this);\n this.send = this.send.bind(this);\n this.sendAsync = this.sendAsync.bind(this);\n this.request = this.request.bind(this);\n this._setAddresses = this._setAddresses.bind(this);\n this.scanQRCode = this.scanQRCode.bind(this);\n this.genericRequest = this.genericRequest.bind(this);\n this._chainIdFromOpts = options.chainId;\n this._jsonRpcUrlFromOpts = options.jsonRpcUrl;\n this._overrideIsMetaMask = options.overrideIsMetaMask;\n this._relayProvider = options.relayProvider;\n this._storage = options.storage;\n this._relayEventManager = options.relayEventManager;\n this.diagnostic = options.diagnosticLogger;\n this.reloadOnDisconnect = true;\n this.isCoinbaseWallet = (_a = options.overrideIsCoinbaseWallet) !== null && _a !== void 0 ? _a : true;\n this.isCoinbaseBrowser = (_b = options.overrideIsCoinbaseBrowser) !== null && _b !== void 0 ? _b : false;\n this.qrUrl = options.qrUrl;\n const chainId = this.getChainId();\n const chainIdStr = (0, util_1.prepend0x)(chainId.toString(16));\n // indicate that we've connected, for EIP-1193 compliance\n this.emit('connect', { chainIdStr });\n const cachedAddresses = this._storage.getItem(RelayAbstract_1.LOCAL_STORAGE_ADDRESSES_KEY);\n if (cachedAddresses) {\n const addresses = cachedAddresses.split(' ');\n if (addresses[0] !== '') {\n this._addresses = addresses.map((address) => (0, util_1.ensureAddressString)(address));\n this.emit('accountsChanged', addresses);\n }\n }\n this._subscriptionManager.events.on('notification', (notification) => {\n this.emit('message', {\n type: notification.method,\n data: notification.params,\n });\n });\n if (this._isAuthorized()) {\n void this.initializeRelay();\n }\n window.addEventListener('message', (event) => {\n var _a;\n // Used to verify the source and window are correct before proceeding\n if (event.origin !== location.origin || event.source !== window) {\n return;\n }\n if (event.data.type !== 'walletLinkMessage')\n return; // compatibility with CBW extension\n if (event.data.data.action === 'dappChainSwitched') {\n const _chainId = event.data.data.chainId;\n const jsonRpcUrl = (_a = event.data.data.jsonRpcUrl) !== null && _a !== void 0 ? _a : this.jsonRpcUrl;\n this.updateProviderInfo(jsonRpcUrl, Number(_chainId));\n }\n });\n }\n /** @deprecated Use `.request({ method: 'eth_accounts' })` instead. */\n get selectedAddress() {\n return this._addresses[0] || undefined;\n }\n /** @deprecated Use the chain ID. If you still need the network ID, use `.request({ method: 'net_version' })`. */\n get networkVersion() {\n return this.getChainId().toString(10);\n }\n /** @deprecated Use `.request({ method: 'eth_chainId' })` instead. */\n get chainId() {\n return (0, util_1.prepend0x)(this.getChainId().toString(16));\n }\n get isWalletLink() {\n // backward compatibility\n return true;\n }\n /**\n * Some DApps (i.e. Alpha Homora) seem to require the window.ethereum object return\n * true for this method.\n */\n get isMetaMask() {\n return this._overrideIsMetaMask;\n }\n get host() {\n return this.jsonRpcUrl;\n }\n get connected() {\n return true;\n }\n isConnected() {\n return true;\n }\n get jsonRpcUrl() {\n var _a;\n return (_a = this._storage.getItem(DEFAULT_JSON_RPC_URL)) !== null && _a !== void 0 ? _a : this._jsonRpcUrlFromOpts;\n }\n set jsonRpcUrl(value) {\n this._storage.setItem(DEFAULT_JSON_RPC_URL, value);\n }\n disableReloadOnDisconnect() {\n this.reloadOnDisconnect = false;\n }\n setProviderInfo(jsonRpcUrl, chainId) {\n if (!this.isCoinbaseBrowser) {\n this._chainIdFromOpts = chainId;\n this._jsonRpcUrlFromOpts = jsonRpcUrl;\n }\n this.updateProviderInfo(this.jsonRpcUrl, this.getChainId());\n }\n updateProviderInfo(jsonRpcUrl, chainId) {\n this.jsonRpcUrl = jsonRpcUrl;\n // emit chainChanged event if necessary\n const originalChainId = this.getChainId();\n this._storage.setItem(DEFAULT_CHAIN_ID_KEY, chainId.toString(10));\n const chainChanged = (0, util_1.ensureIntNumber)(chainId) !== originalChainId;\n if (chainChanged || !this.hasMadeFirstChainChangedEmission) {\n this.emit('chainChanged', this.getChainId());\n this.hasMadeFirstChainChangedEmission = true;\n }\n }\n async watchAsset(type, address, symbol, decimals, image, chainId) {\n const relay = await this.initializeRelay();\n const result = await relay.watchAsset(type, address, symbol, decimals, image, chainId === null || chainId === void 0 ? void 0 : chainId.toString()).promise;\n if ((0, Web3Response_1.isErrorResponse)(result))\n return false;\n return !!result.result;\n }\n async addEthereumChain(chainId, rpcUrls, blockExplorerUrls, chainName, iconUrls, nativeCurrency) {\n var _a, _b;\n if ((0, util_1.ensureIntNumber)(chainId) === this.getChainId()) {\n return false;\n }\n const relay = await this.initializeRelay();\n const isWhitelistedNetworkOrStandalone = relay.inlineAddEthereumChain(chainId.toString());\n if (!this._isAuthorized() && !isWhitelistedNetworkOrStandalone) {\n await relay.requestEthereumAccounts().promise;\n }\n const res = await relay.addEthereumChain(chainId.toString(), rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency).promise;\n if ((0, Web3Response_1.isErrorResponse)(res))\n return false;\n if (((_a = res.result) === null || _a === void 0 ? void 0 : _a.isApproved) === true) {\n this.updateProviderInfo(rpcUrls[0], chainId);\n }\n return ((_b = res.result) === null || _b === void 0 ? void 0 : _b.isApproved) === true;\n }\n async switchEthereumChain(chainId) {\n const relay = await this.initializeRelay();\n const res = await relay.switchEthereumChain(chainId.toString(10), this.selectedAddress || undefined).promise;\n // backward compatibility\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n if (!res.errorCode)\n return;\n if (res.errorCode === error_1.standardErrorCodes.provider.unsupportedChain) {\n throw error_1.standardErrors.provider.unsupportedChain();\n }\n else {\n throw error_1.standardErrors.provider.custom({\n message: res.errorMessage,\n code: res.errorCode,\n });\n }\n }\n const switchResponse = res.result;\n if (switchResponse.isApproved && switchResponse.rpcUrl.length > 0) {\n this.updateProviderInfo(switchResponse.rpcUrl, chainId);\n }\n }\n setAppInfo(appName, appLogoUrl) {\n void this.initializeRelay().then((relay) => relay.setAppInfo(appName, appLogoUrl));\n }\n /** @deprecated Use `.request({ method: 'eth_requestAccounts' })` instead. */\n async enable() {\n var _a;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.ETH_ACCOUNTS_STATE, {\n method: 'provider::enable',\n addresses_length: this._addresses.length,\n sessionIdHash: this._relay ? Session_1.Session.hash(this._relay.session.id) : undefined,\n });\n if (this._isAuthorized()) {\n return [...this._addresses];\n }\n return await this.send('eth_requestAccounts');\n }\n async close() {\n const relay = await this.initializeRelay();\n relay.resetAndReload();\n }\n send(requestOrMethod, callbackOrParams) {\n // send(method, params): Promise\n try {\n const result = this._send(requestOrMethod, callbackOrParams);\n if (result instanceof Promise) {\n return result.catch((error) => {\n throw (0, error_1.serializeError)(error, requestOrMethod);\n });\n }\n }\n catch (error) {\n throw (0, error_1.serializeError)(error, requestOrMethod);\n }\n }\n _send(requestOrMethod, callbackOrParams) {\n if (typeof requestOrMethod === 'string') {\n const method = requestOrMethod;\n const params = Array.isArray(callbackOrParams)\n ? callbackOrParams\n : callbackOrParams !== undefined\n ? [callbackOrParams]\n : [];\n const request = {\n jsonrpc: '2.0',\n id: 0,\n method,\n params,\n };\n return this._sendRequestAsync(request).then((res) => res.result);\n }\n // send(JSONRPCRequest | JSONRPCRequest[], callback): void\n if (typeof callbackOrParams === 'function') {\n const request = requestOrMethod;\n const callback = callbackOrParams;\n return this._sendAsync(request, callback);\n }\n // send(JSONRPCRequest[]): JSONRPCResponse[]\n if (Array.isArray(requestOrMethod)) {\n const requests = requestOrMethod;\n return requests.map((r) => this._sendRequest(r));\n }\n // send(JSONRPCRequest): JSONRPCResponse\n const req = requestOrMethod;\n return this._sendRequest(req);\n }\n async sendAsync(request, callback) {\n try {\n return this._sendAsync(request, callback).catch((error) => {\n throw (0, error_1.serializeError)(error, request);\n });\n }\n catch (error) {\n return Promise.reject((0, error_1.serializeError)(error, request));\n }\n }\n async _sendAsync(request, callback) {\n if (typeof callback !== 'function') {\n throw new Error('callback is required');\n }\n // send(JSONRPCRequest[], callback): void\n if (Array.isArray(request)) {\n const arrayCb = callback;\n this._sendMultipleRequestsAsync(request)\n .then((responses) => arrayCb(null, responses))\n .catch((err) => arrayCb(err, null));\n return;\n }\n // send(JSONRPCRequest, callback): void\n const cb = callback;\n return this._sendRequestAsync(request)\n .then((response) => cb(null, response))\n .catch((err) => cb(err, null));\n }\n async request(args) {\n try {\n return this._request(args).catch((error) => {\n throw (0, error_1.serializeError)(error, args.method);\n });\n }\n catch (error) {\n return Promise.reject((0, error_1.serializeError)(error, args.method));\n }\n }\n async _request(args) {\n if (!args || typeof args !== 'object' || Array.isArray(args)) {\n throw error_1.standardErrors.rpc.invalidRequest({\n message: 'Expected a single, non-array, object argument.',\n data: args,\n });\n }\n const { method, params } = args;\n if (typeof method !== 'string' || method.length === 0) {\n throw error_1.standardErrors.rpc.invalidRequest({\n message: \"'args.method' must be a non-empty string.\",\n data: args,\n });\n }\n if (params !== undefined &&\n !Array.isArray(params) &&\n (typeof params !== 'object' || params === null)) {\n throw error_1.standardErrors.rpc.invalidRequest({\n message: \"'args.params' must be an object or array if provided.\",\n data: args,\n });\n }\n const newParams = params === undefined ? [] : params;\n // Coinbase Wallet Requests\n const id = this._relayEventManager.makeRequestId();\n const result = await this._sendRequestAsync({\n method,\n params: newParams,\n jsonrpc: '2.0',\n id,\n });\n return result.result;\n }\n async scanQRCode(match) {\n const relay = await this.initializeRelay();\n const res = await relay.scanQRCode((0, util_1.ensureRegExpString)(match)).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw (0, error_1.serializeError)(res.errorMessage, 'scanQRCode');\n }\n else if (typeof res.result !== 'string') {\n throw (0, error_1.serializeError)('result was not a string', 'scanQRCode');\n }\n return res.result;\n }\n async genericRequest(data, action) {\n const relay = await this.initializeRelay();\n const res = await relay.genericRequest(data, action).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw (0, error_1.serializeError)(res.errorMessage, 'generic');\n }\n else if (typeof res.result !== 'string') {\n throw (0, error_1.serializeError)('result was not a string', 'generic');\n }\n return res.result;\n }\n /**\n * @beta\n * This method is currently in beta. While it is available for use, please note that it is still under testing and may undergo significant changes.\n *\n * @remarks\n * IMPORTANT: Signature validation is not performed by this method. Users of this method are advised to perform their own signature validation.\n * Common web3 frontend libraries such as ethers.js and viem provide the `verifyMessage` utility function that can be used for signature validation.\n *\n * It combines `eth_requestAccounts` and \"Sign-In with Ethereum\" (EIP-4361) into a single call.\n * The returned account and signed message can be used to authenticate the user.\n *\n * @param {Object} params - An object with the following properties:\n * - `nonce` {string}: A unique string to prevent replay attacks.\n * - `statement` {string}: An optional human-readable ASCII assertion that the user will sign.\n * - `resources` {string[]}: An optional list of information the user wishes to have resolved as part of authentication by the relying party.\n *\n * @returns {Promise} A promise that resolves to an object with the following properties:\n * - `accounts` {string[]}: The Ethereum accounts of the user.\n * - `message` {string}: The overall message that the user signed. Hex encoded.\n * - `signature` {string}: The signature of the message, signed with the user's private key. Hex encoded.\n */\n async connectAndSignIn(params) {\n // NOTE: It was intentionally built by following the pattern of the existing eth_requestAccounts method\n // to maintain consistency and avoid introducing a new pattern.\n // We acknowledge the need for a better design, and it is planned to address and improve it in a future refactor.\n var _a;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.ETH_ACCOUNTS_STATE, {\n method: 'provider::connectAndSignIn',\n sessionIdHash: this._relay ? Session_1.Session.hash(this._relay.session.id) : undefined,\n });\n let res;\n try {\n const relay = await this.initializeRelay();\n if (!(relay instanceof MobileRelay_1.MobileRelay)) {\n throw new Error('connectAndSignIn is only supported on mobile');\n }\n res = await relay.connectAndSignIn(params).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n }\n catch (err) {\n if (typeof err.message === 'string' && err.message.match(/(denied|rejected)/i)) {\n throw error_1.standardErrors.provider.userRejectedRequest('User denied account authorization');\n }\n throw err;\n }\n if (!res.result) {\n throw new Error('accounts received is empty');\n }\n const { accounts } = res.result;\n this._setAddresses(accounts);\n if (!this.isCoinbaseBrowser) {\n await this.switchEthereumChain(this.getChainId());\n }\n return res.result;\n }\n async selectProvider(providerOptions) {\n const relay = await this.initializeRelay();\n const res = await relay.selectProvider(providerOptions).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw (0, error_1.serializeError)(res.errorMessage, 'selectProvider');\n }\n else if (typeof res.result !== 'string') {\n throw (0, error_1.serializeError)('result was not a string', 'selectProvider');\n }\n return res.result;\n }\n supportsSubscriptions() {\n return false;\n }\n subscribe() {\n throw new Error('Subscriptions are not supported');\n }\n unsubscribe() {\n throw new Error('Subscriptions are not supported');\n }\n disconnect() {\n return true;\n }\n _sendRequest(request) {\n const response = {\n jsonrpc: '2.0',\n id: request.id,\n };\n const { method } = request;\n response.result = this._handleSynchronousMethods(request);\n if (response.result === undefined) {\n throw new Error(`Coinbase Wallet does not support calling ${method} synchronously without ` +\n `a callback. Please provide a callback parameter to call ${method} ` +\n `asynchronously.`);\n }\n return response;\n }\n _setAddresses(addresses, _) {\n if (!Array.isArray(addresses)) {\n throw new Error('addresses is not an array');\n }\n const newAddresses = addresses.map((address) => (0, util_1.ensureAddressString)(address));\n if (JSON.stringify(newAddresses) === JSON.stringify(this._addresses)) {\n return;\n }\n this._addresses = newAddresses;\n this.emit('accountsChanged', this._addresses);\n this._storage.setItem(RelayAbstract_1.LOCAL_STORAGE_ADDRESSES_KEY, newAddresses.join(' '));\n }\n _sendRequestAsync(request) {\n return new Promise((resolve, reject) => {\n try {\n const syncResult = this._handleSynchronousMethods(request);\n if (syncResult !== undefined) {\n return resolve({\n jsonrpc: '2.0',\n id: request.id,\n result: syncResult,\n });\n }\n const filterPromise = this._handleAsynchronousFilterMethods(request);\n if (filterPromise !== undefined) {\n filterPromise\n .then((res) => resolve(Object.assign(Object.assign({}, res), { id: request.id })))\n .catch((err) => reject(err));\n return;\n }\n const subscriptionPromise = this._handleSubscriptionMethods(request);\n if (subscriptionPromise !== undefined) {\n subscriptionPromise\n .then((res) => resolve({\n jsonrpc: '2.0',\n id: request.id,\n result: res.result,\n }))\n .catch((err) => reject(err));\n return;\n }\n }\n catch (err) {\n return reject(err);\n }\n this._handleAsynchronousMethods(request)\n .then((res) => res && resolve(Object.assign(Object.assign({}, res), { id: request.id })))\n .catch((err) => reject(err));\n });\n }\n _sendMultipleRequestsAsync(requests) {\n return Promise.all(requests.map((r) => this._sendRequestAsync(r)));\n }\n _handleSynchronousMethods(request) {\n const { method } = request;\n const params = request.params || [];\n switch (method) {\n case 'eth_accounts':\n return this._eth_accounts();\n case 'eth_coinbase':\n return this._eth_coinbase();\n case 'eth_uninstallFilter':\n return this._eth_uninstallFilter(params);\n case 'net_version':\n return this._net_version();\n case 'eth_chainId':\n return this._eth_chainId();\n default:\n return undefined;\n }\n }\n async _handleAsynchronousMethods(request) {\n const { method } = request;\n const params = request.params || [];\n switch (method) {\n case 'eth_requestAccounts':\n return this._eth_requestAccounts();\n case 'eth_sign':\n return this._eth_sign(params);\n case 'eth_ecRecover':\n return this._eth_ecRecover(params);\n case 'personal_sign':\n return this._personal_sign(params);\n case 'personal_ecRecover':\n return this._personal_ecRecover(params);\n case 'eth_signTransaction':\n return this._eth_signTransaction(params);\n case 'eth_sendRawTransaction':\n return this._eth_sendRawTransaction(params);\n case 'eth_sendTransaction':\n return this._eth_sendTransaction(params);\n case 'eth_signTypedData_v1':\n return this._eth_signTypedData_v1(params);\n case 'eth_signTypedData_v2':\n return this._throwUnsupportedMethodError();\n case 'eth_signTypedData_v3':\n return this._eth_signTypedData_v3(params);\n case 'eth_signTypedData_v4':\n case 'eth_signTypedData':\n return this._eth_signTypedData_v4(params);\n case 'cbWallet_arbitrary':\n return this._cbwallet_arbitrary(params);\n case 'wallet_addEthereumChain':\n return this._wallet_addEthereumChain(params);\n case 'wallet_switchEthereumChain':\n return this._wallet_switchEthereumChain(params);\n case 'wallet_watchAsset':\n return this._wallet_watchAsset(params);\n }\n const relay = await this.initializeRelay();\n return relay.makeEthereumJSONRPCRequest(request, this.jsonRpcUrl).catch((err) => {\n var _a;\n if (err.code === error_1.standardErrorCodes.rpc.methodNotFound ||\n err.code === error_1.standardErrorCodes.rpc.methodNotSupported) {\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.METHOD_NOT_IMPLEMENTED, {\n method: request.method,\n sessionIdHash: this._relay ? Session_1.Session.hash(this._relay.session.id) : undefined,\n });\n }\n throw err;\n });\n }\n _handleAsynchronousFilterMethods(request) {\n const { method } = request;\n const params = request.params || [];\n switch (method) {\n case 'eth_newFilter':\n return this._eth_newFilter(params);\n case 'eth_newBlockFilter':\n return this._eth_newBlockFilter();\n case 'eth_newPendingTransactionFilter':\n return this._eth_newPendingTransactionFilter();\n case 'eth_getFilterChanges':\n return this._eth_getFilterChanges(params);\n case 'eth_getFilterLogs':\n return this._eth_getFilterLogs(params);\n }\n return undefined;\n }\n _handleSubscriptionMethods(request) {\n switch (request.method) {\n case 'eth_subscribe':\n case 'eth_unsubscribe':\n return this._subscriptionManager.handleRequest(request);\n }\n return undefined;\n }\n _isKnownAddress(addressString) {\n try {\n const addressStr = (0, util_1.ensureAddressString)(addressString);\n const lowercaseAddresses = this._addresses.map((address) => (0, util_1.ensureAddressString)(address));\n return lowercaseAddresses.includes(addressStr);\n }\n catch (_a) {\n // noop\n }\n return false;\n }\n _ensureKnownAddress(addressString) {\n var _a;\n if (!this._isKnownAddress(addressString)) {\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.UNKNOWN_ADDRESS_ENCOUNTERED);\n throw new Error('Unknown Ethereum address');\n }\n }\n _prepareTransactionParams(tx) {\n const fromAddress = tx.from ? (0, util_1.ensureAddressString)(tx.from) : this.selectedAddress;\n if (!fromAddress) {\n throw new Error('Ethereum address is unavailable');\n }\n this._ensureKnownAddress(fromAddress);\n const toAddress = tx.to ? (0, util_1.ensureAddressString)(tx.to) : null;\n const weiValue = tx.value != null ? (0, util_1.ensureBN)(tx.value) : new bn_js_1.default(0);\n const data = tx.data ? (0, util_1.ensureBuffer)(tx.data) : Buffer.alloc(0);\n const nonce = tx.nonce != null ? (0, util_1.ensureIntNumber)(tx.nonce) : null;\n const gasPriceInWei = tx.gasPrice != null ? (0, util_1.ensureBN)(tx.gasPrice) : null;\n const maxFeePerGas = tx.maxFeePerGas != null ? (0, util_1.ensureBN)(tx.maxFeePerGas) : null;\n const maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? (0, util_1.ensureBN)(tx.maxPriorityFeePerGas) : null;\n const gasLimit = tx.gas != null ? (0, util_1.ensureBN)(tx.gas) : null;\n const chainId = tx.chainId ? (0, util_1.ensureIntNumber)(tx.chainId) : this.getChainId();\n return {\n fromAddress,\n toAddress,\n weiValue,\n data,\n nonce,\n gasPriceInWei,\n maxFeePerGas,\n maxPriorityFeePerGas,\n gasLimit,\n chainId,\n };\n }\n _isAuthorized() {\n return this._addresses.length > 0;\n }\n _requireAuthorization() {\n if (!this._isAuthorized()) {\n throw error_1.standardErrors.provider.unauthorized({});\n }\n }\n _throwUnsupportedMethodError() {\n throw error_1.standardErrors.provider.unsupportedMethod({});\n }\n async _signEthereumMessage(message, address, addPrefix, typedDataJson) {\n this._ensureKnownAddress(address);\n try {\n const relay = await this.initializeRelay();\n const res = await relay.signEthereumMessage(message, address, addPrefix, typedDataJson)\n .promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n return { jsonrpc: '2.0', id: 0, result: res.result };\n }\n catch (err) {\n if (typeof err.message === 'string' && err.message.match(/(denied|rejected)/i)) {\n throw error_1.standardErrors.provider.userRejectedRequest('User denied message signature');\n }\n throw err;\n }\n }\n async _ethereumAddressFromSignedMessage(message, signature, addPrefix) {\n const relay = await this.initializeRelay();\n const res = await relay.ethereumAddressFromSignedMessage(message, signature, addPrefix).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n return { jsonrpc: '2.0', id: 0, result: res.result };\n }\n _eth_accounts() {\n return [...this._addresses];\n }\n _eth_coinbase() {\n return this.selectedAddress || null;\n }\n _net_version() {\n return this.getChainId().toString(10);\n }\n _eth_chainId() {\n return (0, util_1.hexStringFromIntNumber)(this.getChainId());\n }\n getChainId() {\n const chainIdStr = this._storage.getItem(DEFAULT_CHAIN_ID_KEY);\n if (!chainIdStr) {\n return (0, util_1.ensureIntNumber)(this._chainIdFromOpts);\n }\n const chainId = parseInt(chainIdStr, 10);\n return (0, util_1.ensureIntNumber)(chainId);\n }\n async _eth_requestAccounts() {\n var _a;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.ETH_ACCOUNTS_STATE, {\n method: 'provider::_eth_requestAccounts',\n addresses_length: this._addresses.length,\n sessionIdHash: this._relay ? Session_1.Session.hash(this._relay.session.id) : undefined,\n });\n if (this._isAuthorized()) {\n return Promise.resolve({\n jsonrpc: '2.0',\n id: 0,\n result: this._addresses,\n });\n }\n let res;\n try {\n const relay = await this.initializeRelay();\n res = await relay.requestEthereumAccounts().promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n }\n catch (err) {\n if (typeof err.message === 'string' && err.message.match(/(denied|rejected)/i)) {\n throw error_1.standardErrors.provider.userRejectedRequest('User denied account authorization');\n }\n throw err;\n }\n if (!res.result) {\n throw new Error('accounts received is empty');\n }\n this._setAddresses(res.result);\n if (!this.isCoinbaseBrowser) {\n await this.switchEthereumChain(this.getChainId());\n }\n return { jsonrpc: '2.0', id: 0, result: this._addresses };\n }\n _eth_sign(params) {\n this._requireAuthorization();\n const address = (0, util_1.ensureAddressString)(params[0]);\n const message = (0, util_1.ensureBuffer)(params[1]);\n return this._signEthereumMessage(message, address, false);\n }\n _eth_ecRecover(params) {\n const message = (0, util_1.ensureBuffer)(params[0]);\n const signature = (0, util_1.ensureBuffer)(params[1]);\n return this._ethereumAddressFromSignedMessage(message, signature, false);\n }\n _personal_sign(params) {\n this._requireAuthorization();\n const message = (0, util_1.ensureBuffer)(params[0]);\n const address = (0, util_1.ensureAddressString)(params[1]);\n return this._signEthereumMessage(message, address, true);\n }\n _personal_ecRecover(params) {\n const message = (0, util_1.ensureBuffer)(params[0]);\n const signature = (0, util_1.ensureBuffer)(params[1]);\n return this._ethereumAddressFromSignedMessage(message, signature, true);\n }\n async _eth_signTransaction(params) {\n this._requireAuthorization();\n const tx = this._prepareTransactionParams(params[0] || {});\n try {\n const relay = await this.initializeRelay();\n const res = await relay.signEthereumTransaction(tx).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n return { jsonrpc: '2.0', id: 0, result: res.result };\n }\n catch (err) {\n if (typeof err.message === 'string' && err.message.match(/(denied|rejected)/i)) {\n throw error_1.standardErrors.provider.userRejectedRequest('User denied transaction signature');\n }\n throw err;\n }\n }\n async _eth_sendRawTransaction(params) {\n const signedTransaction = (0, util_1.ensureBuffer)(params[0]);\n const relay = await this.initializeRelay();\n const res = await relay.submitEthereumTransaction(signedTransaction, this.getChainId()).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n return { jsonrpc: '2.0', id: 0, result: res.result };\n }\n async _eth_sendTransaction(params) {\n this._requireAuthorization();\n const tx = this._prepareTransactionParams(params[0] || {});\n try {\n const relay = await this.initializeRelay();\n const res = await relay.signAndSubmitEthereumTransaction(tx).promise;\n if ((0, Web3Response_1.isErrorResponse)(res)) {\n throw new Error(res.errorMessage);\n }\n return { jsonrpc: '2.0', id: 0, result: res.result };\n }\n catch (err) {\n if (typeof err.message === 'string' && err.message.match(/(denied|rejected)/i)) {\n throw error_1.standardErrors.provider.userRejectedRequest('User denied transaction signature');\n }\n throw err;\n }\n }\n async _eth_signTypedData_v1(params) {\n this._requireAuthorization();\n const typedData = (0, util_1.ensureParsedJSONObject)(params[0]);\n const address = (0, util_1.ensureAddressString)(params[1]);\n this._ensureKnownAddress(address);\n const message = eth_eip712_util_1.default.hashForSignTypedDataLegacy({ data: typedData });\n const typedDataJSON = JSON.stringify(typedData, null, 2);\n return this._signEthereumMessage(message, address, false, typedDataJSON);\n }\n async _eth_signTypedData_v3(params) {\n this._requireAuthorization();\n const address = (0, util_1.ensureAddressString)(params[0]);\n const typedData = (0, util_1.ensureParsedJSONObject)(params[1]);\n this._ensureKnownAddress(address);\n const message = eth_eip712_util_1.default.hashForSignTypedData_v3({ data: typedData });\n const typedDataJSON = JSON.stringify(typedData, null, 2);\n return this._signEthereumMessage(message, address, false, typedDataJSON);\n }\n async _eth_signTypedData_v4(params) {\n this._requireAuthorization();\n const address = (0, util_1.ensureAddressString)(params[0]);\n const typedData = (0, util_1.ensureParsedJSONObject)(params[1]);\n this._ensureKnownAddress(address);\n const message = eth_eip712_util_1.default.hashForSignTypedData_v4({ data: typedData });\n const typedDataJSON = JSON.stringify(typedData, null, 2);\n return this._signEthereumMessage(message, address, false, typedDataJSON);\n }\n /** @deprecated */\n async _cbwallet_arbitrary(params) {\n const action = params[0];\n const data = params[1];\n if (typeof data !== 'string') {\n throw new Error('parameter must be a string');\n }\n if (typeof action !== 'object' || action === null) {\n throw new Error('parameter must be an object');\n }\n const result = await this.genericRequest(action, data);\n return { jsonrpc: '2.0', id: 0, result };\n }\n async _wallet_addEthereumChain(params) {\n var _a, _b, _c, _d;\n const request = params[0];\n if (((_a = request.rpcUrls) === null || _a === void 0 ? void 0 : _a.length) === 0) {\n return {\n jsonrpc: '2.0',\n id: 0,\n error: { code: 2, message: `please pass in at least 1 rpcUrl` },\n };\n }\n if (!request.chainName || request.chainName.trim() === '') {\n throw error_1.standardErrors.rpc.invalidParams('chainName is a required field');\n }\n if (!request.nativeCurrency) {\n throw error_1.standardErrors.rpc.invalidParams('nativeCurrency is a required field');\n }\n const chainIdNumber = parseInt(request.chainId, 16);\n const success = await this.addEthereumChain(chainIdNumber, (_b = request.rpcUrls) !== null && _b !== void 0 ? _b : [], (_c = request.blockExplorerUrls) !== null && _c !== void 0 ? _c : [], request.chainName, (_d = request.iconUrls) !== null && _d !== void 0 ? _d : [], request.nativeCurrency);\n if (success) {\n return { jsonrpc: '2.0', id: 0, result: null };\n }\n return {\n jsonrpc: '2.0',\n id: 0,\n error: { code: 2, message: `unable to add ethereum chain` },\n };\n }\n async _wallet_switchEthereumChain(params) {\n const request = params[0];\n await this.switchEthereumChain(parseInt(request.chainId, 16));\n return { jsonrpc: '2.0', id: 0, result: null };\n }\n async _wallet_watchAsset(params) {\n const request = (Array.isArray(params) ? params[0] : params);\n if (!request.type) {\n throw error_1.standardErrors.rpc.invalidParams('Type is required');\n }\n if ((request === null || request === void 0 ? void 0 : request.type) !== 'ERC20') {\n throw error_1.standardErrors.rpc.invalidParams(`Asset of type '${request.type}' is not supported`);\n }\n if (!(request === null || request === void 0 ? void 0 : request.options)) {\n throw error_1.standardErrors.rpc.invalidParams('Options are required');\n }\n if (!(request === null || request === void 0 ? void 0 : request.options.address)) {\n throw error_1.standardErrors.rpc.invalidParams('Address is required');\n }\n const chainId = this.getChainId();\n const { address, symbol, image, decimals } = request.options;\n const res = await this.watchAsset(request.type, address, symbol, decimals, image, chainId);\n return { jsonrpc: '2.0', id: 0, result: res };\n }\n _eth_uninstallFilter(params) {\n const filterId = (0, util_1.ensureHexString)(params[0]);\n return this._filterPolyfill.uninstallFilter(filterId);\n }\n async _eth_newFilter(params) {\n const param = params[0];\n const filterId = await this._filterPolyfill.newFilter(param);\n return { jsonrpc: '2.0', id: 0, result: filterId };\n }\n async _eth_newBlockFilter() {\n const filterId = await this._filterPolyfill.newBlockFilter();\n return { jsonrpc: '2.0', id: 0, result: filterId };\n }\n async _eth_newPendingTransactionFilter() {\n const filterId = await this._filterPolyfill.newPendingTransactionFilter();\n return { jsonrpc: '2.0', id: 0, result: filterId };\n }\n _eth_getFilterChanges(params) {\n const filterId = (0, util_1.ensureHexString)(params[0]);\n return this._filterPolyfill.getFilterChanges(filterId);\n }\n _eth_getFilterLogs(params) {\n const filterId = (0, util_1.ensureHexString)(params[0]);\n return this._filterPolyfill.getFilterLogs(filterId);\n }\n initializeRelay() {\n if (this._relay) {\n return Promise.resolve(this._relay);\n }\n return this._relayProvider().then((relay) => {\n relay.setAccountsCallback((accounts, isDisconnect) => this._setAddresses(accounts, isDisconnect));\n relay.setChainCallback((chainId, jsonRpcUrl) => {\n this.updateProviderInfo(jsonRpcUrl, parseInt(chainId, 10));\n });\n relay.setDappDefaultChainCallback(this._chainIdFromOpts);\n this._relay = relay;\n return relay;\n });\n }\n}\nexports.CoinbaseWalletProvider = CoinbaseWalletProvider;\n","\"use strict\";\n// DiagnosticLogger for debugging purposes only\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EVENTS = void 0;\nexports.EVENTS = {\n STARTED_CONNECTING: 'walletlink_sdk.started.connecting',\n CONNECTED_STATE_CHANGE: 'walletlink_sdk.connected',\n DISCONNECTED: 'walletlink_sdk.disconnected',\n METADATA_DESTROYED: 'walletlink_sdk_metadata_destroyed',\n LINKED: 'walletlink_sdk.linked',\n FAILURE: 'walletlink_sdk.generic_failure',\n SESSION_CONFIG_RECEIVED: 'walletlink_sdk.session_config_event_received',\n ETH_ACCOUNTS_STATE: 'walletlink_sdk.eth_accounts_state',\n SESSION_STATE_CHANGE: 'walletlink_sdk.session_state_change',\n UNLINKED_ERROR_STATE: 'walletlink_sdk.unlinked_error_state',\n SKIPPED_CLEARING_SESSION: 'walletlink_sdk.skipped_clearing_session',\n GENERAL_ERROR: 'walletlink_sdk.general_error',\n WEB3_REQUEST: 'walletlink_sdk.web3.request',\n WEB3_REQUEST_PUBLISHED: 'walletlink_sdk.web3.request_published',\n WEB3_RESPONSE: 'walletlink_sdk.web3.response',\n METHOD_NOT_IMPLEMENTED: 'walletlink_sdk.method_not_implemented',\n UNKNOWN_ADDRESS_ENCOUNTERED: 'walletlink_sdk.unknown_address_encountered',\n};\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.filterFromParam = exports.FilterPolyfill = void 0;\nconst type_1 = require(\"../core/type\");\nconst util_1 = require(\"../core/util\");\nconst TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst JSONRPC_TEMPLATE = {\n jsonrpc: '2.0',\n id: 0,\n};\nclass FilterPolyfill {\n constructor(provider) {\n this.logFilters = new Map(); // \n this.blockFilters = new Set(); // \n this.pendingTransactionFilters = new Set(); // \n this.cursors = new Map(); // \n this.timeouts = new Map(); // \n this.nextFilterId = (0, type_1.IntNumber)(1);\n this.REQUEST_THROTTLE_INTERVAL = 1000; // in milliseconds\n this.lastFetchTimestamp = new Date(0);\n this.resolvers = [];\n this.provider = provider;\n }\n async newFilter(param) {\n const filter = filterFromParam(param);\n const id = this.makeFilterId();\n const cursor = await this.setInitialCursorPosition(id, filter.fromBlock);\n console.info(`Installing new log filter(${id}):`, filter, 'initial cursor position:', cursor);\n this.logFilters.set(id, filter);\n this.setFilterTimeout(id);\n return (0, util_1.hexStringFromIntNumber)(id);\n }\n async newBlockFilter() {\n const id = this.makeFilterId();\n const cursor = await this.setInitialCursorPosition(id, 'latest');\n console.info(`Installing new block filter (${id}) with initial cursor position:`, cursor);\n this.blockFilters.add(id);\n this.setFilterTimeout(id);\n return (0, util_1.hexStringFromIntNumber)(id);\n }\n async newPendingTransactionFilter() {\n const id = this.makeFilterId();\n const cursor = await this.setInitialCursorPosition(id, 'latest');\n console.info(`Installing new block filter (${id}) with initial cursor position:`, cursor);\n this.pendingTransactionFilters.add(id);\n this.setFilterTimeout(id);\n return (0, util_1.hexStringFromIntNumber)(id);\n }\n uninstallFilter(filterId) {\n const id = (0, util_1.intNumberFromHexString)(filterId);\n console.info(`Uninstalling filter (${id})`);\n this.deleteFilter(id);\n return true;\n }\n getFilterChanges(filterId) {\n const id = (0, util_1.intNumberFromHexString)(filterId);\n if (this.timeouts.has(id)) {\n // extend timeout\n this.setFilterTimeout(id);\n }\n if (this.logFilters.has(id)) {\n return this.getLogFilterChanges(id);\n }\n else if (this.blockFilters.has(id)) {\n return this.getBlockFilterChanges(id);\n }\n else if (this.pendingTransactionFilters.has(id)) {\n return this.getPendingTransactionFilterChanges(id);\n }\n return Promise.resolve(filterNotFoundError());\n }\n async getFilterLogs(filterId) {\n const id = (0, util_1.intNumberFromHexString)(filterId);\n const filter = this.logFilters.get(id);\n if (!filter) {\n return filterNotFoundError();\n }\n return this.sendAsyncPromise(Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { method: 'eth_getLogs', params: [paramFromFilter(filter)] }));\n }\n makeFilterId() {\n return (0, type_1.IntNumber)(++this.nextFilterId);\n }\n sendAsyncPromise(request) {\n return new Promise((resolve, reject) => {\n this.provider.sendAsync(request, (err, response) => {\n if (err) {\n return reject(err);\n }\n if (Array.isArray(response) || response == null) {\n return reject(new Error(`unexpected response received: ${JSON.stringify(response)}`));\n }\n resolve(response);\n });\n });\n }\n deleteFilter(id) {\n console.info(`Deleting filter (${id})`);\n this.logFilters.delete(id);\n this.blockFilters.delete(id);\n this.pendingTransactionFilters.delete(id);\n this.cursors.delete(id);\n this.timeouts.delete(id);\n }\n async getLogFilterChanges(id) {\n const filter = this.logFilters.get(id);\n const cursorPosition = this.cursors.get(id);\n if (!cursorPosition || !filter) {\n return filterNotFoundError();\n }\n const currentBlockHeight = await this.getCurrentBlockHeight();\n const toBlock = filter.toBlock === 'latest' ? currentBlockHeight : filter.toBlock;\n if (cursorPosition > currentBlockHeight) {\n return emptyResult();\n }\n if (cursorPosition > Number(filter.toBlock)) {\n return emptyResult();\n }\n console.info(`Fetching logs from ${cursorPosition} to ${toBlock} for filter ${id}`);\n const response = await this.sendAsyncPromise(Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { method: 'eth_getLogs', params: [\n paramFromFilter(Object.assign(Object.assign({}, filter), { fromBlock: cursorPosition, toBlock })),\n ] }));\n if (Array.isArray(response.result)) {\n const blocks = response.result.map((log) => (0, util_1.intNumberFromHexString)(log.blockNumber || '0x0'));\n const highestBlock = Math.max(...blocks);\n if (highestBlock && highestBlock > cursorPosition) {\n const newCursorPosition = (0, type_1.IntNumber)(highestBlock + 1);\n console.info(`Moving cursor position for filter (${id}) from ${cursorPosition} to ${newCursorPosition}`);\n this.cursors.set(id, newCursorPosition);\n }\n }\n return response;\n }\n async getBlockFilterChanges(id) {\n const cursorPosition = this.cursors.get(id);\n if (!cursorPosition) {\n return filterNotFoundError();\n }\n const currentBlockHeight = await this.getCurrentBlockHeight();\n if (cursorPosition > currentBlockHeight) {\n return emptyResult();\n }\n console.info(`Fetching blocks from ${cursorPosition} to ${currentBlockHeight} for filter (${id})`);\n const blocks = (await Promise.all(\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (0, util_1.range)(cursorPosition, currentBlockHeight + 1).map((i) => this.getBlockHashByNumber((0, type_1.IntNumber)(i))))).filter((hash) => !!hash);\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n const newCursorPosition = (0, type_1.IntNumber)(cursorPosition + blocks.length);\n console.info(`Moving cursor position for filter (${id}) from ${cursorPosition} to ${newCursorPosition}`);\n this.cursors.set(id, newCursorPosition);\n return Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { result: blocks });\n }\n async getPendingTransactionFilterChanges(_id) {\n // pending transaction filters are not supported\n return Promise.resolve(emptyResult());\n }\n async setInitialCursorPosition(id, startBlock) {\n const currentBlockHeight = await this.getCurrentBlockHeight();\n const initialCursorPosition = typeof startBlock === 'number' && startBlock > currentBlockHeight\n ? startBlock\n : currentBlockHeight;\n this.cursors.set(id, initialCursorPosition);\n return initialCursorPosition;\n }\n setFilterTimeout(id) {\n const existing = this.timeouts.get(id);\n if (existing) {\n window.clearTimeout(existing);\n }\n const timeout = window.setTimeout(() => {\n console.info(`Filter (${id}) timed out`);\n this.deleteFilter(id);\n }, TIMEOUT);\n this.timeouts.set(id, timeout);\n }\n // throttle eth_blockNumber requests\n async getCurrentBlockHeight() {\n const now = new Date();\n if (now.getTime() - this.lastFetchTimestamp.getTime() > this.REQUEST_THROTTLE_INTERVAL) {\n this.lastFetchTimestamp = now;\n const height = await this._getCurrentBlockHeight();\n this.currentBlockHeight = height;\n this.resolvers.forEach((resolve) => resolve(height));\n this.resolvers = [];\n }\n if (!this.currentBlockHeight) {\n return new Promise((resolve) => this.resolvers.push(resolve));\n }\n return this.currentBlockHeight;\n }\n async _getCurrentBlockHeight() {\n const { result } = await this.sendAsyncPromise(Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { method: 'eth_blockNumber', params: [] }));\n return (0, util_1.intNumberFromHexString)((0, util_1.ensureHexString)(result));\n }\n async getBlockHashByNumber(blockNumber) {\n const response = await this.sendAsyncPromise(Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { method: 'eth_getBlockByNumber', params: [(0, util_1.hexStringFromIntNumber)(blockNumber), false] }));\n if (response.result && typeof response.result.hash === 'string') {\n return (0, util_1.ensureHexString)(response.result.hash);\n }\n return null;\n }\n}\nexports.FilterPolyfill = FilterPolyfill;\nfunction filterFromParam(param) {\n return {\n fromBlock: intBlockHeightFromHexBlockHeight(param.fromBlock),\n toBlock: intBlockHeightFromHexBlockHeight(param.toBlock),\n addresses: param.address === undefined\n ? null\n : Array.isArray(param.address)\n ? param.address\n : [param.address],\n topics: param.topics || [],\n };\n}\nexports.filterFromParam = filterFromParam;\nfunction paramFromFilter(filter) {\n const param = {\n fromBlock: hexBlockHeightFromIntBlockHeight(filter.fromBlock),\n toBlock: hexBlockHeightFromIntBlockHeight(filter.toBlock),\n topics: filter.topics,\n };\n if (filter.addresses !== null) {\n param.address = filter.addresses;\n }\n return param;\n}\nfunction intBlockHeightFromHexBlockHeight(value) {\n if (value === undefined || value === 'latest' || value === 'pending') {\n return 'latest';\n }\n else if (value === 'earliest') {\n return (0, type_1.IntNumber)(0);\n }\n else if ((0, util_1.isHexString)(value)) {\n return (0, util_1.intNumberFromHexString)(value);\n }\n throw new Error(`Invalid block option: ${String(value)}`);\n}\nfunction hexBlockHeightFromIntBlockHeight(value) {\n if (value === 'latest') {\n return value;\n }\n return (0, util_1.hexStringFromIntNumber)(value);\n}\nfunction filterNotFoundError() {\n return Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { error: { code: -32000, message: 'filter not found' } });\n}\nfunction emptyResult() {\n return Object.assign(Object.assign({}, JSONRPC_TEMPLATE), { result: [] });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SubscriptionManager = void 0;\nconst eth_block_tracker_1 = require(\"eth-block-tracker\");\n// TODO: When we update this package we should be able to fix this\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst createSubscriptionManager = require('eth-json-rpc-filters/subscriptionManager');\nconst noop = () => { };\nclass SubscriptionManager {\n constructor(provider) {\n const blockTracker = new eth_block_tracker_1.PollingBlockTracker({\n provider: provider,\n pollingInterval: 15000,\n setSkipCacheFlag: true,\n });\n const { events, middleware } = createSubscriptionManager({\n blockTracker,\n provider,\n });\n this.events = events;\n this.subscriptionMiddleware = middleware;\n }\n async handleRequest(request) {\n const result = {};\n await this.subscriptionMiddleware(request, result, noop, noop);\n return result;\n }\n destroy() {\n this.subscriptionMiddleware.destroy();\n }\n}\nexports.SubscriptionManager = SubscriptionManager;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RelayAbstract = exports.APP_VERSION_KEY = exports.LOCAL_STORAGE_ADDRESSES_KEY = exports.WALLET_USER_NAME_KEY = void 0;\nconst error_1 = require(\"../core/error\");\nexports.WALLET_USER_NAME_KEY = 'walletUsername';\nexports.LOCAL_STORAGE_ADDRESSES_KEY = 'Addresses';\nexports.APP_VERSION_KEY = 'AppVersion';\nclass RelayAbstract {\n async makeEthereumJSONRPCRequest(request, jsonRpcUrl) {\n if (!jsonRpcUrl)\n throw new Error('Error: No jsonRpcUrl provided');\n return window\n .fetch(jsonRpcUrl, {\n method: 'POST',\n body: JSON.stringify(request),\n mode: 'cors',\n headers: { 'Content-Type': 'application/json' },\n })\n .then((res) => res.json())\n .then((json) => {\n if (!json) {\n throw error_1.standardErrors.rpc.parse({});\n }\n const response = json;\n const { error } = response;\n if (error) {\n throw (0, error_1.serializeError)(error, request.method);\n }\n return response;\n });\n }\n}\nexports.RelayAbstract = RelayAbstract;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RelayEventManager = void 0;\nconst util_1 = require(\"../core/util\");\nclass RelayEventManager {\n constructor() {\n this._nextRequestId = 0;\n this.callbacks = new Map();\n }\n makeRequestId() {\n // max nextId == max int32 for compatibility with mobile\n this._nextRequestId = (this._nextRequestId + 1) % 0x7fffffff;\n const id = this._nextRequestId;\n const idStr = (0, util_1.prepend0x)(id.toString(16));\n // unlikely that this will ever be an issue, but just to be safe\n const callback = this.callbacks.get(idStr);\n if (callback) {\n this.callbacks.delete(idStr);\n }\n return id;\n }\n}\nexports.RelayEventManager = RelayEventManager;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Session = void 0;\nconst sha_js_1 = require(\"sha.js\");\nconst util_1 = require(\"../core/util\");\nconst STORAGE_KEY_SESSION_ID = 'session:id';\nconst STORAGE_KEY_SESSION_SECRET = 'session:secret';\nconst STORAGE_KEY_SESSION_LINKED = 'session:linked';\nclass Session {\n constructor(storage, id, secret, linked) {\n this._storage = storage;\n this._id = id || (0, util_1.randomBytesHex)(16);\n this._secret = secret || (0, util_1.randomBytesHex)(32);\n this._key = new sha_js_1.sha256()\n .update(`${this._id}, ${this._secret} WalletLink`) // ensure old sessions stay connected\n .digest('hex');\n this._linked = !!linked;\n }\n static load(storage) {\n const id = storage.getItem(STORAGE_KEY_SESSION_ID);\n const linked = storage.getItem(STORAGE_KEY_SESSION_LINKED);\n const secret = storage.getItem(STORAGE_KEY_SESSION_SECRET);\n if (id && secret) {\n return new Session(storage, id, secret, linked === '1');\n }\n return null;\n }\n /**\n * Takes in a session ID and returns the sha256 hash of it.\n * @param sessionId session ID\n */\n static hash(sessionId) {\n return new sha_js_1.sha256().update(sessionId).digest('hex');\n }\n get id() {\n return this._id;\n }\n get secret() {\n return this._secret;\n }\n get key() {\n return this._key;\n }\n get linked() {\n return this._linked;\n }\n set linked(val) {\n this._linked = val;\n this.persistLinked();\n }\n save() {\n this._storage.setItem(STORAGE_KEY_SESSION_ID, this._id);\n this._storage.setItem(STORAGE_KEY_SESSION_SECRET, this._secret);\n this.persistLinked();\n return this;\n }\n persistLinked() {\n this._storage.setItem(STORAGE_KEY_SESSION_LINKED, this._linked ? '1' : '0');\n }\n}\nexports.Session = Session;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MobileRelay = void 0;\nconst util_1 = require(\"../../core/util\");\nconst WalletLinkRelay_1 = require(\"../walletlink/WalletLinkRelay\");\nconst MobileRelayUI_1 = require(\"./MobileRelayUI\");\nclass MobileRelay extends WalletLinkRelay_1.WalletLinkRelay {\n constructor(options) {\n var _a;\n super(options);\n this._enableMobileWalletLink = (_a = options.enableMobileWalletLink) !== null && _a !== void 0 ? _a : false;\n }\n // override\n requestEthereumAccounts() {\n if (this._enableMobileWalletLink) {\n return super.requestEthereumAccounts();\n }\n // TODO: Implement & present in-page wallet picker instead of navigating to www.coinbase.com/connect-dapp\n return {\n promise: new Promise(() => {\n const location = (0, util_1.getLocation)();\n location.href = `https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(location.href)}`;\n }),\n cancel: () => { },\n };\n }\n // override\n publishWeb3RequestEvent(id, request) {\n super.publishWeb3RequestEvent(id, request);\n if (!(this._enableMobileWalletLink && this.ui instanceof MobileRelayUI_1.MobileRelayUI))\n return;\n let navigatedToCBW = false;\n // For mobile relay requests, open the Coinbase Wallet app\n switch (request.method) {\n case 'requestEthereumAccounts':\n case 'connectAndSignIn':\n navigatedToCBW = true;\n this.ui.openCoinbaseWalletDeeplink(this.getQRCodeUrl());\n break;\n case 'switchEthereumChain':\n // switchEthereumChain doesn't need to open the app\n return;\n default:\n navigatedToCBW = true;\n this.ui.openCoinbaseWalletDeeplink();\n break;\n }\n // If the user navigated to the Coinbase Wallet app, then we need to check\n // for unseen events once the user returns to the browser\n if (navigatedToCBW) {\n window.addEventListener('blur', () => {\n window.addEventListener('focus', () => {\n this.connection.checkUnseenEvents();\n }, { once: true });\n }, { once: true });\n }\n }\n // override\n handleWeb3ResponseMessage(message) {\n super.handleWeb3ResponseMessage(message);\n if (this._enableMobileWalletLink && this.ui instanceof MobileRelayUI_1.MobileRelayUI) {\n this.ui.closeOpenedWindow();\n }\n }\n connectAndSignIn(params) {\n if (!this._enableMobileWalletLink) {\n throw new Error('connectAndSignIn is supported only when enableMobileWalletLink is on');\n }\n return this.sendRequest({\n method: 'connectAndSignIn',\n params: {\n appName: this.appName,\n appLogoUrl: this.appLogoUrl,\n domain: window.location.hostname,\n aud: window.location.href,\n version: '1',\n type: 'eip4361',\n nonce: params.nonce,\n iat: new Date().toISOString(),\n chainId: `eip155:${this.dappDefaultChain}`,\n statement: params.statement,\n resources: params.resources,\n },\n });\n }\n}\nexports.MobileRelay = MobileRelay;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MobileRelayUI = void 0;\nconst RedirectDialog_1 = require(\"../walletlink/ui/components/RedirectDialog/RedirectDialog\");\n// TODO: Implement & present in-page wallet picker instead of navigating to www.coinbase.com/connect-dapp\nclass MobileRelayUI {\n constructor(options) {\n this.attached = false;\n this.darkMode = false;\n this.openedWindow = null;\n this.redirectDialog = new RedirectDialog_1.RedirectDialog();\n this.darkMode = options.darkMode;\n }\n attach() {\n if (this.attached) {\n throw new Error('Coinbase Wallet SDK UI is already attached');\n }\n this.redirectDialog.attach();\n this.attached = true;\n }\n setConnected(_connected) { } // no-op\n closeOpenedWindow() {\n var _a;\n (_a = this.openedWindow) === null || _a === void 0 ? void 0 : _a.close();\n this.openedWindow = null;\n }\n redirectToCoinbaseWallet(walletLinkUrl) {\n const url = new URL('https://go.cb-w.com/walletlink');\n url.searchParams.append('redirect_url', window.location.href);\n if (walletLinkUrl) {\n url.searchParams.append('wl_url', walletLinkUrl);\n }\n this.openedWindow = window.open(url.href, 'cbw-opener');\n if (this.openedWindow) {\n setTimeout(() => this.closeOpenedWindow(), 5000);\n }\n }\n openCoinbaseWalletDeeplink(walletLinkUrl) {\n this.redirectDialog.present({\n title: 'Redirecting to Coinbase Wallet...',\n buttonText: 'Open',\n darkMode: this.darkMode,\n onButtonClick: () => {\n this.redirectToCoinbaseWallet(walletLinkUrl);\n },\n });\n setTimeout(() => {\n this.redirectToCoinbaseWallet(walletLinkUrl);\n }, 99);\n }\n showConnecting(_options) {\n // it uses the return callback to clear the dialog\n return () => {\n this.closeOpenedWindow();\n this.redirectDialog.clear();\n };\n }\n hideRequestEthereumAccounts() {\n this.closeOpenedWindow();\n this.redirectDialog.clear();\n }\n // -- Methods below are not needed for mobile\n requestEthereumAccounts() { } // no-op\n addEthereumChain() { } // no-op\n watchAsset() { } // no-op\n selectProvider() { } // no-op\n switchEthereumChain() { } // no-op\n signEthereumMessage() { } // no-op\n signEthereumTransaction() { } // no-op\n submitEthereumTransaction() { } // no-op\n ethereumAddressFromSignedMessage() { } // no-op\n reloadUI() { } // no-op\n setStandalone() { } // no-op\n setConnectDisabled() { } // no-op\n inlineAccountsResponse() {\n return false;\n }\n inlineAddEthereumChain() {\n return false;\n }\n inlineWatchAsset() {\n return false;\n }\n inlineSwitchEthereumChain() {\n return false;\n }\n isStandalone() {\n return false;\n }\n}\nexports.MobileRelayUI = MobileRelayUI;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WalletLinkRelay = void 0;\nconst error_1 = require(\"../../core/error\");\nconst type_1 = require(\"../../core/type\");\nconst util_1 = require(\"../../core/util\");\nconst DiagnosticLogger_1 = require(\"../../provider/DiagnosticLogger\");\nconst RelayAbstract_1 = require(\"../RelayAbstract\");\nconst Session_1 = require(\"../Session\");\nconst WalletLinkConnection_1 = require(\"./connection/WalletLinkConnection\");\nconst Web3Response_1 = require(\"./type/Web3Response\");\nconst WalletLinkRelayUI_1 = require(\"./ui/WalletLinkRelayUI\");\nclass WalletLinkRelay extends RelayAbstract_1.RelayAbstract {\n constructor(options) {\n var _a;\n super();\n this.accountsCallback = null;\n this.chainCallbackParams = { chainId: '', jsonRpcUrl: '' }; // to implement distinctUntilChanged\n this.chainCallback = null;\n this.dappDefaultChain = 1;\n this.appName = '';\n this.appLogoUrl = null;\n this.linkedUpdated = (linked) => {\n var _a;\n this.isLinked = linked;\n const cachedAddresses = this.storage.getItem(RelayAbstract_1.LOCAL_STORAGE_ADDRESSES_KEY);\n if (linked) {\n // Only set linked session variable one way\n this.session.linked = linked;\n }\n this.isUnlinkedErrorState = false;\n if (cachedAddresses) {\n const addresses = cachedAddresses.split(' ');\n const wasConnectedViaStandalone = this.storage.getItem('IsStandaloneSigning') === 'true';\n if (addresses[0] !== '' && !linked && this.session.linked && !wasConnectedViaStandalone) {\n this.isUnlinkedErrorState = true;\n const sessionIdHash = this.getSessionIdHash();\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.UNLINKED_ERROR_STATE, {\n sessionIdHash,\n });\n }\n }\n };\n this.metadataUpdated = (key, value) => {\n this.storage.setItem(key, value);\n };\n this.chainUpdated = (chainId, jsonRpcUrl) => {\n if (this.chainCallbackParams.chainId === chainId &&\n this.chainCallbackParams.jsonRpcUrl === jsonRpcUrl) {\n return;\n }\n this.chainCallbackParams = {\n chainId,\n jsonRpcUrl,\n };\n if (this.chainCallback) {\n this.chainCallback(chainId, jsonRpcUrl);\n }\n };\n this.accountUpdated = (selectedAddress) => {\n if (this.accountsCallback) {\n this.accountsCallback([selectedAddress]);\n }\n if (WalletLinkRelay.accountRequestCallbackIds.size > 0) {\n // We get the ethereum address from the metadata. If for whatever\n // reason we don't get a response via an explicit web3 message\n // we can still fulfill the eip1102 request.\n Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach((id) => {\n const message = {\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'requestEthereumAccounts',\n result: [selectedAddress],\n },\n };\n this.invokeCallback(Object.assign(Object.assign({}, message), { id }));\n });\n WalletLinkRelay.accountRequestCallbackIds.clear();\n }\n };\n this.connectedUpdated = (connected) => {\n this.ui.setConnected(connected);\n };\n this.resetAndReload = this.resetAndReload.bind(this);\n this.linkAPIUrl = options.linkAPIUrl;\n this.storage = options.storage;\n this.options = options;\n const { session, ui, connection } = this.subscribe();\n this._session = session;\n this.connection = connection;\n this.relayEventManager = options.relayEventManager;\n this.diagnostic = options.diagnosticLogger;\n this._reloadOnDisconnect = (_a = options.reloadOnDisconnect) !== null && _a !== void 0 ? _a : true;\n this.ui = ui;\n }\n subscribe() {\n const session = Session_1.Session.load(this.storage) || new Session_1.Session(this.storage).save();\n const { linkAPIUrl, diagnostic } = this;\n const connection = new WalletLinkConnection_1.WalletLinkConnection({\n session,\n linkAPIUrl,\n diagnostic,\n listener: this,\n });\n const { version, darkMode } = this.options;\n const ui = this.options.uiConstructor({\n linkAPIUrl,\n version,\n darkMode,\n session,\n });\n connection.connect();\n return { session, ui, connection };\n }\n attachUI() {\n this.ui.attach();\n }\n resetAndReload() {\n Promise.race([\n this.connection.setSessionMetadata('__destroyed', '1'),\n new Promise((resolve) => setTimeout(() => resolve(null), 1000)),\n ])\n .then(() => {\n var _a, _b;\n const isStandalone = this.ui.isStandalone();\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.SESSION_STATE_CHANGE, {\n method: 'relay::resetAndReload',\n sessionMetadataChange: '__destroyed, 1',\n sessionIdHash: this.getSessionIdHash(),\n });\n this.connection.destroy();\n /**\n * Only clear storage if the session id we have in memory matches the one on disk\n * Otherwise, in the case where we have 2 tabs, another tab might have cleared\n * storage already. In that case if we clear storage again, the user will be in\n * a state where the first tab allows the user to connect but the session that\n * was used isn't persisted. This leaves the user in a state where they aren't\n * connected to the mobile app.\n */\n const storedSession = Session_1.Session.load(this.storage);\n if ((storedSession === null || storedSession === void 0 ? void 0 : storedSession.id) === this._session.id) {\n this.storage.clear();\n }\n else if (storedSession) {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.SKIPPED_CLEARING_SESSION, {\n sessionIdHash: this.getSessionIdHash(),\n storedSessionIdHash: Session_1.Session.hash(storedSession.id),\n });\n }\n if (this._reloadOnDisconnect) {\n this.ui.reloadUI();\n return;\n }\n if (this.accountsCallback) {\n this.accountsCallback([], true);\n }\n const { session, ui, connection } = this.subscribe();\n this._session = session;\n this.connection = connection;\n this.ui = ui;\n if (isStandalone && this.ui.setStandalone)\n this.ui.setStandalone(true);\n this.attachUI();\n })\n .catch((err) => {\n var _a;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.FAILURE, {\n method: 'relay::resetAndReload',\n message: `failed to reset and reload with ${err}`,\n sessionIdHash: this.getSessionIdHash(),\n });\n });\n }\n setAppInfo(appName, appLogoUrl) {\n this.appName = appName;\n this.appLogoUrl = appLogoUrl;\n }\n getStorageItem(key) {\n return this.storage.getItem(key);\n }\n get session() {\n return this._session;\n }\n setStorageItem(key, value) {\n this.storage.setItem(key, value);\n }\n signEthereumMessage(message, address, addPrefix, typedDataJson) {\n return this.sendRequest({\n method: 'signEthereumMessage',\n params: {\n message: (0, util_1.hexStringFromBuffer)(message, true),\n address,\n addPrefix,\n typedDataJson: typedDataJson || null,\n },\n });\n }\n ethereumAddressFromSignedMessage(message, signature, addPrefix) {\n return this.sendRequest({\n method: 'ethereumAddressFromSignedMessage',\n params: {\n message: (0, util_1.hexStringFromBuffer)(message, true),\n signature: (0, util_1.hexStringFromBuffer)(signature, true),\n addPrefix,\n },\n });\n }\n signEthereumTransaction(params) {\n return this.sendRequest({\n method: 'signEthereumTransaction',\n params: {\n fromAddress: params.fromAddress,\n toAddress: params.toAddress,\n weiValue: (0, util_1.bigIntStringFromBN)(params.weiValue),\n data: (0, util_1.hexStringFromBuffer)(params.data, true),\n nonce: params.nonce,\n gasPriceInWei: params.gasPriceInWei ? (0, util_1.bigIntStringFromBN)(params.gasPriceInWei) : null,\n maxFeePerGas: params.gasPriceInWei ? (0, util_1.bigIntStringFromBN)(params.gasPriceInWei) : null,\n maxPriorityFeePerGas: params.gasPriceInWei\n ? (0, util_1.bigIntStringFromBN)(params.gasPriceInWei)\n : null,\n gasLimit: params.gasLimit ? (0, util_1.bigIntStringFromBN)(params.gasLimit) : null,\n chainId: params.chainId,\n shouldSubmit: false,\n },\n });\n }\n signAndSubmitEthereumTransaction(params) {\n return this.sendRequest({\n method: 'signEthereumTransaction',\n params: {\n fromAddress: params.fromAddress,\n toAddress: params.toAddress,\n weiValue: (0, util_1.bigIntStringFromBN)(params.weiValue),\n data: (0, util_1.hexStringFromBuffer)(params.data, true),\n nonce: params.nonce,\n gasPriceInWei: params.gasPriceInWei ? (0, util_1.bigIntStringFromBN)(params.gasPriceInWei) : null,\n maxFeePerGas: params.maxFeePerGas ? (0, util_1.bigIntStringFromBN)(params.maxFeePerGas) : null,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas\n ? (0, util_1.bigIntStringFromBN)(params.maxPriorityFeePerGas)\n : null,\n gasLimit: params.gasLimit ? (0, util_1.bigIntStringFromBN)(params.gasLimit) : null,\n chainId: params.chainId,\n shouldSubmit: true,\n },\n });\n }\n submitEthereumTransaction(signedTransaction, chainId) {\n return this.sendRequest({\n method: 'submitEthereumTransaction',\n params: {\n signedTransaction: (0, util_1.hexStringFromBuffer)(signedTransaction, true),\n chainId,\n },\n });\n }\n scanQRCode(regExp) {\n return this.sendRequest({\n method: 'scanQRCode',\n params: {\n regExp,\n },\n });\n }\n getQRCodeUrl() {\n return (0, util_1.createQrUrl)(this._session.id, this._session.secret, this.linkAPIUrl, false, this.options.version, this.dappDefaultChain);\n }\n genericRequest(data, action) {\n return this.sendRequest({\n method: 'generic',\n params: {\n action,\n data,\n },\n });\n }\n sendGenericMessage(request) {\n return this.sendRequest(request);\n }\n sendRequest(request) {\n let hideSnackbarItem = null;\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n };\n const promise = new Promise((resolve, reject) => {\n if (!this.ui.isStandalone()) {\n hideSnackbarItem = this.ui.showConnecting({\n isUnlinkedErrorState: this.isUnlinkedErrorState,\n onCancel: cancel,\n onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method\n });\n }\n this.relayEventManager.callbacks.set(id, (response) => {\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n if (this.ui.isStandalone()) {\n this.sendRequestStandalone(id, request);\n }\n else {\n this.publishWeb3RequestEvent(id, request);\n }\n });\n return { promise, cancel };\n }\n setConnectDisabled(disabled) {\n this.ui.setConnectDisabled(disabled);\n }\n setAccountsCallback(accountsCallback) {\n this.accountsCallback = accountsCallback;\n }\n setChainCallback(chainCallback) {\n this.chainCallback = chainCallback;\n }\n setDappDefaultChainCallback(chainId) {\n this.dappDefaultChain = chainId;\n if (this.ui instanceof WalletLinkRelayUI_1.WalletLinkRelayUI) {\n this.ui.setChainId(chainId);\n }\n }\n publishWeb3RequestEvent(id, request) {\n var _a;\n const message = { type: 'WEB3_REQUEST', id, request };\n const storedSession = Session_1.Session.load(this.storage);\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.WEB3_REQUEST, {\n eventId: message.id,\n method: `relay::${request.method}`,\n sessionIdHash: this.getSessionIdHash(),\n storedSessionIdHash: storedSession ? Session_1.Session.hash(storedSession.id) : '',\n isSessionMismatched: ((storedSession === null || storedSession === void 0 ? void 0 : storedSession.id) !== this._session.id).toString(),\n });\n this.publishEvent('Web3Request', message, true)\n .then((_) => {\n var _a;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.WEB3_REQUEST_PUBLISHED, {\n eventId: message.id,\n method: `relay::${request.method}`,\n sessionIdHash: this.getSessionIdHash(),\n storedSessionIdHash: storedSession ? Session_1.Session.hash(storedSession.id) : '',\n isSessionMismatched: ((storedSession === null || storedSession === void 0 ? void 0 : storedSession.id) !== this._session.id).toString(),\n });\n })\n .catch((err) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id: message.id,\n response: {\n method: request.method,\n errorMessage: err.message,\n },\n });\n });\n }\n publishWeb3RequestCanceledEvent(id) {\n const message = {\n type: 'WEB3_REQUEST_CANCELED',\n id,\n };\n this.publishEvent('Web3RequestCanceled', message, false).then();\n }\n publishEvent(event, message, callWebhook) {\n return this.connection.publishEvent(event, message, callWebhook);\n }\n handleWeb3ResponseMessage(message) {\n var _a;\n const { response } = message;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.WEB3_RESPONSE, {\n eventId: message.id,\n method: `relay::${response.method}`,\n sessionIdHash: this.getSessionIdHash(),\n });\n if (response.method === 'requestEthereumAccounts') {\n WalletLinkRelay.accountRequestCallbackIds.forEach((id) => this.invokeCallback(Object.assign(Object.assign({}, message), { id })));\n WalletLinkRelay.accountRequestCallbackIds.clear();\n return;\n }\n this.invokeCallback(message);\n }\n handleErrorResponse(id, method, error, errorCode) {\n var _a;\n const errorMessage = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : (0, error_1.getMessageFromCode)(errorCode);\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method,\n errorMessage,\n errorCode,\n },\n });\n }\n invokeCallback(message) {\n const callback = this.relayEventManager.callbacks.get(message.id);\n if (callback) {\n callback(message.response);\n this.relayEventManager.callbacks.delete(message.id);\n }\n }\n requestEthereumAccounts() {\n const request = {\n method: 'requestEthereumAccounts',\n params: {\n appName: this.appName,\n appLogoUrl: this.appLogoUrl || null,\n },\n };\n const hideSnackbarItem = null;\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n };\n const promise = new Promise((resolve, reject) => {\n this.relayEventManager.callbacks.set(id, (response) => {\n this.ui.hideRequestEthereumAccounts();\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n if (this.ui.inlineAccountsResponse()) {\n const onAccounts = (accounts) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: { method: 'requestEthereumAccounts', result: accounts },\n });\n };\n this.ui.requestEthereumAccounts({\n onCancel: cancel,\n onAccounts,\n });\n }\n else {\n // Error if user closes TryExtensionLinkDialog without connecting\n const err = error_1.standardErrors.provider.userRejectedRequest('User denied account authorization');\n this.ui.requestEthereumAccounts({\n onCancel: () => cancel(err),\n });\n }\n WalletLinkRelay.accountRequestCallbackIds.add(id);\n if (!this.ui.inlineAccountsResponse() && !this.ui.isStandalone()) {\n this.publishWeb3RequestEvent(id, request);\n }\n });\n return { promise, cancel };\n }\n selectProvider(providerOptions) {\n const request = {\n method: 'selectProvider',\n params: {\n providerOptions,\n },\n };\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n };\n const promise = new Promise((resolve, reject) => {\n this.relayEventManager.callbacks.set(id, (response) => {\n if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n const _cancel = (_error) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: { method: 'selectProvider', result: type_1.ProviderType.Unselected },\n });\n };\n const approve = (selectedProviderKey) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: { method: 'selectProvider', result: selectedProviderKey },\n });\n };\n if (this.ui.selectProvider)\n this.ui.selectProvider({\n onApprove: approve,\n onCancel: _cancel,\n providerOptions,\n });\n });\n return { cancel, promise };\n }\n watchAsset(type, address, symbol, decimals, image, chainId) {\n const request = {\n method: 'watchAsset',\n params: {\n type,\n options: {\n address,\n symbol,\n decimals,\n image,\n },\n chainId,\n },\n };\n let hideSnackbarItem = null;\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n };\n if (!this.ui.inlineWatchAsset()) {\n hideSnackbarItem = this.ui.showConnecting({\n isUnlinkedErrorState: this.isUnlinkedErrorState,\n onCancel: cancel,\n onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method\n });\n }\n const promise = new Promise((resolve, reject) => {\n this.relayEventManager.callbacks.set(id, (response) => {\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n const _cancel = (_error) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'watchAsset',\n result: false,\n },\n });\n };\n const approve = () => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'watchAsset',\n result: true,\n },\n });\n };\n if (this.ui.inlineWatchAsset()) {\n this.ui.watchAsset({\n onApprove: approve,\n onCancel: _cancel,\n type,\n address,\n symbol,\n decimals,\n image,\n chainId,\n });\n }\n if (!this.ui.inlineWatchAsset() && !this.ui.isStandalone()) {\n this.publishWeb3RequestEvent(id, request);\n }\n });\n return { cancel, promise };\n }\n addEthereumChain(chainId, rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency) {\n const request = {\n method: 'addEthereumChain',\n params: {\n chainId,\n rpcUrls,\n blockExplorerUrls,\n chainName,\n iconUrls,\n nativeCurrency,\n },\n };\n let hideSnackbarItem = null;\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n };\n if (!this.ui.inlineAddEthereumChain(chainId)) {\n hideSnackbarItem = this.ui.showConnecting({\n isUnlinkedErrorState: this.isUnlinkedErrorState,\n onCancel: cancel,\n onResetConnection: this.resetAndReload, // eslint-disable-line @typescript-eslint/unbound-method\n });\n }\n const promise = new Promise((resolve, reject) => {\n this.relayEventManager.callbacks.set(id, (response) => {\n hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();\n if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n const _cancel = (_error) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'addEthereumChain',\n result: {\n isApproved: false,\n rpcUrl: '',\n },\n },\n });\n };\n const approve = (rpcUrl) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'addEthereumChain',\n result: {\n isApproved: true,\n rpcUrl,\n },\n },\n });\n };\n if (this.ui.inlineAddEthereumChain(chainId)) {\n this.ui.addEthereumChain({\n onCancel: _cancel,\n onApprove: approve,\n chainId: request.params.chainId,\n rpcUrls: request.params.rpcUrls,\n blockExplorerUrls: request.params.blockExplorerUrls,\n chainName: request.params.chainName,\n iconUrls: request.params.iconUrls,\n nativeCurrency: request.params.nativeCurrency,\n });\n }\n if (!this.ui.inlineAddEthereumChain(chainId) && !this.ui.isStandalone()) {\n this.publishWeb3RequestEvent(id, request);\n }\n });\n return { promise, cancel };\n }\n switchEthereumChain(chainId, address) {\n const request = {\n method: 'switchEthereumChain',\n params: Object.assign({ chainId }, { address }),\n };\n const id = (0, util_1.randomBytesHex)(8);\n const cancel = (error) => {\n this.publishWeb3RequestCanceledEvent(id);\n this.handleErrorResponse(id, request.method, error);\n };\n const promise = new Promise((resolve, reject) => {\n this.relayEventManager.callbacks.set(id, (response) => {\n if ((0, Web3Response_1.isErrorResponse)(response) && response.errorCode) {\n return reject(error_1.standardErrors.provider.custom({\n code: response.errorCode,\n message: `Unrecognized chain ID. Try adding the chain using addEthereumChain first.`,\n }));\n }\n else if ((0, Web3Response_1.isErrorResponse)(response)) {\n return reject(new Error(response.errorMessage));\n }\n resolve(response);\n });\n const _cancel = (error) => {\n var _a;\n if (error) {\n // backward compatibility\n const errorCode = (_a = (0, error_1.getErrorCode)(error)) !== null && _a !== void 0 ? _a : error_1.standardErrorCodes.provider.unsupportedChain;\n this.handleErrorResponse(id, 'switchEthereumChain', error instanceof Error ? error : error_1.standardErrors.provider.unsupportedChain(chainId), errorCode);\n }\n else {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'switchEthereumChain',\n result: {\n isApproved: false,\n rpcUrl: '',\n },\n },\n });\n }\n };\n const approve = (rpcUrl) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response: {\n method: 'switchEthereumChain',\n result: {\n isApproved: true,\n rpcUrl,\n },\n },\n });\n };\n this.ui.switchEthereumChain({\n onCancel: _cancel,\n onApprove: approve,\n chainId: request.params.chainId,\n address: request.params.address,\n });\n if (!this.ui.inlineSwitchEthereumChain() && !this.ui.isStandalone()) {\n this.publishWeb3RequestEvent(id, request);\n }\n });\n return { promise, cancel };\n }\n inlineAddEthereumChain(chainId) {\n return this.ui.inlineAddEthereumChain(chainId);\n }\n getSessionIdHash() {\n return Session_1.Session.hash(this._session.id);\n }\n sendRequestStandalone(id, request) {\n const _cancel = (error) => {\n this.handleErrorResponse(id, request.method, error);\n };\n const onSuccess = (response) => {\n this.handleWeb3ResponseMessage({\n type: 'WEB3_RESPONSE',\n id,\n response,\n });\n };\n switch (request.method) {\n case 'signEthereumMessage':\n this.ui.signEthereumMessage({\n request,\n onSuccess,\n onCancel: _cancel,\n });\n break;\n case 'signEthereumTransaction':\n this.ui.signEthereumTransaction({\n request,\n onSuccess,\n onCancel: _cancel,\n });\n break;\n case 'submitEthereumTransaction':\n this.ui.submitEthereumTransaction({\n request,\n onSuccess,\n onCancel: _cancel,\n });\n break;\n case 'ethereumAddressFromSignedMessage':\n this.ui.ethereumAddressFromSignedMessage({\n request,\n onSuccess,\n });\n break;\n default:\n _cancel();\n break;\n }\n }\n}\nexports.WalletLinkRelay = WalletLinkRelay;\nWalletLinkRelay.accountRequestCallbackIds = new Set();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WalletLinkConnection = void 0;\nconst type_1 = require(\"../../../core/type\");\nconst Cipher_1 = require(\"../../../lib/Cipher\");\nconst DiagnosticLogger_1 = require(\"../../../provider/DiagnosticLogger\");\nconst RelayAbstract_1 = require(\"../../RelayAbstract\");\nconst Session_1 = require(\"../../Session\");\nconst WalletLinkHTTP_1 = require(\"./WalletLinkHTTP\");\nconst WalletLinkWebSocket_1 = require(\"./WalletLinkWebSocket\");\nconst HEARTBEAT_INTERVAL = 10000;\nconst REQUEST_TIMEOUT = 60000;\n/**\n * Coinbase Wallet Connection\n */\nclass WalletLinkConnection {\n /**\n * Constructor\n * @param session Session\n * @param linkAPIUrl Coinbase Wallet link server URL\n * @param listener WalletLinkConnectionUpdateListener\n * @param [WebSocketClass] Custom WebSocket implementation\n */\n constructor({ session, linkAPIUrl, listener, diagnostic, WebSocketClass = WebSocket, }) {\n this.destroyed = false;\n this.lastHeartbeatResponse = 0;\n this.nextReqId = (0, type_1.IntNumber)(1);\n /**\n * true if connected and authenticated, else false\n * runs listener when connected status changes\n */\n this._connected = false;\n /**\n * true if linked (a guest has joined before)\n * runs listener when linked status changes\n */\n this._linked = false;\n this.shouldFetchUnseenEventsOnConnect = false;\n this.requestResolutions = new Map();\n this.handleSessionMetadataUpdated = (metadata) => {\n if (!metadata)\n return;\n // Map of metadata key to handler function\n const handlers = new Map([\n ['__destroyed', this.handleDestroyed],\n ['EthereumAddress', this.handleAccountUpdated],\n ['WalletUsername', this.handleWalletUsernameUpdated],\n ['AppVersion', this.handleAppVersionUpdated],\n [\n 'ChainId',\n (v) => metadata.JsonRpcUrl && this.handleChainUpdated(v, metadata.JsonRpcUrl),\n ],\n ]);\n // call handler for each metadata key if value is defined\n handlers.forEach((handler, key) => {\n const value = metadata[key];\n if (value === undefined)\n return;\n handler(value);\n });\n };\n this.handleDestroyed = (__destroyed) => {\n var _a, _b;\n if (__destroyed !== '1')\n return;\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.resetAndReload();\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.METADATA_DESTROYED, {\n alreadyDestroyed: this.isDestroyed,\n sessionIdHash: Session_1.Session.hash(this.session.id),\n });\n };\n this.handleAccountUpdated = async (encryptedEthereumAddress) => {\n var _a, _b;\n try {\n const address = await this.cipher.decrypt(encryptedEthereumAddress);\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.accountUpdated(address);\n }\n catch (_c) {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.GENERAL_ERROR, {\n message: 'Had error decrypting',\n value: 'selectedAddress',\n });\n }\n };\n this.handleMetadataUpdated = async (key, encryptedMetadataValue) => {\n var _a, _b;\n try {\n const decryptedValue = await this.cipher.decrypt(encryptedMetadataValue);\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.metadataUpdated(key, decryptedValue);\n }\n catch (_c) {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.GENERAL_ERROR, {\n message: 'Had error decrypting',\n value: key,\n });\n }\n };\n this.handleWalletUsernameUpdated = async (walletUsername) => {\n this.handleMetadataUpdated(RelayAbstract_1.WALLET_USER_NAME_KEY, walletUsername);\n };\n this.handleAppVersionUpdated = async (appVersion) => {\n this.handleMetadataUpdated(RelayAbstract_1.APP_VERSION_KEY, appVersion);\n };\n this.handleChainUpdated = async (encryptedChainId, encryptedJsonRpcUrl) => {\n var _a, _b;\n try {\n const chainId = await this.cipher.decrypt(encryptedChainId);\n const jsonRpcUrl = await this.cipher.decrypt(encryptedJsonRpcUrl);\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.chainUpdated(chainId, jsonRpcUrl);\n }\n catch (_c) {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.GENERAL_ERROR, {\n message: 'Had error decrypting',\n value: 'chainId|jsonRpcUrl',\n });\n }\n };\n this.session = session;\n this.cipher = new Cipher_1.Cipher(session.secret);\n this.diagnostic = diagnostic;\n this.listener = listener;\n const ws = new WalletLinkWebSocket_1.WalletLinkWebSocket(`${linkAPIUrl}/rpc`, WebSocketClass);\n ws.setConnectionStateListener(async (state) => {\n var _a;\n // attempt to reconnect every 5 seconds when disconnected\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.CONNECTED_STATE_CHANGE, {\n state,\n sessionIdHash: Session_1.Session.hash(session.id),\n });\n let connected = false;\n switch (state) {\n case WalletLinkWebSocket_1.ConnectionState.DISCONNECTED:\n // if DISCONNECTED and not destroyed\n if (!this.destroyed) {\n const connect = async () => {\n // wait 5 seconds\n await new Promise((resolve) => setTimeout(resolve, 5000));\n // check whether it's destroyed again\n if (!this.destroyed) {\n // reconnect\n ws.connect().catch(() => {\n connect();\n });\n }\n };\n connect();\n }\n break;\n case WalletLinkWebSocket_1.ConnectionState.CONNECTED:\n // perform authentication upon connection\n try {\n // if CONNECTED, authenticate, and then check link status\n await this.authenticate();\n this.sendIsLinked();\n this.sendGetSessionConfig();\n connected = true;\n }\n catch (_b) {\n /* empty */\n }\n // send heartbeat every n seconds while connected\n // if CONNECTED, start the heartbeat timer\n // first timer event updates lastHeartbeat timestamp\n // subsequent calls send heartbeat message\n this.updateLastHeartbeat();\n setInterval(() => {\n this.heartbeat();\n }, HEARTBEAT_INTERVAL);\n // check for unseen events\n if (this.shouldFetchUnseenEventsOnConnect) {\n this.fetchUnseenEventsAPI();\n }\n break;\n case WalletLinkWebSocket_1.ConnectionState.CONNECTING:\n break;\n }\n // distinctUntilChanged\n if (this.connected !== connected) {\n this.connected = connected;\n }\n });\n ws.setIncomingDataListener((m) => {\n var _a, _b, _c;\n switch (m.type) {\n // handle server's heartbeat responses\n case 'Heartbeat':\n this.updateLastHeartbeat();\n return;\n // handle link status updates\n case 'IsLinkedOK':\n case 'Linked': {\n const linked = m.type === 'IsLinkedOK' ? m.linked : undefined;\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.LINKED, {\n sessionIdHash: Session_1.Session.hash(session.id),\n linked,\n type: m.type,\n onlineGuests: m.onlineGuests,\n });\n this.linked = linked || m.onlineGuests > 0;\n break;\n }\n // handle session config updates\n case 'GetSessionConfigOK':\n case 'SessionConfigUpdated': {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.SESSION_CONFIG_RECEIVED, {\n sessionIdHash: Session_1.Session.hash(session.id),\n metadata_keys: m && m.metadata ? Object.keys(m.metadata) : undefined,\n });\n this.handleSessionMetadataUpdated(m.metadata);\n break;\n }\n case 'Event': {\n this.handleIncomingEvent(m);\n break;\n }\n }\n // resolve request promises\n if (m.id !== undefined) {\n (_c = this.requestResolutions.get(m.id)) === null || _c === void 0 ? void 0 : _c(m);\n }\n });\n this.ws = ws;\n this.http = new WalletLinkHTTP_1.WalletLinkHTTP(linkAPIUrl, session.id, session.key);\n }\n /**\n * Make a connection to the server\n */\n connect() {\n var _a;\n if (this.destroyed) {\n throw new Error('instance is destroyed');\n }\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.STARTED_CONNECTING, {\n sessionIdHash: Session_1.Session.hash(this.session.id),\n });\n this.ws.connect();\n }\n /**\n * Terminate connection, and mark as destroyed. To reconnect, create a new\n * instance of WalletSDKConnection\n */\n destroy() {\n var _a;\n this.destroyed = true;\n this.ws.disconnect();\n (_a = this.diagnostic) === null || _a === void 0 ? void 0 : _a.log(DiagnosticLogger_1.EVENTS.DISCONNECTED, {\n sessionIdHash: Session_1.Session.hash(this.session.id),\n });\n this.listener = undefined;\n }\n get isDestroyed() {\n return this.destroyed;\n }\n get connected() {\n return this._connected;\n }\n set connected(connected) {\n var _a, _b;\n this._connected = connected;\n if (connected)\n (_a = this.onceConnected) === null || _a === void 0 ? void 0 : _a.call(this);\n (_b = this.listener) === null || _b === void 0 ? void 0 : _b.connectedUpdated(connected);\n }\n setOnceConnected(callback) {\n return new Promise((resolve) => {\n if (this.connected) {\n callback().then(resolve);\n }\n else {\n this.onceConnected = () => {\n callback().then(resolve);\n this.onceConnected = undefined;\n };\n }\n });\n }\n get linked() {\n return this._linked;\n }\n set linked(linked) {\n var _a, _b;\n this._linked = linked;\n if (linked)\n (_a = this.onceLinked) === null || _a === void 0 ? void 0 : _a.call(this);\n (_b = this.listener) === null || _b === void 0 ? void 0 : _b.linkedUpdated(linked);\n }\n setOnceLinked(callback) {\n return new Promise((resolve) => {\n if (this.linked) {\n callback().then(resolve);\n }\n else {\n this.onceLinked = () => {\n callback().then(resolve);\n this.onceLinked = undefined;\n };\n }\n });\n }\n async handleIncomingEvent(m) {\n var _a, _b;\n if (m.type !== 'Event' || m.event !== 'Web3Response') {\n return;\n }\n try {\n const decryptedData = await this.cipher.decrypt(m.data);\n const message = JSON.parse(decryptedData);\n if (message.type !== 'WEB3_RESPONSE')\n return;\n (_a = this.listener) === null || _a === void 0 ? void 0 : _a.handleWeb3ResponseMessage(message);\n }\n catch (_c) {\n (_b = this.diagnostic) === null || _b === void 0 ? void 0 : _b.log(DiagnosticLogger_1.EVENTS.GENERAL_ERROR, {\n message: 'Had error decrypting',\n value: 'incomingEvent',\n });\n }\n }\n async checkUnseenEvents() {\n if (!this.connected) {\n this.shouldFetchUnseenEventsOnConnect = true;\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, 250));\n try {\n await this.fetchUnseenEventsAPI();\n }\n catch (e) {\n console.error('Unable to check for unseen events', e);\n }\n }\n async fetchUnseenEventsAPI() {\n this.shouldFetchUnseenEventsOnConnect = false;\n const responseEvents = await this.http.fetchUnseenEvents();\n responseEvents.forEach((e) => this.handleIncomingEvent(e));\n }\n /**\n * Set session metadata in SessionConfig object\n * @param key\n * @param value\n * @returns a Promise that completes when successful\n */\n async setSessionMetadata(key, value) {\n const message = {\n type: 'SetSessionConfig',\n id: (0, type_1.IntNumber)(this.nextReqId++),\n sessionId: this.session.id,\n metadata: { [key]: value },\n };\n return this.setOnceConnected(async () => {\n const res = await this.makeRequest(message);\n if (res.type === 'Fail') {\n throw new Error(res.error || 'failed to set session metadata');\n }\n });\n }\n /**\n * Publish an event and emit event ID when successful\n * @param event event name\n * @param unencryptedData unencrypted event data\n * @param callWebhook whether the webhook should be invoked\n * @returns a Promise that emits event ID when successful\n */\n async publishEvent(event, unencryptedData, callWebhook = false) {\n const data = await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({}, unencryptedData), { origin: location.origin, relaySource: window.coinbaseWalletExtension ? 'injected_sdk' : 'sdk' })));\n const message = {\n type: 'PublishEvent',\n id: (0, type_1.IntNumber)(this.nextReqId++),\n sessionId: this.session.id,\n event,\n data,\n callWebhook,\n };\n return this.setOnceLinked(async () => {\n const res = await this.makeRequest(message);\n if (res.type === 'Fail') {\n throw new Error(res.error || 'failed to publish event');\n }\n return res.eventId;\n });\n }\n sendData(message) {\n this.ws.sendData(JSON.stringify(message));\n }\n updateLastHeartbeat() {\n this.lastHeartbeatResponse = Date.now();\n }\n heartbeat() {\n if (Date.now() - this.lastHeartbeatResponse > HEARTBEAT_INTERVAL * 2) {\n this.ws.disconnect();\n return;\n }\n try {\n this.ws.sendData('h');\n }\n catch (_a) {\n // noop\n }\n }\n async makeRequest(message, timeout = REQUEST_TIMEOUT) {\n const reqId = message.id;\n this.sendData(message);\n // await server message with corresponding id\n let timeoutId;\n return Promise.race([\n new Promise((_, reject) => {\n timeoutId = window.setTimeout(() => {\n reject(new Error(`request ${reqId} timed out`));\n }, timeout);\n }),\n new Promise((resolve) => {\n this.requestResolutions.set(reqId, (m) => {\n clearTimeout(timeoutId); // clear the timeout\n resolve(m);\n this.requestResolutions.delete(reqId);\n });\n }),\n ]);\n }\n async authenticate() {\n const m = {\n type: 'HostSession',\n id: (0, type_1.IntNumber)(this.nextReqId++),\n sessionId: this.session.id,\n sessionKey: this.session.key,\n };\n const res = await this.makeRequest(m);\n if (res.type === 'Fail') {\n throw new Error(res.error || 'failed to authentcate');\n }\n }\n sendIsLinked() {\n const m = {\n type: 'IsLinked',\n id: (0, type_1.IntNumber)(this.nextReqId++),\n sessionId: this.session.id,\n };\n this.sendData(m);\n }\n sendGetSessionConfig() {\n const m = {\n type: 'GetSessionConfig',\n id: (0, type_1.IntNumber)(this.nextReqId++),\n sessionId: this.session.id,\n };\n this.sendData(m);\n }\n}\nexports.WalletLinkConnection = WalletLinkConnection;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WalletLinkHTTP = void 0;\nclass WalletLinkHTTP {\n constructor(linkAPIUrl, sessionId, sessionKey) {\n this.linkAPIUrl = linkAPIUrl;\n this.sessionId = sessionId;\n const credentials = `${sessionId}:${sessionKey}`;\n this.auth = `Basic ${btoa(credentials)}`;\n }\n // mark unseen events as seen\n async markUnseenEventsAsSeen(events) {\n return Promise.all(events.map((e) => fetch(`${this.linkAPIUrl}/events/${e.eventId}/seen`, {\n method: 'POST',\n headers: {\n Authorization: this.auth,\n },\n }))).catch((error) => console.error('Unabled to mark event as failed:', error));\n }\n async fetchUnseenEvents() {\n var _a;\n const response = await fetch(`${this.linkAPIUrl}/events?unseen=true`, {\n headers: {\n Authorization: this.auth,\n },\n });\n if (response.ok) {\n const { events, error } = (await response.json());\n if (error) {\n throw new Error(`Check unseen events failed: ${error}`);\n }\n const responseEvents = (_a = events === null || events === void 0 ? void 0 : events.filter((e) => e.event === 'Web3Response').map((e) => ({\n type: 'Event',\n sessionId: this.sessionId,\n eventId: e.id,\n event: e.event,\n data: e.data,\n }))) !== null && _a !== void 0 ? _a : [];\n this.markUnseenEventsAsSeen(responseEvents);\n return responseEvents;\n }\n throw new Error(`Check unseen events failed: ${response.status}`);\n }\n}\nexports.WalletLinkHTTP = WalletLinkHTTP;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WalletLinkWebSocket = exports.ConnectionState = void 0;\nvar ConnectionState;\n(function (ConnectionState) {\n ConnectionState[ConnectionState[\"DISCONNECTED\"] = 0] = \"DISCONNECTED\";\n ConnectionState[ConnectionState[\"CONNECTING\"] = 1] = \"CONNECTING\";\n ConnectionState[ConnectionState[\"CONNECTED\"] = 2] = \"CONNECTED\";\n})(ConnectionState || (exports.ConnectionState = ConnectionState = {}));\nclass WalletLinkWebSocket {\n setConnectionStateListener(listener) {\n this.connectionStateListener = listener;\n }\n setIncomingDataListener(listener) {\n this.incomingDataListener = listener;\n }\n /**\n * Constructor\n * @param url WebSocket server URL\n * @param [WebSocketClass] Custom WebSocket implementation\n */\n constructor(url, WebSocketClass = WebSocket) {\n this.WebSocketClass = WebSocketClass;\n this.webSocket = null;\n this.pendingData = [];\n this.url = url.replace(/^http/, 'ws');\n }\n /**\n * Make a websocket connection\n * @returns a Promise that resolves when connected\n */\n async connect() {\n if (this.webSocket) {\n throw new Error('webSocket object is not null');\n }\n return new Promise((resolve, reject) => {\n var _a;\n let webSocket;\n try {\n this.webSocket = webSocket = new this.WebSocketClass(this.url);\n }\n catch (err) {\n reject(err);\n return;\n }\n (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.CONNECTING);\n webSocket.onclose = (evt) => {\n var _a;\n this.clearWebSocket();\n reject(new Error(`websocket error ${evt.code}: ${evt.reason}`));\n (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.DISCONNECTED);\n };\n webSocket.onopen = (_) => {\n var _a;\n resolve();\n (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.CONNECTED);\n if (this.pendingData.length > 0) {\n const pending = [...this.pendingData];\n pending.forEach((data) => this.sendData(data));\n this.pendingData = [];\n }\n };\n webSocket.onmessage = (evt) => {\n var _a, _b;\n if (evt.data === 'h') {\n (_a = this.incomingDataListener) === null || _a === void 0 ? void 0 : _a.call(this, {\n type: 'Heartbeat',\n });\n }\n else {\n try {\n const message = JSON.parse(evt.data);\n (_b = this.incomingDataListener) === null || _b === void 0 ? void 0 : _b.call(this, message);\n }\n catch (_c) {\n /* empty */\n }\n }\n };\n });\n }\n /**\n * Disconnect from server\n */\n disconnect() {\n var _a;\n const { webSocket } = this;\n if (!webSocket) {\n return;\n }\n this.clearWebSocket();\n (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.DISCONNECTED);\n this.connectionStateListener = undefined;\n this.incomingDataListener = undefined;\n try {\n webSocket.close();\n }\n catch (_b) {\n // noop\n }\n }\n /**\n * Send data to server\n * @param data text to send\n */\n sendData(data) {\n const { webSocket } = this;\n if (!webSocket) {\n this.pendingData.push(data);\n this.connect();\n return;\n }\n webSocket.send(data);\n }\n clearWebSocket() {\n const { webSocket } = this;\n if (!webSocket) {\n return;\n }\n this.webSocket = null;\n webSocket.onclose = null;\n webSocket.onerror = null;\n webSocket.onmessage = null;\n webSocket.onopen = null;\n }\n}\nexports.WalletLinkWebSocket = WalletLinkWebSocket;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isErrorResponse = void 0;\n// TODO: revisit if this is still needed\nfunction isErrorResponse(response) {\n return response.errorMessage !== undefined;\n}\nexports.isErrorResponse = isErrorResponse;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WalletLinkRelayUI = void 0;\nconst cssReset_1 = require(\"../../../lib/cssReset\");\nconst LinkFlow_1 = require(\"./components/LinkFlow/LinkFlow\");\nconst Snackbar_1 = require(\"./components/Snackbar/Snackbar\");\nclass WalletLinkRelayUI {\n constructor(options) {\n this.standalone = null;\n this.attached = false;\n this.snackbar = new Snackbar_1.Snackbar({\n darkMode: options.darkMode,\n });\n this.linkFlow = new LinkFlow_1.LinkFlow({\n darkMode: options.darkMode,\n version: options.version,\n sessionId: options.session.id,\n sessionSecret: options.session.secret,\n linkAPIUrl: options.linkAPIUrl,\n isParentConnection: false,\n });\n }\n attach() {\n if (this.attached) {\n throw new Error('Coinbase Wallet SDK UI is already attached');\n }\n const el = document.documentElement;\n const container = document.createElement('div');\n container.className = '-cbwsdk-css-reset';\n el.appendChild(container);\n this.linkFlow.attach(container);\n this.snackbar.attach(container);\n this.attached = true;\n (0, cssReset_1.injectCssReset)();\n }\n setConnected(connected) {\n this.linkFlow.setConnected(connected);\n }\n setChainId(chainId) {\n this.linkFlow.setChainId(chainId);\n }\n setConnectDisabled(connectDisabled) {\n this.linkFlow.setConnectDisabled(connectDisabled);\n }\n /* istanbul ignore next */\n addEthereumChain() { } // no-op\n /* istanbul ignore next */\n watchAsset() { } // no-op\n /* istanbul ignore next */\n switchEthereumChain() { } // no-op\n requestEthereumAccounts(options) {\n this.linkFlow.open({ onCancel: options.onCancel });\n }\n hideRequestEthereumAccounts() {\n this.linkFlow.close();\n }\n /* istanbul ignore next */\n signEthereumMessage() { } // no-op\n /* istanbul ignore next */\n signEthereumTransaction() { } // no-op\n /* istanbul ignore next */\n submitEthereumTransaction() { } // no-op\n /* istanbul ignore next */\n ethereumAddressFromSignedMessage() { } // no-op\n showConnecting(options) {\n let snackbarProps;\n if (options.isUnlinkedErrorState) {\n snackbarProps = {\n autoExpand: true,\n message: 'Connection lost',\n menuItems: [\n {\n isRed: false,\n info: 'Reset connection',\n svgWidth: '10',\n svgHeight: '11',\n path: 'M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z',\n defaultFillRule: 'evenodd',\n defaultClipRule: 'evenodd',\n onClick: options.onResetConnection,\n },\n ],\n };\n }\n else {\n snackbarProps = {\n message: 'Confirm on phone',\n menuItems: [\n {\n isRed: true,\n info: 'Cancel transaction',\n svgWidth: '11',\n svgHeight: '11',\n path: 'M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z',\n defaultFillRule: 'inherit',\n defaultClipRule: 'inherit',\n onClick: options.onCancel,\n },\n {\n isRed: false,\n info: 'Reset connection',\n svgWidth: '10',\n svgHeight: '11',\n path: 'M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z',\n defaultFillRule: 'evenodd',\n defaultClipRule: 'evenodd',\n onClick: options.onResetConnection,\n },\n ],\n };\n }\n return this.snackbar.presentItem(snackbarProps);\n }\n /* istanbul ignore next */\n reloadUI() {\n document.location.reload();\n }\n /* istanbul ignore next */\n inlineAccountsResponse() {\n return false;\n }\n /* istanbul ignore next */\n inlineAddEthereumChain() {\n return false;\n }\n /* istanbul ignore next */\n inlineWatchAsset() {\n return false;\n }\n /* istanbul ignore next */\n inlineSwitchEthereumChain() {\n return false;\n }\n /* istanbul ignore next */\n setStandalone(status) {\n this.standalone = status;\n }\n /* istanbul ignore next */\n isStandalone() {\n var _a;\n return (_a = this.standalone) !== null && _a !== void 0 ? _a : false;\n }\n}\nexports.WalletLinkRelayUI = WalletLinkRelayUI;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-cbwsdk-connect-content{height:430px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-connect-content.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-header{display:flex;align-items:center;justify-content:space-between;margin:0 0 30px}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading{font-style:normal;font-weight:500;font-size:28px;line-height:36px;margin:0}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-layout{display:flex;flex-direction:row}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-left{margin-right:30px;display:flex;flex-direction:column;justify-content:space-between}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-right{flex:25%;margin-right:34px}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-wrapper{width:220px;height:220px;border-radius:12px;display:flex;justify-content:center;align-items:center;background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting{position:absolute;top:0;bottom:0;left:0;right:0;display:flex;flex-direction:column;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light{background-color:rgba(255,255,255,.95)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light>p{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark{background-color:rgba(10,11,13,.9)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark>p{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting>p{font-size:12px;font-weight:bold;margin-top:16px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app{border-radius:8px;font-size:14px;line-height:20px;padding:12px;width:339px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.light{background:#eef0f3;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.dark{background:#1e2025;color:#8a919e}.-cbwsdk-css-reset .-cbwsdk-cancel-button{-webkit-appearance:none;border:none;background:none;cursor:pointer;padding:0;margin:0}.-cbwsdk-css-reset .-cbwsdk-cancel-button-x{position:relative;display:block;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-wallet-steps{padding:0 0 0 16px;margin:0;width:100%;list-style:decimal}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item{list-style-type:decimal;display:list-item;font-style:normal;font-weight:400;font-size:16px;line-height:24px;margin-top:20px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item-wrapper{display:flex;align-items:center}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-pad-left{margin-left:6px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon{display:flex;border-radius:50%;height:24px;width:24px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.light{background:#0052ff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.dark{background:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item{align-items:center;display:flex;flex-direction:row;padding:16px 24px;gap:12px;cursor:pointer;border-radius:100px;font-weight:600}.-cbwsdk-css-reset .-cbwsdk-connect-item.light{background:#f5f8ff;color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-connect-item.dark{background:#001033;color:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item-copy-wrapper{margin:0 4px 0 8px}.-cbwsdk-css-reset .-cbwsdk-connect-item-title{margin:0 0 0;font-size:16px;line-height:24px;font-weight:500}.-cbwsdk-css-reset .-cbwsdk-connect-item-description{font-weight:400;font-size:14px;line-height:20px;margin:0}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CoinbaseWalletSteps = exports.ConnectContent = void 0;\nconst clsx_1 = __importDefault(require(\"clsx\"));\nconst preact_1 = require(\"preact\");\nconst util_1 = require(\"../../../../../core/util\");\nconst version_1 = require(\"../../../../../version\");\nconst CloseIcon_1 = require(\"../icons/CloseIcon\");\nconst CoinbaseWalletRound_1 = require(\"../icons/CoinbaseWalletRound\");\nconst QRCodeIcon_1 = require(\"../icons/QRCodeIcon\");\nconst QRCode_1 = require(\"../QRCode\");\nconst Spinner_1 = require(\"../Spinner/Spinner\");\nconst ConnectContent_css_1 = __importDefault(require(\"./ConnectContent-css\"));\nconst wallet = {\n title: 'Coinbase Wallet app',\n description: 'Connect with your self-custody wallet',\n steps: CoinbaseWalletSteps,\n};\nconst makeIconColor = (theme) => {\n return theme === 'light' ? '#FFFFFF' : '#0A0B0D';\n};\nfunction ConnectContent(props) {\n const { theme } = props;\n const qrUrl = (0, util_1.createQrUrl)(props.sessionId, props.sessionSecret, props.linkAPIUrl, props.isParentConnection, props.version, props.chainId);\n const WalletSteps = wallet.steps;\n return ((0, preact_1.h)(\"div\", { \"data-testid\": \"connect-content\", className: (0, clsx_1.default)('-cbwsdk-connect-content', theme) },\n (0, preact_1.h)(\"style\", null, ConnectContent_css_1.default),\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-content-header\" },\n (0, preact_1.h)(\"h2\", { className: (0, clsx_1.default)('-cbwsdk-connect-content-heading', theme) }, \"Scan to connect with our mobile app\"),\n props.onCancel && ((0, preact_1.h)(\"button\", { type: \"button\", className: '-cbwsdk-cancel-button', onClick: props.onCancel },\n (0, preact_1.h)(CloseIcon_1.CloseIcon, { fill: theme === 'light' ? '#0A0B0D' : '#FFFFFF' })))),\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-content-layout\" },\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-content-column-left\" },\n (0, preact_1.h)(ConnectItem, { title: wallet.title, description: wallet.description, theme: theme })),\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-content-column-right\" },\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-content-qr-wrapper\" },\n (0, preact_1.h)(QRCode_1.QRCode, { content: qrUrl, width: 200, height: 200, fgColor: \"#000\", bgColor: \"transparent\" }),\n (0, preact_1.h)(\"input\", { type: \"hidden\", name: \"cbw-cbwsdk-version\", value: version_1.LIB_VERSION }),\n (0, preact_1.h)(\"input\", { type: \"hidden\", value: qrUrl })),\n (0, preact_1.h)(WalletSteps, { theme: theme }),\n !props.isConnected && ((0, preact_1.h)(\"div\", { \"data-testid\": \"connecting-spinner\", className: (0, clsx_1.default)('-cbwsdk-connect-content-qr-connecting', theme) },\n (0, preact_1.h)(Spinner_1.Spinner, { size: 36, color: theme === 'dark' ? '#FFF' : '#000' }),\n (0, preact_1.h)(\"p\", null, \"Connecting...\")))))));\n}\nexports.ConnectContent = ConnectContent;\nfunction ConnectItem({ title, description, theme }) {\n return ((0, preact_1.h)(\"div\", { className: (0, clsx_1.default)('-cbwsdk-connect-item', theme) },\n (0, preact_1.h)(\"div\", null,\n (0, preact_1.h)(CoinbaseWalletRound_1.CoinbaseWalletRound, null)),\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-connect-item-copy-wrapper\" },\n (0, preact_1.h)(\"h3\", { className: \"-cbwsdk-connect-item-title\" }, title),\n (0, preact_1.h)(\"p\", { className: \"-cbwsdk-connect-item-description\" }, description))));\n}\nfunction CoinbaseWalletSteps({ theme }) {\n return ((0, preact_1.h)(\"ol\", { className: \"-cbwsdk-wallet-steps\" },\n (0, preact_1.h)(\"li\", { className: (0, clsx_1.default)('-cbwsdk-wallet-steps-item', theme) },\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-wallet-steps-item-wrapper\" }, \"Open Coinbase Wallet app\")),\n (0, preact_1.h)(\"li\", { className: (0, clsx_1.default)('-cbwsdk-wallet-steps-item', theme) },\n (0, preact_1.h)(\"div\", { className: \"-cbwsdk-wallet-steps-item-wrapper\" },\n (0, preact_1.h)(\"span\", null,\n \"Tap \",\n (0, preact_1.h)(\"strong\", null, \"Scan\"),\n ' '),\n (0, preact_1.h)(\"span\", { className: (0, clsx_1.default)('-cbwsdk-wallet-steps-pad-left', '-cbwsdk-wallet-steps-icon', theme) },\n (0, preact_1.h)(QRCodeIcon_1.QRCodeIcon, { fill: makeIconColor(theme) }))))));\n}\nexports.CoinbaseWalletSteps = CoinbaseWalletSteps;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-cbwsdk-connect-dialog{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.light{background-color:rgba(0,0,0,.5)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.dark{background-color:rgba(50,53,61,.4)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box{display:flex;position:relative;flex-direction:column;transform:scale(1);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box-hidden{opacity:0;transform:scale(0.85)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container{display:block}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container-hidden{display:none}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConnectDialog = void 0;\nconst clsx_1 = __importDefault(require(\"clsx\"));\nconst preact_1 = require(\"preact\");\nconst hooks_1 = require(\"preact/hooks\");\nconst ConnectContent_1 = require(\"../ConnectContent/ConnectContent\");\nconst TryExtensionContent_1 = require(\"../TryExtensionContent/TryExtensionContent\");\nconst ConnectDialog_css_1 = __importDefault(require(\"./ConnectDialog-css\"));\nconst ConnectDialog = (props) => {\n const { isOpen, darkMode } = props;\n const [containerHidden, setContainerHidden] = (0, hooks_1.useState)(!isOpen);\n const [dialogHidden, setDialogHidden] = (0, hooks_1.useState)(!isOpen);\n (0, hooks_1.useEffect)(() => {\n const timers = [\n window.setTimeout(() => {\n setDialogHidden(!isOpen);\n }, 10),\n ];\n if (isOpen) {\n setContainerHidden(false);\n }\n else {\n timers.push(window.setTimeout(() => {\n setContainerHidden(true);\n }, 360));\n }\n return () => {\n timers.forEach(window.clearTimeout);\n };\n }, [isOpen]);\n const theme = darkMode ? 'dark' : 'light';\n return ((0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-connect-dialog-container', containerHidden && '-cbwsdk-connect-dialog-container-hidden') },\n (0, preact_1.h)(\"style\", null, ConnectDialog_css_1.default),\n (0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-connect-dialog-backdrop', theme, dialogHidden && '-cbwsdk-connect-dialog-backdrop-hidden') }),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-connect-dialog\" },\n (0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-connect-dialog-box', dialogHidden && '-cbwsdk-connect-dialog-box-hidden') },\n !props.connectDisabled ? ((0, preact_1.h)(ConnectContent_1.ConnectContent, { theme: theme, version: props.version, sessionId: props.sessionId, sessionSecret: props.sessionSecret, linkAPIUrl: props.linkAPIUrl, isConnected: props.isConnected, isParentConnection: props.isParentConnection, chainId: props.chainId, onCancel: props.onCancel })) : null,\n (0, preact_1.h)(TryExtensionContent_1.TryExtensionContent, { theme: theme })))));\n};\nexports.ConnectDialog = ConnectDialog;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LinkFlow = void 0;\nconst preact_1 = require(\"preact\");\nconst ConnectDialog_1 = require(\"../ConnectDialog/ConnectDialog\");\nclass LinkFlow {\n constructor(options) {\n this.connected = false;\n this.chainId = 1;\n this.isOpen = false;\n this.onCancel = null;\n this.root = null;\n // if true, hide QR code in LinkFlow (which happens if no jsonRpcUrl is provided)\n this.connectDisabled = false;\n this.darkMode = options.darkMode;\n this.version = options.version;\n this.sessionId = options.sessionId;\n this.sessionSecret = options.sessionSecret;\n this.linkAPIUrl = options.linkAPIUrl;\n this.isParentConnection = options.isParentConnection;\n }\n attach(el) {\n this.root = document.createElement('div');\n this.root.className = '-cbwsdk-link-flow-root';\n el.appendChild(this.root);\n this.render();\n }\n setConnected(v) {\n if (this.connected !== v) {\n this.connected = v;\n this.render();\n }\n }\n setChainId(chainId) {\n if (this.chainId !== chainId) {\n this.chainId = chainId;\n this.render();\n }\n }\n detach() {\n var _a;\n if (!this.root) {\n return;\n }\n (0, preact_1.render)(null, this.root);\n (_a = this.root.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(this.root);\n }\n setConnectDisabled(connectDisabled) {\n this.connectDisabled = connectDisabled;\n }\n open(options) {\n this.isOpen = true;\n this.onCancel = options.onCancel;\n this.render();\n }\n close() {\n this.isOpen = false;\n this.onCancel = null;\n this.render();\n }\n render() {\n if (!this.root) {\n return;\n }\n (0, preact_1.render)((0, preact_1.h)(ConnectDialog_1.ConnectDialog, { darkMode: this.darkMode, version: this.version, sessionId: this.sessionId, sessionSecret: this.sessionSecret, linkAPIUrl: this.linkAPIUrl, isOpen: this.isOpen, isConnected: this.connected, isParentConnection: this.isParentConnection, chainId: this.chainId, onCancel: this.onCancel, connectDisabled: this.connectDisabled }), this.root);\n }\n}\nexports.LinkFlow = LinkFlow;\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.QRCode = void 0;\nconst preact_1 = require(\"preact\");\nconst hooks_1 = require(\"preact/hooks\");\nconst qrcode_svg_1 = __importDefault(require(\"../../../../vendor-js/qrcode-svg\"));\nconst QRCode = (props) => {\n const [svg, setSvg] = (0, hooks_1.useState)('');\n (0, hooks_1.useEffect)(() => {\n var _a, _b;\n const qrcode = new qrcode_svg_1.default({\n content: props.content,\n background: props.bgColor || '#ffffff',\n color: props.fgColor || '#000000',\n container: 'svg',\n ecl: 'M',\n width: (_a = props.width) !== null && _a !== void 0 ? _a : 256,\n height: (_b = props.height) !== null && _b !== void 0 ? _b : 256,\n padding: 0,\n image: props.image,\n });\n const base64 = Buffer.from(qrcode.svg(), 'utf8').toString('base64');\n setSvg(`data:image/svg+xml;base64,${base64}`);\n }, [props.bgColor, props.content, props.fgColor, props.height, props.image, props.width]);\n return svg ? (0, preact_1.h)(\"img\", { src: svg, alt: \"QR Code\" }) : null;\n};\nexports.QRCode = QRCode;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}`)();\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RedirectDialog = void 0;\nconst clsx_1 = __importDefault(require(\"clsx\"));\nconst preact_1 = require(\"preact\");\nconst cssReset_1 = require(\"../../../../../lib/cssReset\");\nconst Snackbar_1 = require(\"../Snackbar\");\nconst RedirectDialog_css_1 = __importDefault(require(\"./RedirectDialog-css\"));\nclass RedirectDialog {\n constructor() {\n this.root = null;\n }\n attach() {\n const el = document.documentElement;\n this.root = document.createElement('div');\n this.root.className = '-cbwsdk-css-reset';\n el.appendChild(this.root);\n (0, cssReset_1.injectCssReset)();\n }\n present(props) {\n this.render(props);\n }\n clear() {\n this.render(null);\n }\n render(props) {\n if (!this.root)\n return;\n (0, preact_1.render)(null, this.root);\n if (!props)\n return;\n (0, preact_1.render)((0, preact_1.h)(RedirectDialogContent, Object.assign({}, props, { onDismiss: () => {\n this.clear();\n } })), this.root);\n }\n}\nexports.RedirectDialog = RedirectDialog;\nconst RedirectDialogContent = ({ title, buttonText, darkMode, onButtonClick, onDismiss }) => {\n const theme = darkMode ? 'dark' : 'light';\n return ((0, preact_1.h)(Snackbar_1.SnackbarContainer, { darkMode: darkMode },\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-redirect-dialog\" },\n (0, preact_1.h)(\"style\", null, RedirectDialog_css_1.default),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-redirect-dialog-backdrop\", onClick: onDismiss }),\n (0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-redirect-dialog-box', theme) },\n (0, preact_1.h)(\"p\", null, title),\n (0, preact_1.h)(\"button\", { onClick: onButtonClick }, buttonText)))));\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SnackbarInstance = exports.SnackbarContainer = exports.Snackbar = void 0;\nconst clsx_1 = __importDefault(require(\"clsx\"));\nconst preact_1 = require(\"preact\");\nconst hooks_1 = require(\"preact/hooks\");\nconst Snackbar_css_1 = __importDefault(require(\"./Snackbar-css\"));\nconst cblogo = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+`;\nconst gearIcon = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=`;\nclass Snackbar {\n constructor(options) {\n this.items = new Map();\n this.nextItemKey = 0;\n this.root = null;\n this.darkMode = options.darkMode;\n }\n attach(el) {\n this.root = document.createElement('div');\n this.root.className = '-cbwsdk-snackbar-root';\n el.appendChild(this.root);\n this.render();\n }\n presentItem(itemProps) {\n const key = this.nextItemKey++;\n this.items.set(key, itemProps);\n this.render();\n return () => {\n this.items.delete(key);\n this.render();\n };\n }\n clear() {\n this.items.clear();\n this.render();\n }\n render() {\n if (!this.root) {\n return;\n }\n (0, preact_1.render)((0, preact_1.h)(\"div\", null,\n (0, preact_1.h)(exports.SnackbarContainer, { darkMode: this.darkMode }, Array.from(this.items.entries()).map(([key, itemProps]) => ((0, preact_1.h)(exports.SnackbarInstance, Object.assign({}, itemProps, { key: key })))))), this.root);\n }\n}\nexports.Snackbar = Snackbar;\nconst SnackbarContainer = (props) => ((0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-snackbar-container') },\n (0, preact_1.h)(\"style\", null, Snackbar_css_1.default),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-snackbar\" }, props.children)));\nexports.SnackbarContainer = SnackbarContainer;\nconst SnackbarInstance = ({ autoExpand, message, menuItems, }) => {\n const [hidden, setHidden] = (0, hooks_1.useState)(true);\n const [expanded, setExpanded] = (0, hooks_1.useState)(autoExpand !== null && autoExpand !== void 0 ? autoExpand : false);\n (0, hooks_1.useEffect)(() => {\n const timers = [\n window.setTimeout(() => {\n setHidden(false);\n }, 1),\n window.setTimeout(() => {\n setExpanded(true);\n }, 10000),\n ];\n return () => {\n timers.forEach(window.clearTimeout);\n };\n });\n const toggleExpanded = () => {\n setExpanded(!expanded);\n };\n return ((0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-snackbar-instance', hidden && '-cbwsdk-snackbar-instance-hidden', expanded && '-cbwsdk-snackbar-instance-expanded') },\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-snackbar-instance-header\", onClick: toggleExpanded },\n (0, preact_1.h)(\"img\", { src: cblogo, class: \"-cbwsdk-snackbar-instance-header-cblogo\" }),\n ' ',\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-snackbar-instance-header-message\" }, message),\n (0, preact_1.h)(\"div\", { class: \"-gear-container\" },\n !expanded && ((0, preact_1.h)(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n (0, preact_1.h)(\"circle\", { cx: \"12\", cy: \"12\", r: \"12\", fill: \"#F5F7F8\" }))),\n (0, preact_1.h)(\"img\", { src: gearIcon, class: \"-gear-icon\", title: \"Expand\" }))),\n menuItems && menuItems.length > 0 && ((0, preact_1.h)(\"div\", { class: \"-cbwsdk-snackbar-instance-menu\" }, menuItems.map((action, i) => ((0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-snackbar-instance-menu-item', action.isRed && '-cbwsdk-snackbar-instance-menu-item-is-red'), onClick: action.onClick, key: i },\n (0, preact_1.h)(\"svg\", { width: action.svgWidth, height: action.svgHeight, viewBox: \"0 0 10 11\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n (0, preact_1.h)(\"path\", { \"fill-rule\": action.defaultFillRule, \"clip-rule\": action.defaultClipRule, d: action.path, fill: \"#AAAAAA\" })),\n (0, preact_1.h)(\"span\", { class: (0, clsx_1.default)('-cbwsdk-snackbar-instance-menu-item-info', action.isRed && '-cbwsdk-snackbar-instance-menu-item-info-is-red') }, action.info))))))));\n};\nexports.SnackbarInstance = SnackbarInstance;\n","\"use strict\";\nvar __createBinding = (this && this.__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}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./Snackbar\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-cbwsdk-spinner{display:inline-block}.-cbwsdk-css-reset .-cbwsdk-spinner svg{display:inline-block;animation:2s linear infinite -cbwsdk-spinner-svg}.-cbwsdk-css-reset .-cbwsdk-spinner svg circle{animation:1.9s ease-in-out infinite both -cbwsdk-spinner-circle;display:block;fill:rgba(0,0,0,0);stroke-dasharray:283;stroke-dashoffset:280;stroke-linecap:round;stroke-width:10px;transform-origin:50% 50%}@keyframes -cbwsdk-spinner-svg{0%{transform:rotateZ(0deg)}100%{transform:rotateZ(360deg)}}@keyframes -cbwsdk-spinner-circle{0%,25%{stroke-dashoffset:280;transform:rotate(0)}50%,75%{stroke-dashoffset:75;transform:rotate(45deg)}100%{stroke-dashoffset:280;transform:rotate(360deg)}}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Spinner = void 0;\nconst preact_1 = require(\"preact\");\nconst Spinner_css_1 = __importDefault(require(\"./Spinner-css\"));\nconst Spinner = (props) => {\n var _a;\n const size = (_a = props.size) !== null && _a !== void 0 ? _a : 64;\n const color = props.color || '#000';\n return ((0, preact_1.h)(\"div\", { class: \"-cbwsdk-spinner\" },\n (0, preact_1.h)(\"style\", null, Spinner_css_1.default),\n (0, preact_1.h)(\"svg\", { viewBox: \"0 0 100 100\", xmlns: \"http://www.w3.org/2000/svg\", style: { width: size, height: size } },\n (0, preact_1.h)(\"circle\", { style: { cx: 50, cy: 50, r: 45, stroke: color } }))));\n};\nexports.Spinner = Spinner;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = (() => `.-cbwsdk-css-reset .-cbwsdk-try-extension{display:flex;margin-top:12px;height:202px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-try-extension.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-column-half{flex:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading{font-style:normal;font-weight:500;font-size:25px;line-height:32px;margin:0;max-width:204px}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta{appearance:none;border:none;background:none;color:#0052ff;cursor:pointer;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.light{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.dark{color:#588af5}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-wrapper{display:flex;align-items:center;margin-top:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-icon{display:block;margin-left:4px;height:14px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list{display:flex;flex-direction:column;justify-content:center;align-items:center;margin:0;padding:0;list-style:none;height:100%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item{display:flex;align-items:center;flex-flow:nowrap;margin-top:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item:first-of-type{margin-top:0}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon-wrapper{display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon{display:flex;height:32px;width:32px;border-radius:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.light{background:#eef0f3}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.dark{background:#1e2025}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy{display:block;font-weight:400;font-size:14px;line-height:20px;padding-left:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.light{color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.dark{color:#8a919e}`)();\n","\"use strict\";\n// Copyright (c) 2018-2023 Coinbase, Inc. \n// Licensed under the Apache License, version 2.0\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TryExtensionContent = void 0;\nconst clsx_1 = __importDefault(require(\"clsx\"));\nconst preact_1 = require(\"preact\");\nconst hooks_1 = require(\"preact/hooks\");\nconst ArrowLeftIcon_1 = require(\"../icons/ArrowLeftIcon\");\nconst LaptopIcon_1 = require(\"../icons/LaptopIcon\");\nconst SafeIcon_1 = require(\"../icons/SafeIcon\");\nconst TryExtensionContent_css_1 = __importDefault(require(\"./TryExtensionContent-css\"));\nfunction TryExtensionContent({ theme }) {\n const [clicked, setClicked] = (0, hooks_1.useState)(false);\n const handleInstallClick = (0, hooks_1.useCallback)(() => {\n window.open('https://api.wallet.coinbase.com/rpc/v2/desktop/chrome', '_blank');\n }, []);\n const handleClick = (0, hooks_1.useCallback)(() => {\n if (clicked) {\n window.location.reload();\n }\n else {\n handleInstallClick();\n setClicked(true);\n }\n }, [handleInstallClick, clicked]);\n return ((0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-try-extension', theme) },\n (0, preact_1.h)(\"style\", null, TryExtensionContent_css_1.default),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-try-extension-column-half\" },\n (0, preact_1.h)(\"h3\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-heading', theme) }, \"Or try the Coinbase Wallet browser extension\"),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-try-extension-cta-wrapper\" },\n (0, preact_1.h)(\"button\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-cta', theme), onClick: handleClick }, clicked ? 'Refresh' : 'Install'),\n (0, preact_1.h)(\"div\", null, !clicked && ((0, preact_1.h)(ArrowLeftIcon_1.ArrowLeftIcon, { class: \"-cbwsdk-try-extension-cta-icon\", fill: theme === 'light' ? '#0052FF' : '#588AF5' }))))),\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-try-extension-column-half\" },\n (0, preact_1.h)(\"ul\", { class: \"-cbwsdk-try-extension-list\" },\n (0, preact_1.h)(\"li\", { class: \"-cbwsdk-try-extension-list-item\" },\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-try-extension-list-item-icon-wrapper\" },\n (0, preact_1.h)(\"span\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-list-item-icon', theme) },\n (0, preact_1.h)(LaptopIcon_1.LaptopIcon, { fill: theme === 'light' ? '#0A0B0D' : '#FFFFFF' }))),\n (0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-list-item-copy', theme) }, \"Connect with dapps with just one click on your desktop browser\")),\n (0, preact_1.h)(\"li\", { class: \"-cbwsdk-try-extension-list-item\" },\n (0, preact_1.h)(\"div\", { class: \"-cbwsdk-try-extension-list-item-icon-wrapper\" },\n (0, preact_1.h)(\"span\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-list-item-icon', theme) },\n (0, preact_1.h)(SafeIcon_1.SafeIcon, { fill: theme === 'light' ? '#0A0B0D' : '#FFFFFF' }))),\n (0, preact_1.h)(\"div\", { class: (0, clsx_1.default)('-cbwsdk-try-extension-list-item-copy', theme) }, \"Add an additional layer of security by using a supported Ledger hardware wallet\"))))));\n}\nexports.TryExtensionContent = TryExtensionContent;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ArrowLeftIcon = void 0;\nconst preact_1 = require(\"preact\");\nfunction ArrowLeftIcon(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"16\", height: \"16\", viewBox: \"0 0 16 16\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"path\", { d: \"M8.60675 0.155884L7.37816 1.28209L12.7723 7.16662H0V8.83328H12.6548L6.82149 14.6666L8 15.8451L15.8201 8.02501L8.60675 0.155884Z\" })));\n}\nexports.ArrowLeftIcon = ArrowLeftIcon;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CloseIcon = void 0;\nconst preact_1 = require(\"preact\");\nfunction CloseIcon(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"40\", height: \"40\", viewBox: \"0 0 40 40\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"path\", { d: \"M13.7677 13L12.3535 14.4142L18.3535 20.4142L12.3535 26.4142L13.7677 27.8284L19.7677 21.8284L25.7677 27.8284L27.1819 26.4142L21.1819 20.4142L27.1819 14.4142L25.7677 13L19.7677 19L13.7677 13Z\" })));\n}\nexports.CloseIcon = CloseIcon;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CoinbaseWalletRound = void 0;\nconst preact_1 = require(\"preact\");\nfunction CoinbaseWalletRound(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"28\", height: \"28\", viewBox: \"0 0 28 28\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"circle\", { cx: \"14\", cy: \"14\", r: \"14\", fill: \"#0052FF\" }),\n (0, preact_1.h)(\"path\", { d: \"M23.8521 14.0003C23.8521 19.455 19.455 23.8521 14.0003 23.8521C8.54559 23.8521 4.14844 19.455 4.14844 14.0003C4.14844 8.54559 8.54559 4.14844 14.0003 4.14844C19.455 4.14844 23.8521 8.54559 23.8521 14.0003Z\", fill: \"white\" }),\n (0, preact_1.h)(\"path\", { d: \"M11.1855 12.5042C11.1855 12.0477 11.1855 11.7942 11.2835 11.642C11.3814 11.4899 11.4793 11.3377 11.6261 11.287C11.8219 11.1855 12.0178 11.1855 12.5073 11.1855H15.4934C15.983 11.1855 16.1788 11.1855 16.3746 11.287C16.5215 11.3884 16.6683 11.4899 16.7173 11.642C16.8152 11.8449 16.8152 12.0477 16.8152 12.5042V15.4965C16.8152 15.953 16.8152 16.2066 16.7173 16.3587C16.6194 16.5109 16.5215 16.663 16.3746 16.7137C16.1788 16.8152 15.983 16.8152 15.4934 16.8152H12.5073C12.0178 16.8152 11.8219 16.8152 11.6261 16.7137C11.4793 16.6123 11.3324 16.5109 11.2835 16.3587C11.1855 16.1558 11.1855 15.953 11.1855 15.4965V12.5042Z\", fill: \"#0052FF\" })));\n}\nexports.CoinbaseWalletRound = CoinbaseWalletRound;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LaptopIcon = void 0;\nconst preact_1 = require(\"preact\");\nfunction LaptopIcon(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"14\", height: \"14\", viewBox: \"0 0 14 14\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"path\", { d: \"M1.8001 2.2002H12.2001V9.40019H1.8001V2.2002ZM3.4001 3.8002V7.80019H10.6001V3.8002H3.4001Z\" }),\n (0, preact_1.h)(\"path\", { d: \"M13.4001 10.2002H0.600098C0.600098 11.0838 1.31644 11.8002 2.2001 11.8002H11.8001C12.6838 11.8002 13.4001 11.0838 13.4001 10.2002Z\" })));\n}\nexports.LaptopIcon = LaptopIcon;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.QRCodeIcon = void 0;\nconst preact_1 = require(\"preact\");\nfunction QRCodeIcon(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"18\", height: \"18\", viewBox: \"0 0 24 24\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"path\", { d: \"M3 3V8.99939L5 8.99996V5H9V3H3Z\" }),\n (0, preact_1.h)(\"path\", { d: \"M15 21L21 21V15.0006L19 15V19L15 19V21Z\" }),\n (0, preact_1.h)(\"path\", { d: \"M21 9H19V5H15.0006L15 3H21V9Z\" }),\n (0, preact_1.h)(\"path\", { d: \"M3 15V21H8.99939L8.99996 19H5L5 15H3Z\" })));\n}\nexports.QRCodeIcon = QRCodeIcon;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SafeIcon = void 0;\nconst preact_1 = require(\"preact\");\nfunction SafeIcon(props) {\n return ((0, preact_1.h)(\"svg\", Object.assign({ width: \"14\", height: \"14\", viewBox: \"0 0 14 14\", xmlns: \"http://www.w3.org/2000/svg\" }, props),\n (0, preact_1.h)(\"path\", { \"fill-rule\": \"evenodd\", \"clip-rule\": \"evenodd\", d: \"M0.600098 0.600098V11.8001H13.4001V0.600098H0.600098ZM7.0001 9.2001C5.3441 9.2001 4.0001 7.8561 4.0001 6.2001C4.0001 4.5441 5.3441 3.2001 7.0001 3.2001C8.6561 3.2001 10.0001 4.5441 10.0001 6.2001C10.0001 7.8561 8.6561 9.2001 7.0001 9.2001ZM0.600098 12.6001H3.8001V13.4001H0.600098V12.6001ZM10.2001 12.6001H13.4001V13.4001H10.2001V12.6001ZM8.8001 6.2001C8.8001 7.19421 7.99421 8.0001 7.0001 8.0001C6.00598 8.0001 5.2001 7.19421 5.2001 6.2001C5.2001 5.20598 6.00598 4.4001 7.0001 4.4001C7.99421 4.4001 8.8001 5.20598 8.8001 6.2001Z\" })));\n}\nexports.SafeIcon = SafeIcon;\n","// Extracted from https://github.com/ethereumjs/ethereumjs-abi and stripped out irrelevant code\n// Original code licensed under the MIT License - Copyright (c) 2015 Alex Beregszaszi\n\nconst util = require('./util')\nconst BN = require('bn.js')\n\n// Convert from short to canonical names\n// FIXME: optimise or make this nicer?\nfunction elementaryName (name) {\n if (name.startsWith('int[')) {\n return 'int256' + name.slice(3)\n } else if (name === 'int') {\n return 'int256'\n } else if (name.startsWith('uint[')) {\n return 'uint256' + name.slice(4)\n } else if (name === 'uint') {\n return 'uint256'\n } else if (name.startsWith('fixed[')) {\n return 'fixed128x128' + name.slice(5)\n } else if (name === 'fixed') {\n return 'fixed128x128'\n } else if (name.startsWith('ufixed[')) {\n return 'ufixed128x128' + name.slice(6)\n } else if (name === 'ufixed') {\n return 'ufixed128x128'\n }\n return name\n}\n\n// Parse N from type\nfunction parseTypeN (type) {\n return parseInt(/^\\D+(\\d+)$/.exec(type)[1], 10)\n}\n\n// Parse N,M from typex\nfunction parseTypeNxM (type) {\n var tmp = /^\\D+(\\d+)x(\\d+)$/.exec(type)\n return [ parseInt(tmp[1], 10), parseInt(tmp[2], 10) ]\n}\n\n// Parse N in type[] where \"type\" can itself be an array type.\nfunction parseTypeArray (type) {\n var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n if (tmp) {\n return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n }\n return null\n}\n\nfunction parseNumber (arg) {\n var type = typeof arg\n if (type === 'string') {\n if (util.isHexString(arg)) {\n return new BN(util.stripHexPrefix(arg), 16)\n } else {\n return new BN(arg, 10)\n }\n } else if (type === 'number') {\n return new BN(arg)\n } else if (arg.toArray) {\n // assume this is a BN for the moment, replace with BN.isBN soon\n return arg\n } else {\n throw new Error('Argument is not a number')\n }\n}\n\n// Encodes a single item (can be dynamic array)\n// @returns: Buffer\nfunction encodeSingle (type, arg) {\n var size, num, ret, i\n\n if (type === 'address') {\n return encodeSingle('uint160', parseNumber(arg))\n } else if (type === 'bool') {\n return encodeSingle('uint8', arg ? 1 : 0)\n } else if (type === 'string') {\n return encodeSingle('bytes', new Buffer(arg, 'utf8'))\n } else if (isArray(type)) {\n // this part handles fixed-length ([2]) and variable length ([]) arrays\n // NOTE: we catch here all calls to arrays, that simplifies the rest\n if (typeof arg.length === 'undefined') {\n throw new Error('Not an array?')\n }\n size = parseTypeArray(type)\n if (size !== 'dynamic' && size !== 0 && arg.length > size) {\n throw new Error('Elements exceed array size: ' + size)\n }\n ret = []\n type = type.slice(0, type.lastIndexOf('['))\n if (typeof arg === 'string') {\n arg = JSON.parse(arg)\n }\n for (i in arg) {\n ret.push(encodeSingle(type, arg[i]))\n }\n if (size === 'dynamic') {\n var length = encodeSingle('uint256', arg.length)\n ret.unshift(length)\n }\n return Buffer.concat(ret)\n } else if (type === 'bytes') {\n arg = new Buffer(arg)\n\n ret = Buffer.concat([ encodeSingle('uint256', arg.length), arg ])\n\n if ((arg.length % 32) !== 0) {\n ret = Buffer.concat([ ret, util.zeros(32 - (arg.length % 32)) ])\n }\n\n return ret\n } else if (type.startsWith('bytes')) {\n size = parseTypeN(type)\n if (size < 1 || size > 32) {\n throw new Error('Invalid bytes width: ' + size)\n }\n\n return util.setLengthRight(arg, 32)\n } else if (type.startsWith('uint')) {\n size = parseTypeN(type)\n if ((size % 8) || (size < 8) || (size > 256)) {\n throw new Error('Invalid uint width: ' + size)\n }\n\n num = parseNumber(arg)\n if (num.bitLength() > size) {\n throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength())\n }\n\n if (num < 0) {\n throw new Error('Supplied uint is negative')\n }\n\n return num.toArrayLike(Buffer, 'be', 32)\n } else if (type.startsWith('int')) {\n size = parseTypeN(type)\n if ((size % 8) || (size < 8) || (size > 256)) {\n throw new Error('Invalid int width: ' + size)\n }\n\n num = parseNumber(arg)\n if (num.bitLength() > size) {\n throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength())\n }\n\n return num.toTwos(256).toArrayLike(Buffer, 'be', 32)\n } else if (type.startsWith('ufixed')) {\n size = parseTypeNxM(type)\n\n num = parseNumber(arg)\n\n if (num < 0) {\n throw new Error('Supplied ufixed is negative')\n }\n\n return encodeSingle('uint256', num.mul(new BN(2).pow(new BN(size[1]))))\n } else if (type.startsWith('fixed')) {\n size = parseTypeNxM(type)\n\n return encodeSingle('int256', parseNumber(arg).mul(new BN(2).pow(new BN(size[1]))))\n }\n\n throw new Error('Unsupported or invalid type: ' + type)\n}\n\n// Is a type dynamic?\nfunction isDynamic (type) {\n // FIXME: handle all types? I don't think anything is missing now\n return (type === 'string') || (type === 'bytes') || (parseTypeArray(type) === 'dynamic')\n}\n\n// Is a type an array?\nfunction isArray (type) {\n return type.lastIndexOf(']') === type.length - 1\n}\n\n// Encode a method/event with arguments\n// @types an array of string type names\n// @args an array of the appropriate values\nfunction rawEncode (types, values) {\n var output = []\n var data = []\n\n var headLength = 32 * types.length\n\n for (var i in types) {\n var type = elementaryName(types[i])\n var value = values[i]\n var cur = encodeSingle(type, value)\n\n // Use the head/tail method for storing dynamic data\n if (isDynamic(type)) {\n output.push(encodeSingle('uint256', headLength))\n data.push(cur)\n headLength += cur.length\n } else {\n output.push(cur)\n }\n }\n\n return Buffer.concat(output.concat(data))\n}\n\nfunction solidityPack (types, values) {\n if (types.length !== values.length) {\n throw new Error('Number of types are not matching the values')\n }\n\n var size, num\n var ret = []\n\n for (var i = 0; i < types.length; i++) {\n var type = elementaryName(types[i])\n var value = values[i]\n\n if (type === 'bytes') {\n ret.push(value)\n } else if (type === 'string') {\n ret.push(new Buffer(value, 'utf8'))\n } else if (type === 'bool') {\n ret.push(new Buffer(value ? '01' : '00', 'hex'))\n } else if (type === 'address') {\n ret.push(util.setLength(value, 20))\n } else if (type.startsWith('bytes')) {\n size = parseTypeN(type)\n if (size < 1 || size > 32) {\n throw new Error('Invalid bytes width: ' + size)\n }\n\n ret.push(util.setLengthRight(value, size))\n } else if (type.startsWith('uint')) {\n size = parseTypeN(type)\n if ((size % 8) || (size < 8) || (size > 256)) {\n throw new Error('Invalid uint width: ' + size)\n }\n\n num = parseNumber(value)\n if (num.bitLength() > size) {\n throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength())\n }\n\n ret.push(num.toArrayLike(Buffer, 'be', size / 8))\n } else if (type.startsWith('int')) {\n size = parseTypeN(type)\n if ((size % 8) || (size < 8) || (size > 256)) {\n throw new Error('Invalid int width: ' + size)\n }\n\n num = parseNumber(value)\n if (num.bitLength() > size) {\n throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength())\n }\n\n ret.push(num.toTwos(size).toArrayLike(Buffer, 'be', size / 8))\n } else {\n // FIXME: support all other types\n throw new Error('Unsupported or invalid type: ' + type)\n }\n }\n\n return Buffer.concat(ret)\n}\n\nfunction soliditySHA3 (types, values) {\n return util.keccak(solidityPack(types, values))\n}\n\nmodule.exports = {\n rawEncode,\n solidityPack,\n soliditySHA3\n}\n","const util = require('./util')\nconst abi = require('./abi')\n\nconst TYPED_MESSAGE_SCHEMA = {\n type: 'object',\n properties: {\n types: {\n type: 'object',\n additionalProperties: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n name: {type: 'string'},\n type: {type: 'string'},\n },\n required: ['name', 'type'],\n },\n },\n },\n primaryType: {type: 'string'},\n domain: {type: 'object'},\n message: {type: 'object'},\n },\n required: ['types', 'primaryType', 'domain', 'message'],\n}\n\n/**\n * A collection of utility functions used for signing typed data\n */\nconst TypedDataUtils = {\n /**\n * Encodes an object by encoding and concatenating each of its members\n *\n * @param {string} primaryType - Root type\n * @param {Object} data - Object to encode\n * @param {Object} types - Type definitions\n * @returns {string} - Encoded representation of an object\n */\n encodeData (primaryType, data, types, useV4 = true) {\n const encodedTypes = ['bytes32']\n const encodedValues = [this.hashType(primaryType, types)]\n\n if(useV4) {\n const encodeField = (name, type, value) => {\n if (types[type] !== undefined) {\n return ['bytes32', value == null ?\n '0x0000000000000000000000000000000000000000000000000000000000000000' :\n util.keccak(this.encodeData(type, value, types, useV4))]\n }\n\n if(value === undefined)\n throw new Error(`missing value for field ${name} of type ${type}`)\n\n if (type === 'bytes') {\n return ['bytes32', util.keccak(value)]\n }\n\n if (type === 'string') {\n // convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex\n if (typeof value === 'string') {\n value = Buffer.from(value, 'utf8')\n }\n return ['bytes32', util.keccak(value)]\n }\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = value.map(item =>\n encodeField(name, parsedType, item))\n return ['bytes32', util.keccak(abi.rawEncode(\n typeValuePairs.map(([type]) => type),\n typeValuePairs.map(([, value]) => value),\n ))]\n }\n\n return [type, value]\n }\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField(field.name, field.type, data[field.name])\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n } else {\n for (const field of types[primaryType]) {\n let value = data[field.name]\n if (value !== undefined) {\n if (field.type === 'bytes') {\n encodedTypes.push('bytes32')\n value = util.keccak(value)\n encodedValues.push(value)\n } else if (field.type === 'string') {\n encodedTypes.push('bytes32')\n // convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex\n if (typeof value === 'string') {\n value = Buffer.from(value, 'utf8')\n }\n value = util.keccak(value)\n encodedValues.push(value)\n } else if (types[field.type] !== undefined) {\n encodedTypes.push('bytes32')\n value = util.keccak(this.encodeData(field.type, value, types, useV4))\n encodedValues.push(value)\n } else if (field.type.lastIndexOf(']') === field.type.length - 1) {\n throw new Error('Arrays currently unimplemented in encodeData')\n } else {\n encodedTypes.push(field.type)\n encodedValues.push(value)\n }\n }\n }\n }\n\n return abi.rawEncode(encodedTypes, encodedValues)\n },\n\n /**\n * Encodes the type of an object by encoding a comma delimited list of its members\n *\n * @param {string} primaryType - Root type to encode\n * @param {Object} types - Type definitions\n * @returns {string} - Encoded representation of the type of an object\n */\n encodeType (primaryType, types) {\n let result = ''\n let deps = this.findTypeDependencies(primaryType, types).filter(dep => dep !== primaryType)\n deps = [primaryType].concat(deps.sort())\n for (const type of deps) {\n const children = types[type]\n if (!children) {\n throw new Error('No type definition specified: ' + type)\n }\n result += type + '(' + types[type].map(({ name, type }) => type + ' ' + name).join(',') + ')'\n }\n return result\n },\n\n /**\n * Finds all types within a type defintion object\n *\n * @param {string} primaryType - Root type\n * @param {Object} types - Type definitions\n * @param {Array} results - current set of accumulated types\n * @returns {Array} - Set of all types found in the type definition\n */\n findTypeDependencies (primaryType, types, results = []) {\n primaryType = primaryType.match(/^\\w*/)[0]\n if (results.includes(primaryType) || types[primaryType] === undefined) { return results }\n results.push(primaryType)\n for (const field of types[primaryType]) {\n for (const dep of this.findTypeDependencies(field.type, types, results)) {\n !results.includes(dep) && results.push(dep)\n }\n }\n return results\n },\n\n /**\n * Hashes an object\n *\n * @param {string} primaryType - Root type\n * @param {Object} data - Object to hash\n * @param {Object} types - Type definitions\n * @returns {Buffer} - Hash of an object\n */\n hashStruct (primaryType, data, types, useV4 = true) {\n return util.keccak(this.encodeData(primaryType, data, types, useV4))\n },\n\n /**\n * Hashes the type of an object\n *\n * @param {string} primaryType - Root type to hash\n * @param {Object} types - Type definitions\n * @returns {string} - Hash of an object\n */\n hashType (primaryType, types) {\n return util.keccak(this.encodeType(primaryType, types))\n },\n\n /**\n * Removes properties from a message object that are not defined per EIP-712\n *\n * @param {Object} data - typed message object\n * @returns {Object} - typed message object with only allowed fields\n */\n sanitizeData (data) {\n const sanitizedData = {}\n for (const key in TYPED_MESSAGE_SCHEMA.properties) {\n data[key] && (sanitizedData[key] = data[key])\n }\n if (sanitizedData.types) {\n sanitizedData.types = Object.assign({ EIP712Domain: [] }, sanitizedData.types)\n }\n return sanitizedData\n },\n\n /**\n * Returns the hash of a typed message as per EIP-712 for signing\n *\n * @param {Object} typedData - Types message data to sign\n * @returns {string} - sha3 hash for signing\n */\n hash (typedData, useV4 = true) {\n const sanitizedData = this.sanitizeData(typedData)\n const parts = [Buffer.from('1901', 'hex')]\n parts.push(this.hashStruct('EIP712Domain', sanitizedData.domain, sanitizedData.types, useV4))\n if (sanitizedData.primaryType !== 'EIP712Domain') {\n parts.push(this.hashStruct(sanitizedData.primaryType, sanitizedData.message, sanitizedData.types, useV4))\n }\n return util.keccak(Buffer.concat(parts))\n },\n}\n\nmodule.exports = {\n TYPED_MESSAGE_SCHEMA,\n TypedDataUtils,\n\n hashForSignTypedDataLegacy: function (msgParams) {\n return typedSignatureHashLegacy(msgParams.data)\n },\n\n hashForSignTypedData_v3: function (msgParams) {\n return TypedDataUtils.hash(msgParams.data, false)\n },\n\n hashForSignTypedData_v4: function (msgParams) {\n return TypedDataUtils.hash(msgParams.data)\n },\n}\n\n/**\n * @param typedData - Array of data along with types, as per EIP712.\n * @returns Buffer\n */\nfunction typedSignatureHashLegacy(typedData) {\n const error = new Error('Expect argument to be non-empty array')\n if (typeof typedData !== 'object' || !typedData.length) throw error\n\n const data = typedData.map(function (e) {\n return e.type === 'bytes' ? util.toBuffer(e.value) : e.value\n })\n const types = typedData.map(function (e) { return e.type })\n const schema = typedData.map(function (e) {\n if (!e.name) throw error\n return e.type + ' ' + e.name\n })\n\n return abi.soliditySHA3(\n ['bytes32', 'bytes32'],\n [\n abi.soliditySHA3(new Array(typedData.length).fill('string'), schema),\n abi.soliditySHA3(types, data)\n ]\n )\n}\n","// Extracted from https://github.com/ethereumjs/ethereumjs-util and stripped out irrelevant code\n// Original code licensed under the Mozilla Public License Version 2.0\n\nconst createKeccakHash = require('keccak/js')\nconst BN = require('bn.js')\n\n/**\n * Returns a buffer filled with 0s\n * @method zeros\n * @param {Number} bytes the number of bytes the buffer should be\n * @return {Buffer}\n */\nfunction zeros (bytes) {\n return Buffer.allocUnsafe(bytes).fill(0)\n}\n\n/**\n * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes.\n * Or it truncates the beginning if it exceeds.\n * @method setLength\n * @param {Buffer|Array} msg the value to pad\n * @param {Number} length the number of bytes the output should be\n * @param {Boolean} [right=false] whether to start padding form the left or right\n * @return {Buffer|Array}\n */\nfunction setLength (msg, length, right) {\n const buf = zeros(length)\n msg = toBuffer(msg)\n if (right) {\n if (msg.length < length) {\n msg.copy(buf)\n return buf\n }\n return msg.slice(0, length)\n } else {\n if (msg.length < length) {\n msg.copy(buf, length - msg.length)\n return buf\n }\n return msg.slice(-length)\n }\n}\n\n/**\n * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes.\n * Or it truncates the beginning if it exceeds.\n * @param {Buffer|Array} msg the value to pad\n * @param {Number} length the number of bytes the output should be\n * @return {Buffer|Array}\n */\nfunction setLengthRight (msg, length) {\n return setLength(msg, length, true)\n}\n\n/**\n * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method.\n * @param {*} v the value\n */\nfunction toBuffer (v) {\n if (!Buffer.isBuffer(v)) {\n if (Array.isArray(v)) {\n v = Buffer.from(v)\n } else if (typeof v === 'string') {\n if (isHexString(v)) {\n v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex')\n } else {\n v = Buffer.from(v)\n }\n } else if (typeof v === 'number') {\n v = intToBuffer(v)\n } else if (v === null || v === undefined) {\n v = Buffer.allocUnsafe(0)\n } else if (BN.isBN(v)) {\n v = v.toArrayLike(Buffer)\n } else if (v.toArray) {\n // converts a BN to a Buffer\n v = Buffer.from(v.toArray())\n } else {\n throw new Error('invalid type')\n }\n }\n return v\n}\n\n/**\n * Converts a `Buffer` into a hex `String`\n * @param {Buffer} buf\n * @return {String}\n */\nfunction bufferToHex (buf) {\n buf = toBuffer(buf)\n return '0x' + buf.toString('hex')\n}\n\n/**\n * Creates Keccak hash of the input\n * @param {Buffer|Array|String|Number} a the input data\n * @param {Number} [bits=256] the Keccak width\n * @return {Buffer}\n */\nfunction keccak (a, bits) {\n a = toBuffer(a)\n if (!bits) bits = 256\n\n return createKeccakHash('keccak' + bits).update(a).digest()\n}\n\nfunction padToEven (str) {\n return str.length % 2 ? '0' + str : str\n}\n\nfunction isHexString (str) {\n return typeof str === 'string' && str.match(/^0x[0-9A-Fa-f]*$/)\n}\n\nfunction stripHexPrefix (str) {\n if (typeof str === 'string' && str.startsWith('0x')) {\n return str.slice(2)\n }\n return str\n}\n\nmodule.exports = {\n zeros,\n setLength,\n setLengthRight,\n isHexString,\n stripHexPrefix,\n toBuffer,\n bufferToHex,\n keccak\n}\n","/**\n * @fileoverview\n * - modified davidshimjs/qrcodejs library for use in node.js\n * - Using the 'QRCode for Javascript library'\n * - Fixed dataset of 'QRCode for Javascript library' for support full-spec.\n * - this library has no dependencies.\n *\n * @version 0.9.1 (2016-02-12)\n * @author davidshimjs, papnkukn\n * @see http://www.d-project.com/\n * @see http://jeromeetienne.github.com/jquery-qrcode/\n * @see https://github.com/davidshimjs/qrcodejs\n */\n\n//---------------------------------------------------------------------\n// QRCode for JavaScript\n//\n// Copyright (c) 2009 Kazuhiko Arase\n//\n// URL: http://www.d-project.com/\n//\n// Licensed under the MIT license:\n// http://www.opensource.org/licenses/mit-license.php\n//\n// The word \"QR Code\" is registered trademark of\n// DENSO WAVE INCORPORATED\n// http://www.denso-wave.com/qrcode/faqpatent-e.html\n//\n//---------------------------------------------------------------------\nfunction QR8bitByte(data) {\n this.mode = QRMode.MODE_8BIT_BYTE;\n this.data = data;\n this.parsedData = [];\n\n // Added to support UTF-8 Characters\n for (var i = 0, l = this.data.length; i < l; i++) {\n var byteArray = [];\n var code = this.data.charCodeAt(i);\n\n if (code > 0x10000) {\n byteArray[0] = 0xF0 | ((code & 0x1C0000) >>> 18);\n byteArray[1] = 0x80 | ((code & 0x3F000) >>> 12);\n byteArray[2] = 0x80 | ((code & 0xFC0) >>> 6);\n byteArray[3] = 0x80 | (code & 0x3F);\n } else if (code > 0x800) {\n byteArray[0] = 0xE0 | ((code & 0xF000) >>> 12);\n byteArray[1] = 0x80 | ((code & 0xFC0) >>> 6);\n byteArray[2] = 0x80 | (code & 0x3F);\n } else if (code > 0x80) {\n byteArray[0] = 0xC0 | ((code & 0x7C0) >>> 6);\n byteArray[1] = 0x80 | (code & 0x3F);\n } else {\n byteArray[0] = code;\n }\n\n this.parsedData.push(byteArray);\n }\n\n this.parsedData = Array.prototype.concat.apply([], this.parsedData);\n\n if (this.parsedData.length != this.data.length) {\n this.parsedData.unshift(191);\n this.parsedData.unshift(187);\n this.parsedData.unshift(239);\n }\n}\n\nQR8bitByte.prototype = {\n getLength: function (buffer) {\n return this.parsedData.length;\n },\n write: function (buffer) {\n for (var i = 0, l = this.parsedData.length; i < l; i++) {\n buffer.put(this.parsedData[i], 8);\n }\n }\n};\n\nfunction QRCodeModel(typeNumber, errorCorrectLevel) {\n this.typeNumber = typeNumber;\n this.errorCorrectLevel = errorCorrectLevel;\n this.modules = null;\n this.moduleCount = 0;\n this.dataCache = null;\n this.dataList = [];\n}\n\nQRCodeModel.prototype={addData:function(data){var newData=new QR8bitByte(data);this.dataList.push(newData);this.dataCache=null;},isDark:function(row,col){if(row<0||this.moduleCount<=row||col<0||this.moduleCount<=col){throw new Error(row+\",\"+col);}\nreturn this.modules[row][col];},getModuleCount:function(){return this.moduleCount;},make:function(){this.makeImpl(false,this.getBestMaskPattern());},makeImpl:function(test,maskPattern){this.moduleCount=this.typeNumber*4+17;this.modules=new Array(this.moduleCount);for(var row=0;row=7){this.setupTypeNumber(test);}\nif(this.dataCache==null){this.dataCache=QRCodeModel.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);}\nthis.mapData(this.dataCache,maskPattern);},setupPositionProbePattern:function(row,col){for(var r=-1;r<=7;r++){if(row+r<=-1||this.moduleCount<=row+r)continue;for(var c=-1;c<=7;c++){if(col+c<=-1||this.moduleCount<=col+c)continue;if((0<=r&&r<=6&&(c==0||c==6))||(0<=c&&c<=6&&(r==0||r==6))||(2<=r&&r<=4&&2<=c&&c<=4)){this.modules[row+r][col+c]=true;}else{this.modules[row+r][col+c]=false;}}}},getBestMaskPattern:function(){var minLostPoint=0;var pattern=0;for(var i=0;i<8;i++){this.makeImpl(true,i);var lostPoint=QRUtil.getLostPoint(this);if(i==0||minLostPoint>lostPoint){minLostPoint=lostPoint;pattern=i;}}\nreturn pattern;},createMovieClip:function(target_mc,instance_name,depth){var qr_mc=target_mc.createEmptyMovieClip(instance_name,depth);var cs=1;this.make();for(var row=0;row>i)&1)==1);this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=mod;}\nfor(var i=0;i<18;i++){var mod=(!test&&((bits>>i)&1)==1);this.modules[i%3+this.moduleCount-8-3][Math.floor(i/3)]=mod;}},setupTypeInfo:function(test,maskPattern){var data=(this.errorCorrectLevel<<3)|maskPattern;var bits=QRUtil.getBCHTypeInfo(data);for(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<6){this.modules[i][8]=mod;}else if(i<8){this.modules[i+1][8]=mod;}else{this.modules[this.moduleCount-15+i][8]=mod;}}\nfor(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<8){this.modules[8][this.moduleCount-i-1]=mod;}else if(i<9){this.modules[8][15-i-1+1]=mod;}else{this.modules[8][15-i-1]=mod;}}\nthis.modules[this.moduleCount-8][8]=(!test);},mapData:function(data,maskPattern){var inc=-1;var row=this.moduleCount-1;var bitIndex=7;var byteIndex=0;for(var col=this.moduleCount-1;col>0;col-=2){if(col==6)col--;while(true){for(var c=0;c<2;c++){if(this.modules[row][col-c]==null){var dark=false;if(byteIndex>>bitIndex)&1)==1);}\nvar mask=QRUtil.getMask(maskPattern,row,col-c);if(mask){dark=!dark;}\nthis.modules[row][col-c]=dark;bitIndex--;if(bitIndex==-1){byteIndex++;bitIndex=7;}}}\nrow+=inc;if(row<0||this.moduleCount<=row){row-=inc;inc=-inc;break;}}}}};QRCodeModel.PAD0=0xEC;QRCodeModel.PAD1=0x11;QRCodeModel.createData=function(typeNumber,errorCorrectLevel,dataList){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,errorCorrectLevel);var buffer=new QRBitBuffer();for(var i=0;itotalDataCount*8){throw new Error(\"code length overflow. (\"\n+buffer.getLengthInBits()\n+\">\"\n+totalDataCount*8\n+\")\");}\nif(buffer.getLengthInBits()+4<=totalDataCount*8){buffer.put(0,4);}\nwhile(buffer.getLengthInBits()%8!=0){buffer.putBit(false);}\nwhile(true){if(buffer.getLengthInBits()>=totalDataCount*8){break;}\nbuffer.put(QRCodeModel.PAD0,8);if(buffer.getLengthInBits()>=totalDataCount*8){break;}\nbuffer.put(QRCodeModel.PAD1,8);}\nreturn QRCodeModel.createBytes(buffer,rsBlocks);};QRCodeModel.createBytes=function(buffer,rsBlocks){var offset=0;var maxDcCount=0;var maxEcCount=0;var dcdata=new Array(rsBlocks.length);var ecdata=new Array(rsBlocks.length);for(var r=0;r=0)?modPoly.get(modIndex):0;}}\nvar totalCodeCount=0;for(var i=0;i=0){d^=(QRUtil.G15<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15)));}\nreturn((data<<10)|d)^QRUtil.G15_MASK;},getBCHTypeNumber:function(data){var d=data<<12;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)>=0){d^=(QRUtil.G18<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)));}\nreturn(data<<12)|d;},getBCHDigit:function(data){var digit=0;while(data!=0){digit++;data>>>=1;}\nreturn digit;},getPatternPosition:function(typeNumber){return QRUtil.PATTERN_POSITION_TABLE[typeNumber-1];},getMask:function(maskPattern,i,j){switch(maskPattern){case QRMaskPattern.PATTERN000:return(i+j)%2==0;case QRMaskPattern.PATTERN001:return i%2==0;case QRMaskPattern.PATTERN010:return j%3==0;case QRMaskPattern.PATTERN011:return(i+j)%3==0;case QRMaskPattern.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2==0;case QRMaskPattern.PATTERN101:return(i*j)%2+(i*j)%3==0;case QRMaskPattern.PATTERN110:return((i*j)%2+(i*j)%3)%2==0;case QRMaskPattern.PATTERN111:return((i*j)%3+(i+j)%2)%2==0;default:throw new Error(\"bad maskPattern:\"+maskPattern);}},getErrorCorrectPolynomial:function(errorCorrectLength){var a=new QRPolynomial([1],0);for(var i=0;i5){lostPoint+=(3+sameCount-5);}}}\nfor(var row=0;row=256){n-=255;}\nreturn QRMath.EXP_TABLE[n];},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var i=0;i<8;i++){QRMath.EXP_TABLE[i]=1<>>(7-index%8))&1)==1;},put:function(num,length){for(var i=0;i>>(length-i-1))&1)==1);}},getLengthInBits:function(){return this.length;},putBit:function(bit){var bufIndex=Math.floor(this.length/8);if(this.buffer.length<=bufIndex){this.buffer.push(0);}\nif(bit){this.buffer[bufIndex]|=(0x80>>>(this.length%8));}\nthis.length++;}};var QRCodeLimitLength=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]];\n\n\n/** Constructor */\nfunction QRCode(options) {\n var instance = this;\n\n //Default options\n this.options = {\n padding: 4,\n width: 256,\n height: 256,\n typeNumber: 4,\n color: \"#000000\",\n background: \"#ffffff\",\n ecl: \"M\",\n image:{\n svg:\"\",\n width:0,\n height:0\n }\n };\n\n //In case the options is string\n if (typeof options === 'string') {\n options = {\n content: options\n };\n }\n\n //Merge options\n if (options) {\n for (var i in options) {\n this.options[i] = options[i];\n }\n }\n\n if (typeof this.options.content !== 'string') {\n throw new Error(\"Expected 'content' as string!\");\n }\n\n if (this.options.content.length === 0 /* || this.options.content.length > 7089 */) {\n throw new Error(\"Expected 'content' to be non-empty!\");\n }\n\n if (!(this.options.padding >= 0)) {\n throw new Error(\"Expected 'padding' value to be non-negative!\");\n }\n\n if (!(this.options.width > 0) || !(this.options.height > 0)) {\n throw new Error(\"Expected 'width' or 'height' value to be higher than zero!\");\n }\n\n //Gets the error correction level\n function _getErrorCorrectLevel(ecl) {\n switch (ecl) {\n case \"L\":\n return QRErrorCorrectLevel.L;\n\n case \"M\":\n return QRErrorCorrectLevel.M;\n\n case \"Q\":\n return QRErrorCorrectLevel.Q;\n\n case \"H\":\n return QRErrorCorrectLevel.H;\n\n default:\n throw new Error(\"Unknwon error correction level: \" + ecl);\n }\n }\n\n //Get type number\n function _getTypeNumber(content, ecl) {\n var length = _getUTF8Length(content);\n\n var type = 1;\n var limit = 0;\n for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) {\n var table = QRCodeLimitLength[i];\n if (!table) {\n throw new Error(\"Content too long: expected \" + limit + \" but got \" + length);\n }\n\n switch (ecl) {\n case \"L\":\n limit = table[0];\n break;\n\n case \"M\":\n limit = table[1];\n break;\n\n case \"Q\":\n limit = table[2];\n break;\n\n case \"H\":\n limit = table[3];\n break;\n\n default:\n throw new Error(\"Unknwon error correction level: \" + ecl);\n }\n\n if (length <= limit) {\n break;\n }\n\n type++;\n }\n\n if (type > QRCodeLimitLength.length) {\n throw new Error(\"Content too long\");\n }\n\n return type;\n }\n\n //Gets text length\n function _getUTF8Length(content) {\n var result = encodeURI(content).toString().replace(/\\%[0-9a-fA-F]{2}/g, 'a');\n return result.length + (result.length != content ? 3 : 0);\n }\n\n //Generate QR Code matrix\n var content = this.options.content;\n var type = _getTypeNumber(content, this.options.ecl);\n var ecl = _getErrorCorrectLevel(this.options.ecl);\n this.qrcode = new QRCodeModel(type, ecl);\n this.qrcode.addData(content);\n this.qrcode.make();\n}\n\n/** Generates QR Code as SVG image */\nQRCode.prototype.svg = function(opt) {\n var options = this.options || { };\n var modules = this.qrcode.modules;\n\n if (typeof opt == \"undefined\") {\n opt = { container: options.container || \"svg\" };\n }\n\n //Apply new lines and indents in SVG?\n var pretty = typeof options.pretty != \"undefined\" ? !!options.pretty : true;\n\n var indent = pretty ? ' ' : '';\n var EOL = pretty ? '\\r\\n' : '';\n var width = options.width;\n var height = options.height;\n var length = modules.length;\n var xsize = width / (length + 2 * options.padding);\n var ysize = height / (length + 2 * options.padding);\n\n //Join (union, merge) rectangles into one shape?\n var join = typeof options.join != \"undefined\" ? !!options.join : false;\n\n //Swap the X and Y modules, pull request #2\n var swap = typeof options.swap != \"undefined\" ? !!options.swap : false;\n\n //Apply declaration in SVG?\n var xmlDeclaration = typeof options.xmlDeclaration != \"undefined\" ? !!options.xmlDeclaration : true;\n\n //Populate with predefined shape instead of \"rect\" elements, thanks to @kkocdko\n var predefined = typeof options.predefined != \"undefined\" ? !!options.predefined : false;\n var defs = predefined ? indent + '' + EOL : '';\n\n //Background rectangle\n var bgrect = indent + '' + EOL;\n\n //Rectangles representing modules\n var modrect = '';\n var pathdata = '';\n\n for (var y = 0; y < length; y++) {\n for (var x = 0; x < length; x++) {\n var module = modules[x][y];\n if (module) {\n\n var px = (x * xsize + options.padding * xsize);\n var py = (y * ysize + options.padding * ysize);\n\n //Some users have had issues with the QR Code, thanks to @danioso for the solution\n if (swap) {\n var t = px;\n px = py;\n py = t;\n }\n\n if (join) {\n //Module as a part of svg path data, thanks to @danioso\n var w = xsize + px\n var h = ysize + py\n\n px = (Number.isInteger(px))? Number(px): px.toFixed(2);\n py = (Number.isInteger(py))? Number(py): py.toFixed(2);\n w = (Number.isInteger(w))? Number(w): w.toFixed(2);\n h = (Number.isInteger(h))? Number(h): h.toFixed(2);\n\n pathdata += ('M' + px + ',' + py + ' V' + h + ' H' + w + ' V' + py + ' H' + px + ' Z ');\n }\n else if (predefined) {\n //Module as a predefined shape, thanks to @kkocdko\n modrect += indent + '' + EOL;\n }\n else {\n //Module as rectangle element\n modrect += indent + '' + EOL;\n }\n }\n }\n }\n\n if (join) {\n modrect = indent + '';\n }\n let imgSvg = \"\";\n if(this.options.image !== undefined && this.options.image.svg){\n const imgWidth = width * this.options.image.width / 100;\n const imgHeight = height * this.options.image.height / 100;\n const imgX = (width/2) - imgWidth/2;\n const imgY = (height/2) - imgHeight/2;\n imgSvg += ``;\n imgSvg += this.options.image.svg + EOL;\n imgSvg += '';\n }\n\n var svg = \"\";\n switch (opt.container) {\n //Wrapped in SVG document\n case \"svg\":\n if (xmlDeclaration) {\n svg += '' + EOL;\n }\n svg += '' + EOL;\n svg += defs + bgrect + modrect;\n svg += imgSvg;\n svg += '';\n break;\n\n //Viewbox for responsive use in a browser, thanks to @danioso\n case \"svg-viewbox\":\n if (xmlDeclaration) {\n svg += '' + EOL;\n }\n svg += '' + EOL;\n svg += defs + bgrect + modrect;\n svg += imgSvg;\n svg += '';\n break;\n\n\n //Wrapped in group element\n case \"g\":\n svg += '' + EOL;\n svg += defs + bgrect + modrect;\n svg += imgSvg;\n svg += '';\n\n break;\n\n //Without a container\n default:\n svg += (defs + bgrect + modrect + imgSvg).replace(/^\\s+/, \"\"); //Clear indents on each line\n break;\n }\n\n return svg;\n};\n\nmodule.exports = QRCode;\n\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LIB_VERSION = void 0;\nexports.LIB_VERSION = '3.9.1';\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n",null,"import { assert as assertSuperstruct, Struct } from 'superstruct';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Get the error message from an unknown error object. If the error object has\n * a `message` property, that property is returned. Otherwise, the stringified\n * error object is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The error message.\n */\nfunction getErrorMessage(error: unknown): string {\n const message = isErrorWithMessage(error) ? error.message : String(error);\n\n // If the error ends with a period, remove it, as we'll add our own period.\n if (message.endsWith('.')) {\n return message.slice(0, -1);\n }\n\n return message;\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct(\n value: unknown,\n struct: Struct,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is T {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n","import { pattern, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Base64Options = {\n /**\n * Is the `=` padding at the end required or not.\n *\n * @default false\n */\n // Padding is optional in RFC 4648, that's why the default value is false\n paddingRequired?: boolean;\n /**\n * Which character set should be used.\n * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.\n *\n * @default 'base64'\n */\n characterSet?: 'base64' | 'base64url';\n};\n\n/**\n * Ensure that a provided string-based struct is valid base64.\n *\n * @param struct - The string based struct.\n * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.\n * @returns A superstruct validating base64.\n */\nexport const base64 = (\n struct: Struct,\n options: Base64Options = {},\n) => {\n const paddingRequired = options.paddingRequired ?? false;\n const characterSet = options.characterSet ?? 'base64';\n\n let letters: string;\n if (characterSet === 'base64') {\n letters = String.raw`[A-Za-z0-9+\\/]`;\n } else {\n assert(characterSet === 'base64url');\n letters = String.raw`[-_A-Za-z0-9]`;\n }\n\n let re: RegExp;\n if (paddingRequired) {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n } else {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n }\n\n return pattern(struct, re);\n};\n","import { assert } from './assert';\nimport { add0x, assertIsHexString, Hex, remove0x } from './hex';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hexadecimal = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hexadecimal[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hexadecimal.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hexadecimal = bytesToHex(bytes);\n return BigInt(hexadecimal);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\n // \"0x\" is often used as empty byte array.\n if (value?.toLowerCase?.() === '0x') {\n return new Uint8Array();\n }\n\n assertIsHexString(value);\n\n // Remove the `0x` prefix if it exists, and pad the string to have an even\n // number of characters.\n const strippedValue = remove0x(value).toLowerCase();\n const normalizedValue =\n strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;\n const bytes = new Uint8Array(normalizedValue.length / 2);\n\n for (let i = 0; i < bytes.length; i++) {\n // While this is not the prettiest way to convert a hexadecimal string to a\n // `Uint8Array`, it is a lot faster than using `parseInt` to convert each\n // character.\n const c1 = normalizedValue.charCodeAt(i * 2);\n const c2 = normalizedValue.charCodeAt(i * 2 + 1);\n const n1 =\n c1 -\n (c1 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n const n2 =\n c2 -\n (c2 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n\n bytes[i] = n1 * 16 + n2;\n }\n\n return bytes;\n}\n\n/**\n * Convert a `bigint` to a `Uint8Array`.\n *\n * This assumes that the `bigint` is an unsigned integer. To convert a signed\n * `bigint` instead, use {@link signedBigIntToBytes}.\n *\n * @param value - The bigint to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function bigIntToBytes(value: bigint): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= BigInt(0), 'Value must be a non-negative bigint.');\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Check if a `bigint` fits in a certain number of bytes.\n *\n * @param value - The `bigint` to check.\n * @param bytes - The number of bytes.\n * @returns Whether the `bigint` fits in the number of bytes.\n */\nfunction bigIntFits(value: bigint, bytes: number): boolean {\n assert(bytes > 0);\n\n /* eslint-disable no-bitwise */\n const mask = value >> BigInt(31);\n return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement\n * encoding to represent negative numbers.\n *\n * To convert an unsigned `bigint` to a `Uint8Array` instead, use\n * {@link bigIntToBytes}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param value - The number to convert to bytes.\n * @param byteLength - The length of the resulting `Uint8Array`. If the number\n * is larger than the maximum value that can be represented by the given length,\n * an error is thrown.\n * @returns The bytes as `Uint8Array`.\n */\nexport function signedBigIntToBytes(\n value: bigint,\n byteLength: number,\n): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(typeof byteLength === 'number', 'Byte length must be a number.');\n assert(byteLength > 0, 'Byte length must be greater than 0.');\n assert(\n bigIntFits(value, byteLength),\n 'Byte length is too small to represent the given value.',\n );\n\n // ESLint doesn't like mutating function parameters, so to avoid having to\n // disable the rule, we create a new variable.\n let numberValue = value;\n const bytes = new Uint8Array(byteLength);\n\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number(BigInt.asUintN(8, numberValue));\n // eslint-disable-next-line no-bitwise\n numberValue >>= BigInt(8);\n }\n\n return bytes.reverse();\n}\n\n/**\n * Convert a `number` to a `Uint8Array`.\n *\n * @param value - The number to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n * @throws If the number is not a safe integer.\n */\nexport function numberToBytes(value: number): Uint8Array {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToBytes` instead.',\n );\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Convert a `string` to a UTF-8 encoded `Uint8Array`.\n *\n * @param value - The string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function stringToBytes(value: string): Uint8Array {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\n}\n\n/**\n * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,\n * a `bigint`, a `number`, or a `string`.\n *\n * This will attempt to guess the type of the value based on its type and\n * contents. For more control over the conversion, use the more specific\n * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.\n *\n * If the value is a `string`, and it is prefixed with `0x`, it will be\n * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a\n * UTF-8 string. To convert a hexadecimal string to bytes without interpreting\n * it as a UTF-8 string, use {@link hexToBytes} instead.\n *\n * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed\n * `bigint` to bytes, use {@link signedBigIntToBytes} instead.\n *\n * If the value is a `Uint8Array`, it will be returned as-is.\n *\n * @param value - The value to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function valueToBytes(value: Bytes): Uint8Array {\n if (typeof value === 'bigint') {\n return bigIntToBytes(value);\n }\n\n if (typeof value === 'number') {\n return numberToBytes(value);\n }\n\n if (typeof value === 'string') {\n if (value.startsWith('0x')) {\n return hexToBytes(value);\n }\n\n return stringToBytes(value);\n }\n\n if (isBytes(value)) {\n return value;\n }\n\n throw new TypeError(`Unsupported value type: \"${typeof value}\".`);\n}\n\n/**\n * Concatenate multiple byte-like values into a single `Uint8Array`. The values\n * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses\n * {@link valueToBytes} under the hood to convert each value to bytes. Refer to\n * the documentation of that function for more information.\n *\n * @param values - The values to concatenate.\n * @returns The concatenated bytes as `Uint8Array`.\n */\nexport function concatBytes(values: Bytes[]): Uint8Array {\n const normalizedValues = new Array(values.length);\n let byteLength = 0;\n\n for (let i = 0; i < values.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const value = valueToBytes(values[i]!);\n\n normalizedValues[i] = value;\n byteLength += value.length;\n }\n\n const bytes = new Uint8Array(byteLength);\n for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\n // While we could simply spread the values into an array and use\n // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.\n bytes.set(normalizedValues[i], offset);\n offset += normalizedValues[i].length;\n }\n\n return bytes;\n}\n\n/**\n * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience\n * function that avoids having to create a {@link DataView} manually, which\n * requires passing the `byteOffset` and `byteLength` parameters every time.\n *\n * Not passing the `byteOffset` and `byteLength` parameters can result in\n * unexpected behavior when the {@link Uint8Array} is a view of a larger\n * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.\n *\n * This function also supports Node.js {@link Buffer}s.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([1, 2, 3]);\n *\n * // This is equivalent to:\n * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n * const dataView = createDataView(bytes);\n * ```\n * @param bytes - The bytes to create the {@link DataView} from.\n * @returns The {@link DataView}.\n */\nexport function createDataView(bytes: Uint8Array): DataView {\n // To maintain compatibility with Node.js, we need to check if the bytes are\n // a Buffer. If so, we need to slice the buffer to get the underlying\n // ArrayBuffer.\n // eslint-disable-next-line no-restricted-globals\n if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n );\n\n return new DataView(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n","import { size, string } from 'superstruct';\n\nimport { base64 } from './base64';\n\nexport const ChecksumStruct = size(\n base64(string(), { paddingRequired: true }),\n 44,\n 44,\n);\n","import {\n bigint,\n coerce,\n create,\n Infer,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\nimport { Hex, StrictHexStruct } from './hex';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\nconst BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);\nconst BytesCoercer = coerce(\n instance(Uint8Array),\n union([StrictHexStruct]),\n hexToBytes,\n);\n\nconst HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);\n\nexport type NumberLike = Infer;\nexport type BytesLike = Infer;\n\n/**\n * Create a number from a number-like value.\n *\n * - If the value is a number, it is returned as-is.\n * - If the value is a `bigint`, it is converted to a number.\n * - If the value is a string, it is interpreted as a decimal number.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number.\n *\n * This validates that the value is a number-like value, and that the resulting\n * number is not `NaN` or `Infinity`.\n *\n * @example\n * ```typescript\n * const value = createNumber('0x010203');\n * console.log(value); // 66051\n *\n * const otherValue = createNumber(123n);\n * console.log(otherValue); // 123\n * ```\n * @param value - The value to create the number from.\n * @returns The created number.\n * @throws If the value is not a number-like value, or if the resulting number\n * is `NaN` or `Infinity`.\n */\nexport function createNumber(value: NumberLike): number {\n try {\n const result = create(value, NumberCoercer);\n\n assert(\n Number.isFinite(result),\n `Expected a number-like value, got \"${value}\".`,\n );\n\n return result;\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a `bigint` from a number-like value.\n *\n * - If the value is a number, it is converted to a `bigint`.\n * - If the value is a `bigint`, it is returned as-is.\n * - If the value is a string, it is interpreted as a decimal number and\n * converted to a `bigint`.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number and converted to a `bigint`.\n *\n * @example\n * ```typescript\n * const value = createBigInt('0x010203');\n * console.log(value); // 16909060n\n *\n * const otherValue = createBigInt(123);\n * console.log(otherValue); // 123n\n * ```\n * @param value - The value to create the bigint from.\n * @returns The created bigint.\n * @throws If the value is not a number-like value.\n */\nexport function createBigInt(value: NumberLike): bigint {\n try {\n // The `BigInt` constructor throws if the value is not a number-like value.\n // There is no need to validate the value manually.\n return create(value, BigIntCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a number-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a byte array from a bytes-like value.\n *\n * - If the value is a byte array, it is returned as-is.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is interpreted\n * as a hexadecimal number and converted to a byte array.\n *\n * @example\n * ```typescript\n * const value = createBytes('0x010203');\n * console.log(value); // Uint8Array [ 1, 2, 3 ]\n *\n * const otherValue = createBytes('0x010203');\n * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]\n * ```\n * @param value - The value to create the byte array from.\n * @returns The created byte array.\n * @throws If the value is not a bytes-like value.\n */\nexport function createBytes(value: BytesLike): Uint8Array {\n if (typeof value === 'string' && value.toLowerCase() === '0x') {\n return new Uint8Array();\n }\n\n try {\n return create(value, BytesCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a hexadecimal string from a bytes-like value.\n *\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is returned\n * as-is.\n * - If the value is a `Uint8Array`, it is converted to a hex string.\n *\n * @example\n * ```typescript\n * const value = createHex(new Uint8Array([1, 2, 3]));\n * console.log(value); // '0x010203'\n *\n * const otherValue = createHex('0x010203');\n * console.log(otherValue); // '0x010203'\n * ```\n * @param value - The value to create the hex string from.\n * @returns The created hex string.\n * @throws If the value is not a bytes-like value.\n */\nexport function createHex(value: BytesLike): Hex {\n if (\n (value instanceof Uint8Array && value.length === 0) ||\n (typeof value === 'string' && value.toLowerCase() === '0x')\n ) {\n return '0x';\n }\n\n try {\n return create(value, HexCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n","/**\n * A {@link ReadonlyMap} that cannot be modified after instantiation.\n * The implementation uses an inner map hidden via a private field, and the\n * immutability guarantee relies on it being impossible to get a reference\n * to this map.\n */\nclass FrozenMap implements ReadonlyMap {\n readonly #map: Map;\n\n public get size() {\n return this.#map.size;\n }\n\n public [Symbol.iterator]() {\n return this.#map[Symbol.iterator]();\n }\n\n constructor(entries?: readonly (readonly [Key, Value])[] | null) {\n this.#map = new Map(entries);\n Object.freeze(this);\n }\n\n public entries() {\n return this.#map.entries();\n }\n\n public forEach(\n callbackfn: (value: Value, key: Key, map: this) => void,\n thisArg?: any,\n ): void {\n // We have to wrap the specified callback in order to prevent it from\n // receiving a reference to the inner map.\n return this.#map.forEach((value: Value, key: Key, _map: unknown) =>\n callbackfn.call(thisArg, value, key, this),\n );\n }\n\n public get(key: Key) {\n return this.#map.get(key);\n }\n\n public has(key: Key) {\n return this.#map.has(key);\n }\n\n public keys() {\n return this.#map.keys();\n }\n\n public values() {\n return this.#map.values();\n }\n\n public toString(): string {\n return `FrozenMap(${this.size}) {${\n this.size > 0\n ? ` ${[...this.entries()]\n .map(([key, value]) => `${String(key)} => ${String(value)}`)\n .join(', ')} `\n : ''\n }}`;\n }\n}\n\n/**\n * A {@link ReadonlySet} that cannot be modified after instantiation.\n * The implementation uses an inner set hidden via a private field, and the\n * immutability guarantee relies on it being impossible to get a reference\n * to this set.\n */\nclass FrozenSet implements ReadonlySet {\n readonly #set: Set;\n\n public get size() {\n return this.#set.size;\n }\n\n public [Symbol.iterator]() {\n return this.#set[Symbol.iterator]();\n }\n\n constructor(values?: readonly Value[] | null) {\n this.#set = new Set(values);\n Object.freeze(this);\n }\n\n public entries() {\n return this.#set.entries();\n }\n\n public forEach(\n callbackfn: (value: Value, value2: Value, set: this) => void,\n thisArg?: any,\n ): void {\n // We have to wrap the specified callback in order to prevent it from\n // receiving a reference to the inner set.\n return this.#set.forEach((value: Value, value2: Value, _set: unknown) =>\n callbackfn.call(thisArg, value, value2, this),\n );\n }\n\n public has(value: Value) {\n return this.#set.has(value);\n }\n\n public keys() {\n return this.#set.keys();\n }\n\n public values() {\n return this.#set.values();\n }\n\n public toString(): string {\n return `FrozenSet(${this.size}) {${\n this.size > 0\n ? ` ${[...this.values()].map((member) => String(member)).join(', ')} `\n : ''\n }}`;\n }\n}\n\nObject.freeze(FrozenMap);\nObject.freeze(FrozenMap.prototype);\n\nObject.freeze(FrozenSet);\nObject.freeze(FrozenSet.prototype);\n\nexport { FrozenMap, FrozenSet };\n","import { is, pattern, string, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Hex = `0x${string}`;\n\nexport const HexStruct = pattern(string(), /^(?:0x)?[0-9a-f]+$/iu);\nexport const StrictHexStruct = pattern(string(), /^0x[0-9a-f]+$/iu) as Struct<\n Hex,\n null\n>;\n\n/**\n * Check if a string is a valid hex string.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isHexString(value: unknown): value is string {\n return is(value, HexStruct);\n}\n\n/**\n * Strictly check if a string is a valid hex string. A valid hex string must\n * start with the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isStrictHexString(value: unknown): value is Hex {\n return is(value, StrictHexStruct);\n}\n\n/**\n * Assert that a value is a valid hex string.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsHexString(value: unknown): asserts value is string {\n assert(isHexString(value), 'Value must be a hexadecimal string.');\n}\n\n/**\n * Assert that a value is a valid hex string. A valid hex string must start with\n * the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsStrictHexString(value: unknown): asserts value is Hex {\n assert(\n isStrictHexString(value),\n 'Value must be a hexadecimal string, starting with \"0x\".',\n );\n}\n\n/**\n * Add the `0x`-prefix to a hexadecimal string. If the string already has the\n * prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to add the prefix to.\n * @returns The prefixed hexadecimal string.\n */\nexport function add0x(hexadecimal: string): Hex {\n if (hexadecimal.startsWith('0x')) {\n return hexadecimal as Hex;\n }\n\n if (hexadecimal.startsWith('0X')) {\n return `0x${hexadecimal.substring(2)}`;\n }\n\n return `0x${hexadecimal}`;\n}\n\n/**\n * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have\n * the prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to remove the prefix from.\n * @returns The un-prefixed hexadecimal string.\n */\nexport function remove0x(hexadecimal: string): string {\n if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) {\n return hexadecimal.substring(2);\n }\n\n return hexadecimal;\n}\n","export * from './assert';\nexport * from './base64';\nexport * from './bytes';\nexport * from './checksum';\nexport * from './coercers';\nexport * from './collections';\nexport * from './encryption-types';\nexport * from './hex';\nexport * from './json';\nexport * from './keyring';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './opaque';\nexport * from './time';\nexport * from './transaction-types';\nexport * from './versions';\n","import {\n array,\n boolean,\n define,\n Infer,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\n\nimport { AssertionErrorConstructor, assertStruct } from './assert';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = define('Json', (value, context) => {\n /**\n * Helper function that runs the given struct validator and returns the\n * validation errors, if any. If the value is valid, it returns `true`.\n *\n * @param innerValue - The value to validate.\n * @param struct - The struct to use for validation.\n * @returns The validation errors, or `true` if the value is valid.\n */\n function checkStruct(innerValue: unknown, struct: Struct) {\n const iterator = struct.validator(innerValue, context);\n const errors = [...iterator];\n\n if (errors.length > 0) {\n return errors;\n }\n\n return true;\n }\n\n try {\n // The plain value must be a valid JSON value, but it may be altered in the\n // process of JSON serialization, so we need to validate it again after\n // serialization. This has the added benefit that the returned error messages\n // will be more helpful, as they will point to the exact location of the\n // invalid value.\n //\n // This seems overcomplicated, but without checking the plain value first,\n // there are some cases where the validation passes, even though the value is\n // not valid JSON. For example, `undefined` is not valid JSON, but serializing\n // it will remove it from the object, so the validation will pass.\n const unsafeResult = checkStruct(value, UnsafeJsonStruct);\n if (unsafeResult !== true) {\n return unsafeResult;\n }\n\n // JavaScript engines are highly optimized for this specific use case of\n // JSON parsing and stringifying, so there should be no performance impact.\n return checkStruct(JSON.parse(JSON.stringify(value)), UnsafeJsonStruct);\n } catch (error) {\n if (error instanceof RangeError) {\n return 'Circular reference detected';\n }\n\n return false;\n }\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n return is(value, JsonStruct);\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: optional(JsonStruct),\n stack: optional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record,\n Key extends keyof Type,\n> = Omit & Partial>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\n);\nexport type JsonRpcParams = Infer;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct,\n Params extends JsonRpcParams,\n> = Omit, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest =\n InferWithParams;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification =\n InferWithParams;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse = Omit<\n Infer,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess = Omit<\n Infer,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse =\n | JsonRpcSuccess\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n","import debug, { Debugger } from 'debug';\n\nconst globalLogger = debug('metamask');\n\n/**\n * Creates a logger via the `debug` library whose log messages will be tagged\n * using the name of your project. By default, such messages will be\n * suppressed, but you can reveal them by setting the `DEBUG` environment\n * variable to `metamask:`. You can also set this variable to\n * `metamask:*` if you want to see log messages from all MetaMask projects that\n * are also using this function to create their loggers.\n *\n * @param projectName - The name of your project. This should be the name of\n * your NPM package if you're developing one.\n * @returns An instance of `debug`.\n */\nexport function createProjectLogger(projectName: string): Debugger {\n return globalLogger.extend(projectName);\n}\n\n/**\n * Creates a logger via the `debug` library which is derived from the logger for\n * the whole project whose log messages will be tagged using the name of your\n * module. By default, such messages will be suppressed, but you can reveal them\n * by setting the `DEBUG` environment variable to\n * `metamask::`. You can also set this variable to\n * `metamask::*` if you want to see log messages from the project,\n * or `metamask:*` if you want to see log messages from all MetaMask projects.\n *\n * @param projectLogger - The logger created via {@link createProjectLogger}.\n * @param moduleName - The name of your module. You could use the name of the\n * file where you're using this logger or some other name.\n * @returns An instance of `debug`.\n */\nexport function createModuleLogger(\n projectLogger: Debugger,\n moduleName: string,\n): Debugger {\n return projectLogger.extend(moduleName);\n}\n","//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record,\n TargetKey extends keyof ObjectValue,\n> = {\n -readonly [Key in keyof Pick]: ObjectValue[Key];\n} & {\n [Key in keyof Omit]: ObjectValue[Key];\n};\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent = Partial | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array.\n */\nexport type RuntimeObject = Record;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray(\n value: Element[],\n): value is NonEmptyArray {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * A type guard for ensuring an object has a property.\n *\n * @param objectToCheck - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = <\n // eslint-disable-next-line @typescript-eslint/ban-types\n ObjectToCheck extends Object,\n Property extends PropertyKey,\n>(\n objectToCheck: ObjectToCheck,\n name: Property,\n): objectToCheck is ObjectToCheck &\n Record<\n Property,\n Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown\n > => Object.hasOwnProperty.call(objectToCheck, name);\n\nexport type PlainObject = Record;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Date = 24,\n}\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string) {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n","import { assert } from './assert';\nimport { add0x, assertIsHexString } from './hex';\n\n/**\n * Convert a number to a hexadecimal string. This verifies that the number is a\n * non-negative safe integer.\n *\n * To convert a `bigint` to a hexadecimal string instead, use\n * {@link bigIntToHex}.\n *\n * @example\n * ```typescript\n * numberToHex(0); // '0x0'\n * numberToHex(1); // '0x1'\n * numberToHex(16); // '0x10'\n * ```\n * @param value - The number to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the number is not a non-negative safe integer.\n */\nexport const numberToHex = (value: number): string => {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToHex` instead.',\n );\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint`\n * is a non-negative integer.\n *\n * To convert a number to a hexadecimal string instead, use {@link numberToHex}.\n *\n * @example\n * ```typescript\n * bigIntToHex(0n); // '0x0'\n * bigIntToHex(1n); // '0x1'\n * bigIntToHex(16n); // '0x10'\n * ```\n * @param value - The `bigint` to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the `bigint` is not a non-negative integer.\n */\nexport const bigIntToHex = (value: bigint): string => {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= 0, 'Value must be a non-negative bigint.');\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a hexadecimal string to a number. This verifies that the string is a\n * valid hex string, and that the resulting number is a safe integer. Both\n * \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a `bigint` instead, use\n * {@link hexToBigInt}.\n *\n * @example\n * ```typescript\n * hexToNumber('0x0'); // 0\n * hexToNumber('0x1'); // 1\n * hexToNumber('0x10'); // 16\n * ```\n * @param value - The hexadecimal string to convert to a number.\n * @returns The number.\n * @throws If the value is not a valid hexadecimal string, or if the resulting\n * number is not a safe integer.\n */\nexport const hexToNumber = (value: string): number => {\n assertIsHexString(value);\n\n // `parseInt` accepts values without the \"0x\"-prefix, whereas `Number` does\n // not. Using this is slightly faster than `Number(add0x(value))`.\n const numberValue = parseInt(value, 16);\n\n assert(\n Number.isSafeInteger(numberValue),\n 'Value is not a safe integer. Use `hexToBigInt` instead.',\n );\n\n return numberValue;\n};\n\n/**\n * Convert a hexadecimal string to a `bigint`. This verifies that the string is\n * a valid hex string. Both \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a number instead, use {@link hexToNumber}.\n *\n * @example\n * ```typescript\n * hexToBigInt('0x0'); // 0n\n * hexToBigInt('0x1'); // 1n\n * hexToBigInt('0x10'); // 16n\n * ```\n * @param value - The hexadecimal string to convert to a `bigint`.\n * @returns The `bigint`.\n * @throws If the value is not a valid hexadecimal string.\n */\nexport const hexToBigInt = (value: string): bigint => {\n assertIsHexString(value);\n\n // The `BigInt` constructor requires the \"0x\"-prefix to parse a hex string.\n return BigInt(add0x(value));\n};\n","/**\n * Common duration constants, in milliseconds.\n */\nexport enum Duration {\n /**\n * A millisecond.\n */\n Millisecond = 1,\n\n /**\n * A second, in milliseconds.\n */\n Second = 1000, // Millisecond * 1000\n\n /**\n * A minute, in milliseconds.\n */\n Minute = 60_000, // Second * 60\n\n /**\n * An hour, in milliseconds.\n */\n Hour = 3_600_000, // Minute * 60\n\n /**\n * A day, in milliseconds.\n */\n Day = 86_400_000, // Hour * 24\n\n /**\n * A week, in milliseconds.\n */\n Week = 604_800_000, // Day * 7\n\n /**\n * A year, in milliseconds.\n */\n Year = 31_536_000_000, // Day * 365\n}\n\nconst isNonNegativeInteger = (number: number) =>\n Number.isInteger(number) && number >= 0;\n\nconst assertIsNonNegativeInteger = (number: number, name: string) => {\n if (!isNonNegativeInteger(number)) {\n throw new Error(\n `\"${name}\" must be a non-negative integer. Received: \"${number}\".`,\n );\n }\n};\n\n/**\n * Calculates the millisecond value of the specified number of units of time.\n *\n * @param count - The number of units of time.\n * @param duration - The unit of time to count.\n * @returns The count multiplied by the specified duration.\n */\nexport function inMilliseconds(count: number, duration: Duration): number {\n assertIsNonNegativeInteger(count, 'count');\n return count * duration;\n}\n\n/**\n * Gets the milliseconds since a particular Unix epoch timestamp.\n *\n * @param timestamp - A Unix millisecond timestamp.\n * @returns The number of milliseconds elapsed since the specified timestamp.\n */\nexport function timeSince(timestamp: number): number {\n assertIsNonNegativeInteger(timestamp, 'timestamp');\n return Date.now() - timestamp;\n}\n","import {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport { is, refine, string, Struct } from 'superstruct';\n\nimport { assertStruct } from './assert';\nimport { Opaque } from './opaque';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine(\n string() as unknown as Struct,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine(\n string() as unknown as Struct,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha implements ChaCha stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of ChaCha rounds (ChaCha20).\nconst ROUNDS = 20;\n\n// Applies the ChaCha core function to 16-byte input,\n// 32-byte key key, and puts the result into 64-byte array out.\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\" -- ChaCha's \"sigma\" constant\n let j1 = 0x3320646E; // \"nd 3\" for 32-byte keys\n let j2 = 0x79622D32; // \"2-by\"\n let j3 = 0x6B206574; // \"te k\"\n let j4 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j5 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j6 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j7 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j8 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j9 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j10 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j11 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j12 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j13 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j14 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j15 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 16) | x12 << 16;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 12) | x4 << 12;\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 16) | x13 << 16;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 12) | x5 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 16) | x14 << 16;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 12) | x6 << 12;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 16) | x15 << 16;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 12) | x7 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 8) | x14 << 8;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 7) | x6 << 7;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 8) | x15 << 8;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 7) | x7 << 7;\n\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 8) | x13 << 8;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 7) | x5 << 7;\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 8) | x12 << 8;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 16) | x15 << 16;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 12) | x5 << 12;\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 16) | x12 << 16;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 12) | x6 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 16) | x13 << 16;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 12) | x7 << 12;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 16) | x14 << 16;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 12) | x4 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 8) | x13 << 8;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 7) | x7 << 7;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 8) | x14 << 8;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 8) | x12 << 8;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 7) | x6 << 7;\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 8) | x15 << 8;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 7) | x5 << 7;\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with ChaCha20 stream generated for the given 32-byte key and\n * 8-byte (as in original implementation) or 12-byte (as in RFC7539) nonce and\n * write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * If nonce is 12 bytes, users should not encrypt more than 256 GiB with the\n * same key and nonce, otherwise the stream will repeat. The function will\n * throw error if counter overflows to prevent this.\n *\n * If nonce is 8 bytes, the output is practically unlimited (2^70 bytes, which\n * is more than a million petabytes). However, it is not recommended to\n * generate 8-byte nonces randomly, as the chance of collision is high.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each ChaCha block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"ChaCha: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"ChaCha: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterLength: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8 && nonce.length !== 12) {\n throw new Error(\"ChaCha nonce must be 8 or 12 bytes\");\n }\n nc = new Uint8Array(16);\n // First counterLength bytes of nc are counter, starting with zero.\n counterLength = nc.length - nonce.length;\n // Last bytes of nc after counterLength are nonce, set them.\n nc.set(nonce, counterLength);\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"ChaCha nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterLength = nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for ChaCha block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, 0, counterLength);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate ChaCha20 stream for the given 32-byte key and 8-byte or 12-byte\n * nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same with respect to\n * the nonce as described in the streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"ChaCha: counter overflow\");\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha20poly1305 implements ChaCha20-Poly1305 AEAD.\n */\n\nimport { AEAD } from \"@stablelib/aead\";\nimport { streamXOR, stream } from \"@stablelib/chacha\";\nimport { Poly1305 } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { writeUint64LE } from \"@stablelib/binary\";\nimport { equal } from \"@stablelib/constant-time\";\n\nexport const KEY_LENGTH = 32;\nexport const NONCE_LENGTH = 12;\nexport const TAG_LENGTH = 16;\n\nconst ZEROS = new Uint8Array(16);\n\n/**\n * ChaCha20-Poly1305 Authenticated Encryption with Associated Data.\n *\n * Defined in RFC7539.\n */\nexport class ChaCha20Poly1305 implements AEAD {\n readonly nonceLength = NONCE_LENGTH;\n readonly tagLength = TAG_LENGTH;\n\n private _key: Uint8Array;\n\n /**\n * Creates a new instance with the given 32-byte key.\n */\n constructor(key: Uint8Array) {\n if (key.length !== KEY_LENGTH) {\n throw new Error(\"ChaCha20Poly1305 needs 32-byte key\");\n }\n // Copy key.\n this._key = new Uint8Array(key);\n }\n\n /**\n * Encrypts and authenticates plaintext, authenticates associated data,\n * and returns sealed ciphertext, which includes authentication tag.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If dst is given (it must be the size of plaintext + the size of tag\n * length) the result will be put into it. Dst and plaintext must not\n * overlap.\n */\n seal(nonce: Uint8Array, plaintext: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n // We pass full counter, which has 12-byte nonce and 4-byte block counter,\n // and it will get incremented after generating the block, which is\n // exactly what we need: we only use the first 32 bytes of 64-byte\n // ChaCha block and discard the next 32 bytes.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Allocate space for sealed ciphertext.\n const resultLength = plaintext.length + this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Encrypt plaintext.\n streamXOR(this._key, counter, plaintext, result, 4);\n\n // Authenticate.\n // XXX: can \"simplify\" here: pass full result (which is already padded\n // due to zeroes prepared for tag), and ciphertext length instead of\n // subarray of result.\n this._authenticate(result.subarray(result.length - this.tagLength, result.length),\n authKey, result.subarray(0, result.length - this.tagLength), associatedData);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n /**\n * Authenticates sealed ciphertext (which includes authentication tag) and\n * associated data, decrypts ciphertext and returns decrypted plaintext.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If authentication fails, it returns null.\n *\n * If dst is given (it must be of ciphertext length minus tag length),\n * the result will be put into it. Dst and plaintext must not overlap.\n */\n open(nonce: Uint8Array, sealed: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array | null {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Sealed ciphertext should at least contain tag.\n if (sealed.length < this.tagLength) {\n // TODO(dchest): should we throw here instead?\n return null;\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Authenticate.\n // XXX: can simplify and avoid allocation: since authenticate()\n // already allocates tag (from Poly1305.digest(), it can return)\n // it instead of copying to calculatedTag. But then in seal()\n // we'll need to copy it.\n const calculatedTag = new Uint8Array(this.tagLength);\n this._authenticate(calculatedTag, authKey,\n sealed.subarray(0, sealed.length - this.tagLength), associatedData);\n\n // Constant-time compare tags and return null if they differ.\n if (!equal(calculatedTag,\n sealed.subarray(sealed.length - this.tagLength, sealed.length))) {\n return null;\n }\n\n // Allocate space for decrypted plaintext.\n const resultLength = sealed.length - this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Decrypt.\n streamXOR(this._key, counter,\n sealed.subarray(0, sealed.length - this.tagLength), result, 4);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n clean(): this {\n wipe(this._key);\n return this;\n }\n\n private _authenticate(tagOut: Uint8Array, authKey: Uint8Array,\n ciphertext: Uint8Array, associatedData?: Uint8Array) {\n\n // Initialize Poly1305 with authKey.\n const h = new Poly1305(authKey);\n\n // Authenticate padded associated data.\n if (associatedData) {\n h.update(associatedData);\n if (associatedData.length % 16 > 0) {\n h.update(ZEROS.subarray(associatedData.length % 16));\n }\n }\n\n // Authenticate padded ciphertext.\n h.update(ciphertext);\n if (ciphertext.length % 16 > 0) {\n h.update(ZEROS.subarray(ciphertext.length % 16));\n }\n\n // Authenticate length of associated data.\n // XXX: can avoid allocation here?\n const length = new Uint8Array(8);\n if (associatedData) {\n writeUint64LE(associatedData.length, length);\n }\n h.update(length);\n\n // Authenticate length of ciphertext.\n writeUint64LE(ciphertext.length, length);\n h.update(length);\n\n // Get tag and copy it into tagOut.\n const tag = h.digest();\n for (let i = 0; i < tag.length; i++) {\n tagOut[i] = tag[i];\n }\n\n // Cleanup.\n h.clean();\n wipe(tag);\n wipe(length);\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package ed25519 implements Ed25519 public-key signature algorithm.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { hash, SHA512 } from \"@stablelib/sha512\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const SIGNATURE_LENGTH = 64;\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\nexport const SEED_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../kex/x25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which was ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst gf0 = gf();\n\nconst gf1 = gf([1]);\n\nconst D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203\n]);\n\nconst D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406\n]);\n\nconst X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169\n]);\n\nconst Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666\n]);\n\nconst I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83\n]);\n\nfunction set25519(r: GF, a: GF) {\n for (let i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let 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\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n 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 const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n 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\nfunction verify32(x: Uint8Array, y: Uint8Array) {\n let d = 0;\n for (let i = 0; i < 32; i++) {\n d |= x[i] ^ y[i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\n\nfunction neq25519(a: GF, b: GF) {\n const c = new Uint8Array(32);\n const d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return verify32(c, d);\n}\n\nfunction par25519(a: GF) {\n const d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\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\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\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\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\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, i: GF) {\n const c = gf();\n let a: number;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 253; a >= 0; a--) {\n square(c, c);\n if (a !== 2 && a !== 4) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\n\nfunction pow2523(o: GF, i: GF) {\n const c = gf();\n let a: number;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 250; a >= 0; a--) {\n square(c, c);\n if (a !== 1) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\n\n\nfunction edadd(p: GF[], q: GF[]) {\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n sub(a, p[1], p[0]);\n sub(t, q[1], q[0]);\n mul(a, a, t);\n add(b, p[0], p[1]);\n add(t, q[0], q[1]);\n mul(b, b, t);\n mul(c, p[3], q[3]);\n mul(c, c, D2);\n mul(d, p[2], q[2]);\n add(d, d, d);\n sub(e, b, a);\n sub(f, d, c);\n add(g, d, c);\n add(h, b, a);\n\n mul(p[0], e, f);\n mul(p[1], h, g);\n mul(p[2], g, f);\n mul(p[3], e, h);\n}\n\nfunction cswap(p: GF[], q: GF[], b: number) {\n for (let i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r: Uint8Array, p: GF[]) {\n const tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n mul(tx, p[0], zi);\n mul(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p: GF[], q: GF[], s: Uint8Array) {\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (let i = 255; i >= 0; --i) {\n const b = (s[(i / 8) | 0] >> (i & 7)) & 1;\n cswap(p, q, b);\n edadd(q, p);\n edadd(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p: GF[], s: Uint8Array) {\n const q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n mul(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n// Generates key pair from secret 32-byte seed.\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SEED_LENGTH) {\n throw new Error(`ed25519: seed must be ${SEED_LENGTH} bytes`);\n }\n\n const d = hash(seed);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n const publicKey = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n scalarbase(p, d);\n pack(publicKey, p);\n\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\nexport function extractPublicKeyFromSecretKey(secretKey: Uint8Array): Uint8Array {\n if (secretKey.length !== SECRET_KEY_LENGTH) {\n throw new Error(`ed25519: secret key must be ${SECRET_KEY_LENGTH} bytes`);\n }\n return new Uint8Array(secretKey.subarray(32));\n}\n\nconst L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2,\n 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10\n]);\n\nfunction modL(r: Uint8Array, x: Float64Array) {\n let carry: number;\n let i: number;\n let j: number;\n let k: number;\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] * 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) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) {\n x[j] -= carry * L[j];\n }\n for (i = 0; i < 32; i++) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r: Uint8Array) {\n const x = new Float64Array(64);\n for (let i = 0; i < 64; i++) {\n x[i] = r[i];\n }\n for (let i = 0; i < 64; i++) {\n r[i] = 0;\n }\n modL(r, x);\n}\n\n// Returns 64-byte signature of the message under the 64-byte secret key.\nexport function sign(secretKey: Uint8Array, message: Uint8Array): Uint8Array {\n const x = new Float64Array(64);\n const p = [gf(), gf(), gf(), gf()];\n\n const d = hash(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n const signature = new Uint8Array(64);\n signature.set(d.subarray(32), 32);\n\n const hs = new SHA512();\n hs.update(signature.subarray(32));\n hs.update(message);\n const r = hs.digest();\n hs.clean();\n reduce(r);\n scalarbase(p, r);\n pack(signature, p);\n\n hs.reset();\n hs.update(signature.subarray(0, 32));\n hs.update(secretKey.subarray(32));\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n\n for (let i = 0; i < 32; i++) {\n x[i] = r[i];\n }\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 modL(signature.subarray(32), x);\n\n return signature;\n}\n\nfunction unpackneg(r: GF[], p: Uint8Array) {\n const t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n square(num, r[1]);\n mul(den, num, D);\n sub(num, num, r[2]);\n add(den, r[2], den);\n\n square(den2, den);\n square(den4, den2);\n mul(den6, den4, den2);\n mul(t, den6, num);\n mul(t, t, den);\n\n pow2523(t, t);\n mul(t, t, num);\n mul(t, t, den);\n mul(t, t, den);\n mul(r[0], t, den);\n\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n mul(r[0], r[0], I);\n }\n\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n return -1;\n }\n\n if (par25519(r[0]) === (p[31] >> 7)) {\n sub(r[0], gf0, r[0]);\n }\n\n mul(r[3], r[0], r[1]);\n return 0;\n}\n\nexport function verify(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean {\n const t = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n const q = [gf(), gf(), gf(), gf()];\n\n if (signature.length !== SIGNATURE_LENGTH) {\n throw new Error(`ed25519: signature must be ${SIGNATURE_LENGTH} bytes`);\n }\n\n if (unpackneg(q, publicKey)) {\n return false;\n }\n\n const hs = new SHA512();\n hs.update(signature.subarray(0, 32));\n hs.update(publicKey);\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, signature.subarray(32));\n edadd(p, q);\n pack(t, p);\n\n if (verify32(signature, t)) {\n return false;\n }\n return true;\n}\n\n/**\n * Convert Ed25519 public key to X25519 public key.\n *\n * Throws if given an invalid public key.\n */\nexport function convertPublicKeyToX25519(publicKey: Uint8Array): Uint8Array {\n let q = [gf(), gf(), gf(), gf()];\n\n if (unpackneg(q, publicKey)) {\n throw new Error(\"Ed25519: invalid public key\");\n }\n\n // Formula: montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p\n let a = gf();\n let b = gf();\n let y = q[1];\n add(a, gf1, y);\n sub(b, gf1, y);\n inv25519(b, b);\n mul(a, a, b);\n\n let z = new Uint8Array(32);\n pack25519(z, a);\n return z;\n}\n\n/**\n * Convert Ed25519 secret (private) key to X25519 secret key.\n */\nexport function convertSecretKeyToX25519(secretKey: Uint8Array): Uint8Array {\n const d = hash(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const o = new Uint8Array(d.subarray(0, 32));\n wipe(d);\n return o;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hash provides interface for hash functions.\n */\n\n/**\n * Hash interface describes properties of\n * cryptographic hash functions.\n */\nexport interface Hash {\n readonly digestLength: number;\n readonly blockSize: number;\n update(data: Uint8Array): this;\n reset(): this;\n finish(out: Uint8Array): this;\n digest(): Uint8Array;\n clean(): void;\n}\n\nexport interface SerializableHash extends Hash {\n saveState(): any;\n restoreState(savedState: any): this;\n cleanSavedState(savedState: any): void;\n}\n\nexport function isSerializableHash(h: Hash): h is SerializableHash {\n return (\n typeof (h as SerializableHash).saveState !== \"undefined\" &&\n typeof (h as SerializableHash).restoreState !== \"undefined\" &&\n typeof (h as SerializableHash).cleanSavedState !== \"undefined\"\n );\n}\n\n// TODO(dchest): figure out the standardized interface for XOF such as\n// SHAKE and BLAKE2X.\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hkdf implements HKDF key derivation function.\n */\n\nimport { Hash } from \"@stablelib/hash\";\nimport { HMAC, hmac } from \"@stablelib/hmac\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC-based Extract-and-Expand Key Derivation Function.\n *\n * Implements HKDF from RFC5869.\n *\n * Expands the given master key with salt and info into\n * a limited stream of key material.\n */\nexport class HKDF {\n private _hmac: HMAC;\n private _buffer: Uint8Array;\n private _bufpos: number;\n private _counter = new Uint8Array(1); // starts with zero\n private _hash: new () => Hash;\n private _info?: Uint8Array;\n\n /**\n * Create a new HKDF instance for the given hash function\n * with the master key, optional salt, and info.\n *\n * - Master key is a high-entropy secret key (not a password).\n * - Salt is a non-secret random value.\n * - Info is application- and/or context-specific information.\n */\n constructor(hash: new () => Hash,\n key: Uint8Array,\n salt = new Uint8Array(0),\n info?: Uint8Array) {\n\n this._hash = hash;\n this._info = info;\n\n // HKDF-Extract uses salt as HMAC key, and key as data.\n const okm = hmac(this._hash, salt, key);\n\n // Initialize HMAC for expanding with extracted key.\n this._hmac = new HMAC(hash, okm);\n\n // Allocate buffer.\n this._buffer = new Uint8Array(this._hmac.digestLength);\n this._bufpos = this._buffer.length;\n }\n\n // Fill buffer with new block of HKDF-Extract output.\n private _fillBuffer(): void {\n // Increment counter.\n this._counter[0]++;\n\n const ctr = this._counter[0];\n\n // Check if counter overflowed.\n if (ctr === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n\n // Prepare HMAC instance for new data with old key.\n this._hmac.reset();\n\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (ctr > 1) {\n this._hmac.update(this._buffer);\n }\n\n // Hash in info if it exists.\n if (this._info) {\n this._hmac.update(this._info);\n }\n\n // Hash in the counter.\n this._hmac.update(this._counter);\n\n // Output result to buffer and clean HMAC instance.\n this._hmac.finish(this._buffer);\n\n // Reset buffer position.\n this._bufpos = 0;\n }\n\n /**\n * Expand returns next key material of the given length.\n *\n * It throws if expansion limit is reached (which is\n * 254 digests of the underlying HMAC function).\n */\n expand(length: number): Uint8Array {\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i++) {\n if (this._bufpos === this._buffer.length) {\n this._fillBuffer();\n }\n out[i] = this._buffer[this._bufpos++];\n }\n return out;\n }\n\n clean(): void {\n this._hmac.clean();\n wipe(this._buffer);\n wipe(this._counter);\n this._bufpos = 0;\n }\n}\n\n// TODO(dchest): maybe implement deriveKey?\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hmac implements HMAC algorithm.\n */\n\nimport { Hash, SerializableHash, isSerializableHash } from \"@stablelib/hash\";\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC implements hash-based message authentication algorithm.\n */\nexport class HMAC implements SerializableHash {\n readonly blockSize: number;\n readonly digestLength: number;\n\n private _inner: Hash; // inner hash\n private _outer: Hash; // outer hash\n\n private _finished = false; // true if HMAC was finalized\n\n // Copies of hash states after keying.\n // Need for quick reset without hashing the key again.\n private _innerKeyedState: any | undefined;\n private _outerKeyedState: any | undefined;\n\n /**\n * Constructs a new HMAC with the given Hash and secret key.\n */\n constructor(hash: new () => Hash | SerializableHash, key: Uint8Array) {\n // Initialize inner and outer hashes.\n this._inner = new hash();\n this._outer = new hash();\n\n // Set block and digest sizes for this HMAC\n // instance to values from the hash.\n this.blockSize = this._outer.blockSize;\n this.digestLength = this._outer.digestLength;\n\n // Pad temporary stores a key (or its hash) padded with zeroes.\n const pad = new Uint8Array(this.blockSize);\n\n if (key.length > this.blockSize) {\n // If key is bigger than hash block size, it must be\n // hashed and this hash is used as a key instead.\n this._inner.update(key).finish(pad).clean();\n } else {\n // Otherwise, copy the key into pad.\n pad.set(key);\n }\n\n // Now two different keys are derived from padded key\n // by xoring a different byte value to each.\n\n // To make inner hash key, xor byte 0x36 into pad.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n // Update inner hash with the result.\n this._inner.update(pad);\n\n // To make outer hash key, xor byte 0x5c into pad.\n // But since we already xored 0x36 there, we must\n // first undo this by xoring it again.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n // Update outer hash with the result.\n this._outer.update(pad);\n\n // Save states of both hashes, so that we can quickly restore\n // them later in reset() without the need to remember the actual\n // key and perform this initialization again.\n if (isSerializableHash(this._inner) && isSerializableHash(this._outer)) {\n this._innerKeyedState = this._inner.saveState();\n this._outerKeyedState = this._outer.saveState();\n }\n\n // Clean pad.\n wipe(pad);\n }\n\n /**\n * Returns HMAC state to the state initialized with key\n * to make it possible to run HMAC over the other data with the same\n * key without creating a new instance.\n */\n reset(): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't reset() because hash doesn't implement restoreState()\");\n }\n // Restore keyed states of inner and outer hashes.\n this._inner.restoreState(this._innerKeyedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans HMAC state.\n */\n clean() {\n if (isSerializableHash(this._inner)) {\n this._inner.cleanSavedState(this._innerKeyedState);\n }\n if (isSerializableHash(this._outer)) {\n this._outer.cleanSavedState(this._outerKeyedState);\n }\n this._inner.clean();\n this._outer.clean();\n }\n\n /**\n * Updates state with provided data.\n */\n update(data: Uint8Array): this {\n this._inner.update(data);\n return this;\n }\n\n /**\n * Finalizes HMAC and puts the result in out.\n */\n finish(out: Uint8Array): this {\n if (this._finished) {\n // If HMAC was finalized, outer hash is also finalized,\n // so it produces the same digest it produced when it\n // was finalized.\n this._outer.finish(out);\n return this;\n }\n\n // Finalize inner hash and store the result temporarily.\n this._inner.finish(out);\n\n // Update outer hash with digest of inner hash and and finalize it.\n this._outer.update(out.subarray(0, this.digestLength)).finish(out);\n this._finished = true;\n\n return this;\n }\n\n /**\n * Returns the computed message authentication code.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Saves HMAC state.\n * This function is needed for PBKDF2 optimization.\n */\n saveState(): any {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't saveState() because hash doesn't implement it\");\n }\n return this._inner.saveState();\n }\n\n restoreState(savedState: any): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't restoreState() because hash doesn't implement it\");\n }\n this._inner.restoreState(savedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n cleanSavedState(savedState: any) {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't cleanSavedState() because hash doesn't implement it\");\n }\n this._inner.cleanSavedState(savedState);\n }\n}\n\n/**\n * Returns HMAC using the given hash constructor for the key over data.\n */\nexport function hmac(hash: new () => Hash, key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new HMAC(hash, key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two HMAC digests are equal.\n * Uses constant-time comparison to avoid leaking timing information.\n *\n * Example:\n *\n * const receivedDigest = ...\n * const realDigest = hmac(SHA256, key, data);\n * if (!equal(receivedDigest, realDigest)) {\n * throw new Error(\"Authentication error\");\n * }\n */\nexport const equal = constantTimeEqual;\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished — others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha256 implements SHA-2-256 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 32;\nexport const BLOCK_SIZE = 64;\n\n/**\n * SHA2-256 cryptographic hash algorithm.\n */\nexport class SHA256 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _state = new Int32Array(8); // hash state\n private _temp = new Int32Array(64); // temporary state\n private _buffer = new Uint8Array(128); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._state[0] = 0x6a09e667;\n this._state[1] = 0xbb67ae85;\n this._state[2] = 0x3c6ef372;\n this._state[3] = 0xa54ff53a;\n this._state[4] = 0x510e527f;\n this._state[5] = 0x9b05688c;\n this._state[6] = 0x1f83d9ab;\n this._state[7] = 0x5be0cd19;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._temp);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < this.blockSize && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._temp, this._state, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 4; i++) {\n writeUint32BE(this._state[i], out, i * 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Returns hash state to be used with restoreState().\n * Only chain value is saved, not buffers or other\n * state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n state: new Int32Array(this._state),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Restores state saved by saveState() and sets bytesHashed\n * to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._state.set(savedState.state);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.state);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n state: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\nfunction hashBlocks(w: Int32Array, v: Int32Array, p: Uint8Array, pos: number, len: number): number {\n while (len >= 64) {\n let a = v[0];\n let b = v[1];\n let c = v[2];\n let d = v[3];\n let e = v[4];\n let f = v[5];\n let g = v[6];\n let h = v[7];\n\n for (let i = 0; i < 16; i++) {\n let j = pos + i * 4;\n w[i] = readUint32BE(p, j);\n }\n\n for (let i = 16; i < 64; i++) {\n let u = w[i - 2];\n let t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n\n u = w[i - 15];\n let t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n\n for (let i = 0; i < 64; i++) {\n let t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n\n let t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n\n v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA256();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha512 implements SHA-2-512 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 64;\nexport const BLOCK_SIZE = 128;\n\n/**\n * SHA-2-512 cryptographic hash algorithm.\n */\nexport class SHA512 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _stateHi = new Int32Array(8); // hash state, high bytes\n protected _stateLo = new Int32Array(8); // hash state, low bytes\n private _tempHi = new Int32Array(16); // temporary state, high bytes\n private _tempLo = new Int32Array(16); // temporary state, low bytes\n private _buffer = new Uint8Array(256); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._stateHi[0] = 0x6a09e667;\n this._stateHi[1] = 0xbb67ae85;\n this._stateHi[2] = 0x3c6ef372;\n this._stateHi[3] = 0xa54ff53a;\n this._stateHi[4] = 0x510e527f;\n this._stateHi[5] = 0x9b05688c;\n this._stateHi[6] = 0x1f83d9ab;\n this._stateHi[7] = 0x5be0cd19;\n\n this._stateLo[0] = 0xf3bcc908;\n this._stateLo[1] = 0x84caa73b;\n this._stateLo[2] = 0xfe94f82b;\n this._stateLo[3] = 0x5f1d36f1;\n this._stateLo[4] = 0xade682d1;\n this._stateLo[5] = 0x2b3e6c1f;\n this._stateLo[6] = 0xfb41bd6b;\n this._stateLo[7] = 0x137e2179;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._tempHi);\n wipe(this._tempLo);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA512: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < BLOCK_SIZE && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo,\n this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo,\n data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 128 < 112) ? 128 : 256;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 8; i++) {\n writeUint32BE(this._stateHi[i], out, i * 8);\n writeUint32BE(this._stateLo[i], out, i * 8 + 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization. Returns hash state to be\n * used with restoreState(). Only chain value is saved, not buffers or\n * other state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n stateHi: new Int32Array(this._stateHi),\n stateLo: new Int32Array(this._stateLo),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization. Restores state saved by\n * saveState() and sets bytesHashed to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._stateHi.set(savedState.stateHi);\n this._stateLo.set(savedState.stateLo);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.stateHi);\n wipe(savedState.stateLo);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n stateHi: Int32Array;\n stateLo: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n]);\n\n\nfunction hashBlocks(wh: Int32Array, wl: Int32Array, hh: Int32Array, hl: Int32Array,\n m: Uint8Array, pos: number, len: number): number {\n\n let ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n let h: number, l: number;\n let th: number, tl: number;\n let a: number, b: number, c: number, d: number;\n\n while (len >= 128) {\n for (let i = 0; i < 16; i++) {\n const j = 8 * i + pos;\n wh[i] = readUint32BE(m, j);\n wl[i] = readUint32BE(m, j + 4);\n }\n for (let i = 0; i < 80; i++) {\n let bh0 = ah0;\n let bh1 = ah1;\n let bh2 = ah2;\n let bh3 = ah3;\n let bh4 = ah4;\n let bh5 = ah5;\n let bh6 = ah6;\n let bh7 = ah7;\n\n let bl0 = al0;\n let bl1 = al1;\n let bl2 = al2;\n let bl3 = al3;\n let bl4 = al4;\n let bl5 = al5;\n let bl6 = al6;\n let bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) |\n (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32))));\n l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) |\n (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i * 2];\n l = K[i * 2 + 1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i % 16];\n l = wl[i % 16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) |\n (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32))));\n l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) |\n (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i % 16 === 15) {\n for (let j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j + 9) % 16];\n l = wl[(j + 9) % 16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j + 1) % 16];\n tl = wl[(j + 1) % 16];\n h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) |\n (tl << (32 - 8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) |\n (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j + 14) % 16];\n tl = wl[(j + 14) % 16];\n h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) |\n (th << (32 - (61 - 32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) |\n (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n len -= 128;\n }\n\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA512();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let 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\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n 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 const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n 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\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\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\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\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\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\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n",null,null,null,"/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,"/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n",null,null,null,null,null,null,null,"/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Semaphore_1 = require(\"./Semaphore\");\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._semaphore = new Semaphore_1.default(1);\n }\n Mutex.prototype.acquire = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _a, releaser;\n return tslib_1.__generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this._semaphore.acquire()];\n case 1:\n _a = _b.sent(), releaser = _a[1];\n return [2 /*return*/, releaser];\n }\n });\n });\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this._semaphore.runExclusive(function () { return callback(); });\n };\n Mutex.prototype.isLocked = function () {\n return this._semaphore.isLocked();\n };\n Mutex.prototype.release = function () {\n this._semaphore.release();\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Semaphore = /** @class */ (function () {\n function Semaphore(_maxConcurrency) {\n this._maxConcurrency = _maxConcurrency;\n this._queue = [];\n if (_maxConcurrency <= 0) {\n throw new Error('semaphore must be initialized to a positive value');\n }\n this._value = _maxConcurrency;\n }\n Semaphore.prototype.acquire = function () {\n var _this = this;\n var locked = this.isLocked();\n var ticket = new Promise(function (r) { return _this._queue.push(r); });\n if (!locked)\n this._dispatch();\n return ticket;\n };\n Semaphore.prototype.runExclusive = function (callback) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _a, value, release;\n return tslib_1.__generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this.acquire()];\n case 1:\n _a = _b.sent(), value = _a[0], release = _a[1];\n _b.label = 2;\n case 2:\n _b.trys.push([2, , 4, 5]);\n return [4 /*yield*/, callback(value)];\n case 3: return [2 /*return*/, _b.sent()];\n case 4:\n release();\n return [7 /*endfinally*/];\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n Semaphore.prototype.isLocked = function () {\n return this._value <= 0;\n };\n Semaphore.prototype.release = function () {\n if (this._maxConcurrency > 1) {\n throw new Error('this method is unavailabel on semaphores with concurrency > 1; use the scoped release returned by acquire instead');\n }\n if (this._currentReleaser) {\n var releaser = this._currentReleaser;\n this._currentReleaser = undefined;\n releaser();\n }\n };\n Semaphore.prototype._dispatch = function () {\n var _this = this;\n var nextConsumer = this._queue.shift();\n if (!nextConsumer)\n return;\n var released = false;\n this._currentReleaser = function () {\n if (released)\n return;\n released = true;\n _this._value++;\n _this._dispatch();\n };\n nextConsumer([this._value--, this._currentReleaser]);\n };\n return Semaphore;\n}());\nexports.default = Semaphore;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.withTimeout = exports.Semaphore = exports.Mutex = void 0;\nvar Mutex_1 = require(\"./Mutex\");\nObject.defineProperty(exports, \"Mutex\", { enumerable: true, get: function () { return Mutex_1.default; } });\nvar Semaphore_1 = require(\"./Semaphore\");\nObject.defineProperty(exports, \"Semaphore\", { enumerable: true, get: function () { return Semaphore_1.default; } });\nvar withTimeout_1 = require(\"./withTimeout\");\nObject.defineProperty(exports, \"withTimeout\", { enumerable: true, get: function () { return withTimeout_1.withTimeout; } });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.withTimeout = void 0;\nvar tslib_1 = require(\"tslib\");\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction withTimeout(sync, timeout, timeoutError) {\n var _this = this;\n if (timeoutError === void 0) { timeoutError = new Error('timeout'); }\n return {\n acquire: function () {\n return new Promise(function (resolve, reject) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var isTimeout, ticket, release;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n isTimeout = false;\n setTimeout(function () {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n return [4 /*yield*/, sync.acquire()];\n case 1:\n ticket = _a.sent();\n if (isTimeout) {\n release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n resolve(ticket);\n }\n return [2 /*return*/];\n }\n });\n }); });\n },\n runExclusive: function (callback) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var release, ticket;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n release = function () { return undefined; };\n _a.label = 1;\n case 1:\n _a.trys.push([1, , 7, 8]);\n return [4 /*yield*/, this.acquire()];\n case 2:\n ticket = _a.sent();\n if (!Array.isArray(ticket)) return [3 /*break*/, 4];\n release = ticket[1];\n return [4 /*yield*/, callback(ticket[0])];\n case 3: return [2 /*return*/, _a.sent()];\n case 4:\n release = ticket;\n return [4 /*yield*/, callback()];\n case 5: return [2 /*return*/, _a.sent()];\n case 6: return [3 /*break*/, 8];\n case 7:\n release();\n return [7 /*endfinally*/];\n case 8: return [2 /*return*/];\n }\n });\n });\n },\n release: function () {\n sync.release();\n },\n isLocked: function () { return sync.isLocked(); },\n };\n}\nexports.withTimeout = withTimeout;\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)0,p<=y.r||!y.r){p<=1&&c>0&&(y=h[c-1]);var v=l[y.l];u&&(p=u(\"\"+p)),a=\"string\"==typeof v?v.replace(\"%d\",p):v(p,n,y.l,s);break}}if(n)return a;var M=s?l.future:l.past;return\"function\"==typeof M?M(a):M.replace(\"%s\",a)},n.to=function(r,e){return i(r,e,this,!0)},n.from=function(r,e){return i(r,e,this)};var d=function(r){return r.$u?t.utc():t()};n.toNow=function(r){return this.to(d(this),r)},n.fromNow=function(r){return this.from(d(this),r)}}}));","!function(e,n){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=n():\"function\"==typeof define&&define.amd?define(n):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_updateLocale=n()}(this,(function(){\"use strict\";return function(e,n,t){t.updateLocale=function(e,n){var o=t.Ls[e];if(o)return(n?Object.keys(n):[]).forEach((function(e){o[e]=n[e]})),o}}}));","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","'use strict';\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn [decodeURIComponent(components.join(''))];\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher) || [];\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher) || [];\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n","'use strict';\n\n/******************************************************************************\n * Created 2008-08-19.\n *\n * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.\n *\n * Copyright (C) 2008\n * Wyatt Baldwin \n * All rights reserved\n *\n * Licensed under the MIT license.\n *\n * http://www.opensource.org/licenses/mit-license.php\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *****************************************************************************/\nvar dijkstra = {\n single_source_shortest_paths: function(graph, s, d) {\n // Predecessor map for each node that has been encountered.\n // node ID => predecessor node ID\n var predecessors = {};\n\n // Costs of shortest paths from s to all nodes encountered.\n // node ID => cost\n var costs = {};\n costs[s] = 0;\n\n // Costs of shortest paths from s to all nodes encountered; differs from\n // `costs` in that it provides easy access to the node that currently has\n // the known shortest path from s.\n // XXX: Do we actually need both `costs` and `open`?\n var open = dijkstra.PriorityQueue.make();\n open.push(s, 0);\n\n var closest,\n u, v,\n cost_of_s_to_u,\n adjacent_nodes,\n cost_of_e,\n cost_of_s_to_u_plus_cost_of_e,\n cost_of_s_to_v,\n first_visit;\n while (!open.empty()) {\n // In the nodes remaining in graph that have a known cost from s,\n // find the node, u, that currently has the shortest path from s.\n closest = open.pop();\n u = closest.value;\n cost_of_s_to_u = closest.cost;\n\n // Get nodes adjacent to u...\n adjacent_nodes = graph[u] || {};\n\n // ...and explore the edges that connect u to those nodes, updating\n // the cost of the shortest paths to any or all of those nodes as\n // necessary. v is the node across the current edge from u.\n for (v in adjacent_nodes) {\n if (adjacent_nodes.hasOwnProperty(v)) {\n // Get the cost of the edge running from u to v.\n cost_of_e = adjacent_nodes[v];\n\n // Cost of s to u plus the cost of u to v across e--this is *a*\n // cost from s to v that may or may not be less than the current\n // known cost to v.\n cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;\n\n // If we haven't visited v yet OR if the current known cost from s to\n // v is greater than the new cost we just found (cost of s to u plus\n // cost of u to v across e), update v's cost in the cost list and\n // update v's predecessor in the predecessor list (it's now u).\n cost_of_s_to_v = costs[v];\n first_visit = (typeof costs[v] === 'undefined');\n if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {\n costs[v] = cost_of_s_to_u_plus_cost_of_e;\n open.push(v, cost_of_s_to_u_plus_cost_of_e);\n predecessors[v] = u;\n }\n }\n }\n }\n\n if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {\n var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');\n throw new Error(msg);\n }\n\n return predecessors;\n },\n\n extract_shortest_path_from_predecessor_list: function(predecessors, d) {\n var nodes = [];\n var u = d;\n var predecessor;\n while (u) {\n nodes.push(u);\n predecessor = predecessors[u];\n u = predecessors[u];\n }\n nodes.reverse();\n return nodes;\n },\n\n find_path: function(graph, s, d) {\n var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);\n return dijkstra.extract_shortest_path_from_predecessor_list(\n predecessors, d);\n },\n\n /**\n * A very naive priority queue implementation.\n */\n PriorityQueue: {\n make: function (opts) {\n var T = dijkstra.PriorityQueue,\n t = {},\n key;\n opts = opts || {};\n for (key in T) {\n if (T.hasOwnProperty(key)) {\n t[key] = T[key];\n }\n }\n t.queue = [];\n t.sorter = opts.sorter || T.default_sorter;\n return t;\n },\n\n default_sorter: function (a, b) {\n return a.cost - b.cost;\n },\n\n /**\n * Add a new item to the queue and ensure the highest priority element\n * is at the front of the queue.\n */\n push: function (value, cost) {\n var item = {value: value, cost: cost};\n this.queue.push(item);\n this.queue.sort(this.sorter);\n },\n\n /**\n * Return the highest priority element in the queue.\n */\n pop: function () {\n return this.queue.shift();\n },\n\n empty: function () {\n return this.queue.length === 0;\n }\n }\n};\n\n\n// node.js module exports\nif (typeof module !== 'undefined') {\n module.exports = dijkstra;\n}\n","'use strict'\n\nmodule.exports = function encodeUtf8 (input) {\n var result = []\n var size = input.length\n\n for (var index = 0; index < size; index++) {\n var point = input.charCodeAt(index)\n\n if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) {\n var second = input.charCodeAt(index + 1)\n\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n index += 1\n }\n }\n\n // US-ASCII\n if (point < 0x80) {\n result.push(point)\n continue\n }\n\n // 2-byte UTF-8\n if (point < 0x800) {\n result.push((point >> 6) | 192)\n result.push((point & 63) | 128)\n continue\n }\n\n // 3-byte UTF-8\n if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) {\n result.push((point >> 12) | 224)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // 4-byte UTF-8\n if (point >= 0x10000 && point <= 0x10FFFF) {\n result.push((point >> 18) | 240)\n result.push(((point >> 12) & 63) | 128)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // Invalid character\n result.push(0xEF, 0xBF, 0xBD)\n }\n\n return new Uint8Array(result).buffer\n}\n","import SafeEventEmitter from '@metamask/safe-event-emitter';\n\nconst sec = 1000;\n\nconst calculateSum = (accumulator: number, currentValue: number) =>\n accumulator + currentValue;\nconst blockTrackerEvents: (string | symbol)[] = ['sync', 'latest'];\n\ninterface BaseBlockTrackerArgs {\n blockResetDuration?: number;\n usePastBlocks?: boolean;\n}\n\nexport abstract class BaseBlockTracker extends SafeEventEmitter {\n protected _isRunning: boolean;\n\n private _blockResetDuration: number;\n\n private _usePastBlocks: boolean;\n\n private _currentBlock: string | null;\n\n private _blockResetTimeout?: ReturnType;\n\n constructor(opts: BaseBlockTrackerArgs) {\n super();\n\n // config\n this._blockResetDuration = opts.blockResetDuration || 20 * sec;\n this._usePastBlocks = opts.usePastBlocks || false;\n // state\n this._currentBlock = null;\n this._isRunning = false;\n\n // bind functions for internal use\n this._onNewListener = this._onNewListener.bind(this);\n this._onRemoveListener = this._onRemoveListener.bind(this);\n this._resetCurrentBlock = this._resetCurrentBlock.bind(this);\n\n // listen for handler changes\n this._setupInternalEvents();\n }\n\n async destroy() {\n this._cancelBlockResetTimeout();\n await this._maybeEnd();\n super.removeAllListeners();\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n getCurrentBlock(): string | null {\n return this._currentBlock;\n }\n\n async getLatestBlock(): Promise {\n // return if available\n if (this._currentBlock) {\n return this._currentBlock;\n }\n // wait for a new latest block\n const latestBlock: string = await new Promise((resolve) =>\n this.once('latest', resolve),\n );\n // return newly set current block\n return latestBlock;\n }\n\n // dont allow module consumer to remove our internal event listeners\n removeAllListeners(eventName?: string | symbol) {\n // perform default behavior, preserve fn arity\n if (eventName) {\n super.removeAllListeners(eventName);\n } else {\n super.removeAllListeners();\n }\n\n // re-add internal events\n this._setupInternalEvents();\n // trigger stop check just in case\n this._onRemoveListener();\n\n return this;\n }\n\n /**\n * To be implemented in subclass.\n */\n protected abstract _start(): Promise;\n\n /**\n * To be implemented in subclass.\n */\n protected abstract _end(): Promise;\n\n private _setupInternalEvents(): void {\n // first remove listeners for idempotence\n this.removeListener('newListener', this._onNewListener);\n this.removeListener('removeListener', this._onRemoveListener);\n // then add them\n this.on('newListener', this._onNewListener);\n this.on('removeListener', this._onRemoveListener);\n }\n\n private _onNewListener(eventName: string | symbol): void {\n // `newListener` is called *before* the listener is added\n if (blockTrackerEvents.includes(eventName)) {\n this._maybeStart();\n }\n }\n\n private _onRemoveListener(): void {\n // `removeListener` is called *after* the listener is removed\n if (this._getBlockTrackerEventCount() > 0) {\n return;\n }\n this._maybeEnd();\n }\n\n private async _maybeStart(): Promise {\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // cancel setting latest block to stale\n this._cancelBlockResetTimeout();\n await this._start();\n this.emit('_started');\n }\n\n private async _maybeEnd(): Promise {\n if (!this._isRunning) {\n return;\n }\n this._isRunning = false;\n this._setupBlockResetTimeout();\n await this._end();\n this.emit('_ended');\n }\n\n private _getBlockTrackerEventCount(): number {\n return blockTrackerEvents\n .map((eventName) => this.listenerCount(eventName))\n .reduce(calculateSum);\n }\n\n protected _shouldUseNewBlock(newBlock: string) {\n const currentBlock = this._currentBlock;\n if (!currentBlock) {\n return true;\n }\n const newBlockInt = hexToInt(newBlock);\n const currentBlockInt = hexToInt(currentBlock);\n\n return (\n (this._usePastBlocks && newBlockInt < currentBlockInt) ||\n newBlockInt > currentBlockInt\n );\n }\n\n protected _newPotentialLatest(newBlock: string): void {\n if (!this._shouldUseNewBlock(newBlock)) {\n return;\n }\n this._setCurrentBlock(newBlock);\n }\n\n private _setCurrentBlock(newBlock: string): void {\n const oldBlock = this._currentBlock;\n this._currentBlock = newBlock;\n this.emit('latest', newBlock);\n this.emit('sync', { oldBlock, newBlock });\n }\n\n private _setupBlockResetTimeout(): void {\n // clear any existing timeout\n this._cancelBlockResetTimeout();\n // clear latest block when stale\n this._blockResetTimeout = setTimeout(\n this._resetCurrentBlock,\n this._blockResetDuration,\n );\n\n // nodejs - dont hold process open\n if (this._blockResetTimeout.unref) {\n this._blockResetTimeout.unref();\n }\n }\n\n private _cancelBlockResetTimeout(): void {\n if (this._blockResetTimeout) {\n clearTimeout(this._blockResetTimeout);\n }\n }\n\n private _resetCurrentBlock(): void {\n this._currentBlock = null;\n }\n}\n\n/**\n * Converts a number represented as a string in hexadecimal format into a native\n * number.\n *\n * @param hexInt - The hex string.\n * @returns The number.\n */\nfunction hexToInt(hexInt: string): number {\n return Number.parseInt(hexInt, 16);\n}\n","import getCreateRandomId from 'json-rpc-random-id';\nimport pify from 'pify';\nimport { JsonRpcRequest } from 'json-rpc-engine';\nimport type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport { BaseBlockTracker } from './BaseBlockTracker';\nimport { projectLogger, createModuleLogger } from './logging-utils';\n\nconst log = createModuleLogger(projectLogger, 'polling-block-tracker');\nconst createRandomId = getCreateRandomId();\nconst sec = 1000;\n\nexport interface PollingBlockTrackerOptions {\n provider?: SafeEventEmitterProvider;\n pollingInterval?: number;\n retryTimeout?: number;\n keepEventLoopActive?: boolean;\n setSkipCacheFlag?: boolean;\n blockResetDuration?: number;\n usePastBlocks?: boolean;\n}\n\ninterface ExtendedJsonRpcRequest extends JsonRpcRequest {\n skipCache?: boolean;\n}\n\nexport class PollingBlockTracker extends BaseBlockTracker {\n private _provider: SafeEventEmitterProvider;\n\n private _pollingInterval: number;\n\n private _retryTimeout: number;\n\n private _keepEventLoopActive: boolean;\n\n private _setSkipCacheFlag: boolean;\n\n constructor(opts: PollingBlockTrackerOptions = {}) {\n // parse + validate args\n if (!opts.provider) {\n throw new Error('PollingBlockTracker - no provider specified.');\n }\n\n super({\n ...opts,\n blockResetDuration: opts.blockResetDuration ?? opts.pollingInterval,\n });\n\n // config\n this._provider = opts.provider;\n this._pollingInterval = opts.pollingInterval || 20 * sec;\n this._retryTimeout = opts.retryTimeout || this._pollingInterval / 10;\n this._keepEventLoopActive =\n opts.keepEventLoopActive === undefined ? true : opts.keepEventLoopActive;\n this._setSkipCacheFlag = opts.setSkipCacheFlag || false;\n }\n\n // trigger block polling\n async checkForLatestBlock() {\n await this._updateLatestBlock();\n return await this.getLatestBlock();\n }\n\n protected async _start(): Promise {\n this._synchronize();\n }\n\n protected async _end(): Promise {\n // No-op\n }\n\n private async _synchronize(): Promise {\n while (this._isRunning) {\n try {\n await this._updateLatestBlock();\n const promise = timeout(\n this._pollingInterval,\n !this._keepEventLoopActive,\n );\n this.emit('_waitingForNextIteration');\n await promise;\n } catch (err: any) {\n const newErr = new Error(\n `PollingBlockTracker - encountered an error while attempting to update latest block:\\n${\n err.stack ?? err\n }`,\n );\n try {\n this.emit('error', newErr);\n } catch (emitErr) {\n console.error(newErr);\n }\n const promise = timeout(this._retryTimeout, !this._keepEventLoopActive);\n this.emit('_waitingForNextIteration');\n await promise;\n }\n }\n }\n\n private async _updateLatestBlock(): Promise {\n // fetch + set latest block\n const latestBlock = await this._fetchLatestBlock();\n this._newPotentialLatest(latestBlock);\n }\n\n private async _fetchLatestBlock(): Promise {\n const req: ExtendedJsonRpcRequest<[]> = {\n jsonrpc: '2.0',\n id: createRandomId(),\n method: 'eth_blockNumber',\n params: [],\n };\n if (this._setSkipCacheFlag) {\n req.skipCache = true;\n }\n\n log('Making request', req);\n const res = await pify((cb) => this._provider.sendAsync(req, cb))();\n log('Got response', res);\n if (res.error) {\n throw new Error(\n `PollingBlockTracker - encountered error fetching block:\\n${res.error.message}`,\n );\n }\n return res.result;\n }\n}\n\n/**\n * Waits for the specified amount of time.\n *\n * @param duration - The amount of time in milliseconds.\n * @param unref - Assuming this function is run in a Node context, governs\n * whether Node should wait before the `setTimeout` has completed before ending\n * the process (true for no, false for yes). Defaults to false.\n * @returns A promise that can be used to wait.\n */\nfunction timeout(duration: number, unref: boolean) {\n return new Promise((resolve) => {\n const timeoutRef = setTimeout(resolve, duration);\n // don't keep process open\n if (timeoutRef.unref && unref) {\n timeoutRef.unref();\n }\n });\n}\n","import getCreateRandomId from 'json-rpc-random-id';\nimport { JsonRpcNotification, JsonRpcSuccess } from 'json-rpc-engine';\nimport type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport { BaseBlockTracker } from './BaseBlockTracker';\n\nconst createRandomId = getCreateRandomId();\n\nexport interface SubscribeBlockTrackerOptions {\n provider?: SafeEventEmitterProvider;\n blockResetDuration?: number;\n usePastBlocks?: boolean;\n}\n\ninterface SubscriptionNotificationParams {\n subscription: string;\n result: { number: string };\n}\n\nexport class SubscribeBlockTracker extends BaseBlockTracker {\n private _provider: SafeEventEmitterProvider;\n\n private _subscriptionId: string | null;\n\n constructor(opts: SubscribeBlockTrackerOptions = {}) {\n // parse + validate args\n if (!opts.provider) {\n throw new Error('SubscribeBlockTracker - no provider specified.');\n }\n\n // BaseBlockTracker constructor\n super(opts);\n // config\n this._provider = opts.provider;\n this._subscriptionId = null;\n }\n\n async checkForLatestBlock(): Promise {\n return await this.getLatestBlock();\n }\n\n protected async _start(): Promise {\n if (this._subscriptionId === undefined || this._subscriptionId === null) {\n try {\n const blockNumber = (await this._call('eth_blockNumber')) as string;\n this._subscriptionId = (await this._call(\n 'eth_subscribe',\n 'newHeads',\n )) as string;\n this._provider.on('data', this._handleSubData.bind(this));\n this._newPotentialLatest(blockNumber);\n } catch (e) {\n this.emit('error', e);\n }\n }\n }\n\n protected async _end() {\n if (this._subscriptionId !== null && this._subscriptionId !== undefined) {\n try {\n await this._call('eth_unsubscribe', this._subscriptionId);\n this._subscriptionId = null;\n } catch (e) {\n this.emit('error', e);\n }\n }\n }\n\n private _call(method: string, ...params: unknown[]): Promise {\n return new Promise((resolve, reject) => {\n this._provider.sendAsync(\n {\n id: createRandomId(),\n method,\n params,\n jsonrpc: '2.0',\n },\n (err, res) => {\n if (err) {\n reject(err);\n } else {\n resolve((res as JsonRpcSuccess).result);\n }\n },\n );\n });\n }\n\n private _handleSubData(\n _: unknown,\n response: JsonRpcNotification,\n ): void {\n if (\n response.method === 'eth_subscription' &&\n response.params?.subscription === this._subscriptionId\n ) {\n this._newPotentialLatest(response.params.result.number);\n }\n }\n}\n","export * from './PollingBlockTracker';\nexport * from './SubscribeBlockTracker';\n","import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('eth-block-tracker');\n\nexport { createModuleLogger };\n","'use strict';\n\nconst processFn = (fn, opts) => function () {\n\tconst P = opts.promiseModule;\n\tconst args = new Array(arguments.length);\n\n\tfor (let i = 0; i < arguments.length; i++) {\n\t\targs[i] = arguments[i];\n\t}\n\n\treturn new P((resolve, reject) => {\n\t\tif (opts.errorFirst) {\n\t\t\targs.push(function (err, result) {\n\t\t\t\tif (opts.multiArgs) {\n\t\t\t\t\tconst results = new Array(arguments.length - 1);\n\n\t\t\t\t\tfor (let i = 1; i < arguments.length; i++) {\n\t\t\t\t\t\tresults[i - 1] = arguments[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tresults.unshift(err);\n\t\t\t\t\t\treject(results);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t} else if (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t} else {\n\t\t\t\t\tresolve(result);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\targs.push(function (result) {\n\t\t\t\tif (opts.multiArgs) {\n\t\t\t\t\tconst results = new Array(arguments.length - 1);\n\n\t\t\t\t\tfor (let i = 0; i < arguments.length; i++) {\n\t\t\t\t\t\tresults[i] = arguments[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(results);\n\t\t\t\t} else {\n\t\t\t\t\tresolve(result);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfn.apply(this, args);\n\t});\n};\n\nmodule.exports = (obj, opts) => {\n\topts = Object.assign({\n\t\texclude: [/.+(Sync|Stream)$/],\n\t\terrorFirst: true,\n\t\tpromiseModule: Promise\n\t}, opts);\n\n\tconst filter = key => {\n\t\tconst match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);\n\t\treturn opts.include ? opts.include.some(match) : !opts.exclude.some(match);\n\t};\n\n\tlet ret;\n\tif (typeof obj === 'function') {\n\t\tret = function () {\n\t\t\tif (opts.excludeMain) {\n\t\t\t\treturn obj.apply(this, arguments);\n\t\t\t}\n\n\t\t\treturn processFn(obj, opts).apply(this, arguments);\n\t\t};\n\t} else {\n\t\tret = Object.create(Object.getPrototypeOf(obj));\n\t}\n\n\tfor (const key in obj) { // eslint-disable-line guard-for-in\n\t\tconst x = obj[key];\n\t\tret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;\n\t}\n\n\treturn ret;\n};\n","const BaseFilter = require('./base-filter')\n\n// tracks all results ever recorded\nclass BaseFilterWithHistory extends BaseFilter {\n\n constructor () {\n super()\n this.allResults = []\n }\n\n async update () {\n throw new Error('BaseFilterWithHistory - no update method specified')\n }\n\n addResults (newResults) {\n this.allResults = this.allResults.concat(newResults)\n super.addResults(newResults)\n }\n\n addInitialResults (newResults) {\n this.allResults = this.allResults.concat(newResults)\n super.addInitialResults(newResults)\n }\n\n getAllResults () {\n return this.allResults\n }\n\n}\n\nmodule.exports = BaseFilterWithHistory","const SafeEventEmitter = require('@metamask/safe-event-emitter').default\n\nclass BaseFilter extends SafeEventEmitter {\n\n constructor () {\n super()\n this.updates = []\n }\n\n async initialize () {}\n\n async update () {\n throw new Error('BaseFilter - no update method specified')\n }\n\n addResults (newResults) {\n this.updates = this.updates.concat(newResults)\n newResults.forEach(result => this.emit('update', result))\n }\n\n addInitialResults (newResults) {}\n\n getChangesAndClear () {\n const updates = this.updates\n this.updates = []\n return updates\n }\n \n}\n\nmodule.exports = BaseFilter\n","const BaseFilter = require('./base-filter')\nconst getBlocksForRange = require('./getBlocksForRange')\nconst { incrementHexInt } = require('./hexUtils')\n\nclass BlockFilter extends BaseFilter {\n\n constructor ({ provider, params }) {\n super()\n this.type = 'block'\n this.provider = provider\n }\n\n async update ({ oldBlock, newBlock }) {\n const toBlock = newBlock\n const fromBlock = incrementHexInt(oldBlock)\n const blockBodies = await getBlocksForRange({ provider: this.provider, fromBlock, toBlock })\n const blockHashes = blockBodies.map((block) => block.hash)\n this.addResults(blockHashes)\n }\n\n}\n\nmodule.exports = BlockFilter\n","module.exports = getBlocksForRange\n\nasync function getBlocksForRange({ provider, fromBlock, toBlock }) {\n if (!fromBlock) fromBlock = toBlock\n\n const fromBlockNumber = hexToInt(fromBlock)\n const toBlockNumber = hexToInt(toBlock)\n const blockCountToQuery = toBlockNumber - fromBlockNumber + 1\n // load all blocks from old to new (inclusive)\n const missingBlockNumbers = Array(blockCountToQuery).fill()\n .map((_,index) => fromBlockNumber + index)\n .map(intToHex)\n let blockBodies = await Promise.all(\n missingBlockNumbers.map(blockNum => query(provider, 'eth_getBlockByNumber', [blockNum, false]))\n )\n blockBodies = blockBodies.filter(block => block !== null);\n return blockBodies\n}\n\nfunction hexToInt(hexString) {\n if (hexString === undefined || hexString === null) return hexString\n return Number.parseInt(hexString, 16)\n}\n\nfunction incrementHexInt(hexString){\n if (hexString === undefined || hexString === null) return hexString\n const value = hexToInt(hexString)\n return intToHex(value + 1)\n}\n\nfunction intToHex(int) {\n if (int === undefined || int === null) return int\n const hexString = int.toString(16)\n return '0x' + hexString\n}\n\nfunction sendAsync(provider, request) {\n return new Promise((resolve, reject) => {\n provider.sendAsync(request, (error, response) => {\n if (error) {\n reject(error);\n } else if (response.error) {\n reject(response.error);\n } else if (response.result) {\n resolve(response.result);\n } else {\n reject(new Error(\"Result was empty\"));\n }\n });\n });\n}\n\nasync function query(provider, method, params) {\n for (let i = 0; i < 3; i++) {\n try {\n return await sendAsync(provider, {\n id: 1,\n jsonrpc: \"2.0\",\n method,\n params,\n });\n } catch (error) {\n console.error(\n `provider.sendAsync failed: ${error.stack || error.message || error}`\n );\n }\n }\n return null;\n}\n","\nmodule.exports = {\n minBlockRef,\n maxBlockRef,\n sortBlockRefs,\n bnToHex,\n blockRefIsNumber,\n hexToInt,\n incrementHexInt,\n intToHex,\n unsafeRandomBytes,\n}\n\nfunction minBlockRef(...refs) {\n const sortedRefs = sortBlockRefs(refs)\n return sortedRefs[0]\n}\n\nfunction maxBlockRef(...refs) {\n const sortedRefs = sortBlockRefs(refs)\n return sortedRefs[sortedRefs.length-1]\n}\n\nfunction sortBlockRefs(refs) {\n return refs.sort((refA, refB) => {\n if (refA === 'latest' || refB === 'earliest') return 1\n if (refB === 'latest' || refA === 'earliest') return -1\n return hexToInt(refA) - hexToInt(refB)\n })\n}\n\nfunction bnToHex(bn) {\n return '0x' + bn.toString(16)\n}\n\nfunction blockRefIsNumber(blockRef){\n return blockRef && !['earliest', 'latest', 'pending'].includes(blockRef)\n}\n\nfunction hexToInt(hexString) {\n if (hexString === undefined || hexString === null) return hexString\n return Number.parseInt(hexString, 16)\n}\n\nfunction incrementHexInt(hexString){\n if (hexString === undefined || hexString === null) return hexString\n const value = hexToInt(hexString)\n return intToHex(value + 1)\n}\n\nfunction intToHex(int) {\n if (int === undefined || int === null) return int\n let hexString = int.toString(16)\n const needsLeftPad = hexString.length % 2\n if (needsLeftPad) hexString = '0' + hexString\n return '0x' + hexString\n}\n\nfunction unsafeRandomBytes(byteCount) {\n let result = '0x'\n for (let i = 0; i < byteCount; i++) {\n result += unsafeRandomNibble()\n result += unsafeRandomNibble()\n }\n return result\n}\n\nfunction unsafeRandomNibble() {\n return Math.floor(Math.random() * 16).toString(16)\n}\n","const Mutex = require('async-mutex').Mutex\nconst { createAsyncMiddleware, createScaffoldMiddleware } = require('json-rpc-engine')\nconst LogFilter = require('./log-filter.js')\nconst BlockFilter = require('./block-filter.js')\nconst TxFilter = require('./tx-filter.js')\nconst { intToHex, hexToInt } = require('./hexUtils')\n\nmodule.exports = createEthFilterMiddleware\n\nfunction createEthFilterMiddleware({ blockTracker, provider }) {\n\n // create filter collection\n let filterIndex = 0\n let filters = {}\n // create update mutex\n const mutex = new Mutex()\n const waitForFree = mutexMiddlewareWrapper({ mutex })\n\n const middleware = createScaffoldMiddleware({\n // install filters\n eth_newFilter: waitForFree(toFilterCreationMiddleware(newLogFilter)),\n eth_newBlockFilter: waitForFree(toFilterCreationMiddleware(newBlockFilter)),\n eth_newPendingTransactionFilter: waitForFree(toFilterCreationMiddleware(newPendingTransactionFilter)),\n // uninstall filters\n eth_uninstallFilter: waitForFree(toAsyncRpcMiddleware(uninstallFilterHandler)),\n // checking filter changes\n eth_getFilterChanges: waitForFree(toAsyncRpcMiddleware(getFilterChanges)),\n eth_getFilterLogs: waitForFree(toAsyncRpcMiddleware(getFilterLogs)),\n })\n\n // setup filter updating and destroy handler\n const filterUpdater = async ({ oldBlock, newBlock }) => {\n if (filters.length === 0) return\n // lock update reads\n const releaseLock = await mutex.acquire()\n try {\n // process all filters in parallel\n await Promise.all(objValues(filters).map(async (filter) => {\n try {\n await filter.update({ oldBlock, newBlock })\n } catch (err) {\n // handle each error individually so filter update errors don't affect other filters\n console.error(err)\n }\n }))\n } catch (err) {\n // log error so we don't skip the releaseLock\n console.error(err)\n }\n // unlock update reads\n releaseLock()\n }\n\n // expose filter methods directly\n middleware.newLogFilter = newLogFilter\n middleware.newBlockFilter = newBlockFilter\n middleware.newPendingTransactionFilter = newPendingTransactionFilter\n middleware.uninstallFilter = uninstallFilterHandler\n middleware.getFilterChanges = getFilterChanges\n middleware.getFilterLogs = getFilterLogs\n\n // expose destroy method for cleanup\n middleware.destroy = () => {\n uninstallAllFilters()\n }\n\n return middleware\n\n //\n // new filters\n //\n\n async function newLogFilter(params) {\n const filter = new LogFilter({ provider, params })\n const filterIndex = await installFilter(filter)\n return filter\n }\n\n async function newBlockFilter() {\n const filter = new BlockFilter({ provider })\n const filterIndex = await installFilter(filter)\n return filter\n }\n\n async function newPendingTransactionFilter() {\n const filter = new TxFilter({ provider })\n const filterIndex = await installFilter(filter)\n return filter\n }\n\n //\n // get filter changes\n //\n\n async function getFilterChanges(filterIndexHex) {\n const filterIndex = hexToInt(filterIndexHex)\n const filter = filters[filterIndex]\n if (!filter) {\n throw new Error(`No filter for index \"${filterIndex}\"`)\n }\n const results = filter.getChangesAndClear()\n return results\n }\n\n async function getFilterLogs(filterIndexHex) {\n const filterIndex = hexToInt(filterIndexHex)\n const filter = filters[filterIndex]\n if (!filter) {\n throw new Error(`No filter for index \"${filterIndex}\"`)\n }\n // only return results for log filters\n let results = []\n if (filter.type === 'log') {\n results = filter.getAllResults()\n }\n return results\n }\n\n\n //\n // remove filters\n //\n\n\n async function uninstallFilterHandler(filterIndexHex) {\n // check filter exists\n const filterIndex = hexToInt(filterIndexHex)\n const filter = filters[filterIndex]\n const result = Boolean(filter)\n // uninstall filter\n if (result) {\n await uninstallFilter(filterIndex)\n }\n return result\n }\n\n //\n // utils\n //\n\n async function installFilter(filter) {\n const prevFilterCount = objValues(filters).length\n // install filter\n const currentBlock = await blockTracker.getLatestBlock()\n await filter.initialize({ currentBlock })\n filterIndex++\n filters[filterIndex] = filter\n filter.id = filterIndex\n filter.idHex = intToHex(filterIndex)\n // update block tracker subs\n const newFilterCount = objValues(filters).length\n updateBlockTrackerSubs({ prevFilterCount, newFilterCount })\n return filterIndex\n }\n\n async function uninstallFilter(filterIndex) {\n const prevFilterCount = objValues(filters).length\n delete filters[filterIndex]\n // update block tracker subs\n const newFilterCount = objValues(filters).length\n updateBlockTrackerSubs({ prevFilterCount, newFilterCount })\n }\n\n async function uninstallAllFilters() {\n const prevFilterCount = objValues(filters).length\n filters = {}\n // update block tracker subs\n updateBlockTrackerSubs({ prevFilterCount, newFilterCount: 0 })\n }\n\n function updateBlockTrackerSubs({ prevFilterCount, newFilterCount }) {\n // subscribe\n if (prevFilterCount === 0 && newFilterCount > 0) {\n blockTracker.on('sync', filterUpdater)\n return\n }\n // unsubscribe\n if (prevFilterCount > 0 && newFilterCount === 0) {\n blockTracker.removeListener('sync', filterUpdater)\n return\n }\n }\n\n}\n\n// helper for turning filter constructors into rpc middleware\nfunction toFilterCreationMiddleware(createFilterFn) {\n return toAsyncRpcMiddleware(async (...args) => {\n const filter = await createFilterFn(...args)\n const result = intToHex(filter.id)\n return result\n })\n}\n\n// helper for pulling out req.params and setting res.result\nfunction toAsyncRpcMiddleware(asyncFn) {\n return createAsyncMiddleware(async (req, res) => {\n const result = await asyncFn.apply(null, req.params)\n res.result = result\n })\n}\n\nfunction mutexMiddlewareWrapper({ mutex }) {\n return (middleware) => {\n return async (req, res, next, end) => {\n // wait for mutex available\n // we can release immediately because\n // we just need to make sure updates aren't active\n const releaseLock = await mutex.acquire()\n releaseLock()\n middleware(req, res, next, end)\n }\n }\n}\n\nfunction objValues(obj, fn){\n const values = []\n for (let key in obj) {\n values.push(obj[key])\n }\n return values\n}\n","const EthQuery = require('eth-query')\nconst pify = require('pify')\nconst BaseFilterWithHistory = require('./base-filter-history')\nconst { bnToHex, hexToInt, incrementHexInt, minBlockRef, blockRefIsNumber } = require('./hexUtils')\n\nclass LogFilter extends BaseFilterWithHistory {\n\n constructor ({ provider, params }) {\n super()\n this.type = 'log'\n this.ethQuery = new EthQuery(provider)\n this.params = Object.assign({\n fromBlock: 'latest',\n toBlock: 'latest',\n address: undefined,\n topics: [],\n }, params)\n // normalize address parameter\n if (this.params.address) {\n // ensure array\n if (!Array.isArray(this.params.address)) {\n this.params.address = [this.params.address]\n }\n // ensure lowercase\n this.params.address = this.params.address.map(address => address.toLowerCase())\n }\n }\n\n async initialize({ currentBlock }) {\n // resolve params.fromBlock\n let fromBlock = this.params.fromBlock\n if (['latest', 'pending'].includes(fromBlock)) fromBlock = currentBlock\n if ('earliest' === fromBlock) fromBlock = '0x0'\n this.params.fromBlock = fromBlock\n // set toBlock for initial lookup\n const toBlock = minBlockRef(this.params.toBlock, currentBlock)\n const params = Object.assign({}, this.params, { toBlock })\n // fetch logs and add to results\n const newLogs = await this._fetchLogs(params)\n this.addInitialResults(newLogs)\n }\n\n async update ({ oldBlock, newBlock }) {\n // configure params for this update\n const toBlock = newBlock\n let fromBlock\n // oldBlock is empty on first sync\n if (oldBlock) {\n fromBlock = incrementHexInt(oldBlock)\n } else {\n fromBlock = newBlock\n }\n // fetch logs\n const params = Object.assign({}, this.params, { fromBlock, toBlock })\n const newLogs = await this._fetchLogs(params)\n const matchingLogs = newLogs.filter(log => this.matchLog(log))\n\n // add to results\n this.addResults(matchingLogs)\n }\n\n async _fetchLogs (params) {\n const newLogs = await pify(cb => this.ethQuery.getLogs(params, cb))()\n // add to results\n return newLogs\n }\n\n matchLog(log) {\n // check if block number in bounds:\n if (hexToInt(this.params.fromBlock) >= hexToInt(log.blockNumber)) return false\n if (blockRefIsNumber(this.params.toBlock) && hexToInt(this.params.toBlock) <= hexToInt(log.blockNumber)) return false\n\n // address is correct:\n const normalizedLogAddress = log.address && log.address.toLowerCase()\n if (this.params.address && normalizedLogAddress && !this.params.address.includes(normalizedLogAddress)) return false\n\n // topics match:\n // topics are position-dependant\n // topics can be nested to represent `or` [[a || b], c]\n // topics can be null, representing a wild card for that position\n const topicsMatch = this.params.topics.every((topicPattern, index) => {\n // pattern is longer than actual topics\n let logTopic = log.topics[index]\n if (!logTopic) return false\n logTopic = logTopic.toLowerCase()\n // normalize subTopics\n let subtopicsToMatch = Array.isArray(topicPattern) ? topicPattern : [topicPattern]\n // check for wild card\n const subtopicsIncludeWildcard = subtopicsToMatch.includes(null)\n if (subtopicsIncludeWildcard) return true\n subtopicsToMatch = subtopicsToMatch.map(topic => topic.toLowerCase())\n // check each possible matching topic\n const topicDoesMatch = subtopicsToMatch.includes(logTopic)\n return topicDoesMatch\n })\n\n return topicsMatch\n }\n\n}\n\nmodule.exports = LogFilter\n","'use strict';\n\nconst processFn = (fn, options, proxy, unwrapped) => function (...arguments_) {\n\tconst P = options.promiseModule;\n\n\treturn new P((resolve, reject) => {\n\t\tif (options.multiArgs) {\n\t\t\targuments_.push((...result) => {\n\t\t\t\tif (options.errorFirst) {\n\t\t\t\t\tif (result[0]) {\n\t\t\t\t\t\treject(result);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult.shift();\n\t\t\t\t\t\tresolve(result);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresolve(result);\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (options.errorFirst) {\n\t\t\targuments_.push((error, result) => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t} else {\n\t\t\t\t\tresolve(result);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\targuments_.push(resolve);\n\t\t}\n\n\t\tconst self = this === proxy ? unwrapped : this;\n\t\tReflect.apply(fn, self, arguments_);\n\t});\n};\n\nconst filterCache = new WeakMap();\n\nmodule.exports = (input, options) => {\n\toptions = {\n\t\texclude: [/.+(?:Sync|Stream)$/],\n\t\terrorFirst: true,\n\t\tpromiseModule: Promise,\n\t\t...options\n\t};\n\n\tconst objectType = typeof input;\n\tif (!(input !== null && (objectType === 'object' || objectType === 'function'))) {\n\t\tthrow new TypeError(`Expected \\`input\\` to be a \\`Function\\` or \\`Object\\`, got \\`${input === null ? 'null' : objectType}\\``);\n\t}\n\n\tconst filter = (target, key) => {\n\t\tlet cached = filterCache.get(target);\n\n\t\tif (!cached) {\n\t\t\tcached = {};\n\t\t\tfilterCache.set(target, cached);\n\t\t}\n\n\t\tif (key in cached) {\n\t\t\treturn cached[key];\n\t\t}\n\n\t\tconst match = pattern => (typeof pattern === 'string' || typeof key === 'symbol') ? key === pattern : pattern.test(key);\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(target, key);\n\t\tconst writableOrConfigurableOwn = (desc === undefined || desc.writable || desc.configurable);\n\t\tconst included = options.include ? options.include.some(match) : !options.exclude.some(match);\n\t\tconst shouldFilter = included && writableOrConfigurableOwn;\n\t\tcached[key] = shouldFilter;\n\t\treturn shouldFilter;\n\t};\n\n\tconst cache = new WeakMap();\n\n\tconst proxy = new Proxy(input, {\n\t\tapply(target, thisArg, args) {\n\t\t\tconst cached = cache.get(target);\n\n\t\t\tif (cached) {\n\t\t\t\treturn Reflect.apply(cached, thisArg, args);\n\t\t\t}\n\n\t\t\tconst pified = options.excludeMain ? target : processFn(target, options, proxy, target);\n\t\t\tcache.set(target, pified);\n\t\t\treturn Reflect.apply(pified, thisArg, args);\n\t\t},\n\n\t\tget(target, key) {\n\t\t\tconst property = target[key];\n\n\t\t\t// eslint-disable-next-line no-use-extend-native/no-use-extend-native\n\t\t\tif (!filter(target, key) || property === Function.prototype[key]) {\n\t\t\t\treturn property;\n\t\t\t}\n\n\t\t\tconst cached = cache.get(property);\n\n\t\t\tif (cached) {\n\t\t\t\treturn cached;\n\t\t\t}\n\n\t\t\tif (typeof property === 'function') {\n\t\t\t\tconst pified = processFn(property, options, proxy, target);\n\t\t\t\tcache.set(property, pified);\n\t\t\t\treturn pified;\n\t\t\t}\n\n\t\t\treturn property;\n\t\t}\n\t});\n\n\treturn proxy;\n};\n","const SafeEventEmitter = require('@metamask/safe-event-emitter').default\nconst { createAsyncMiddleware, createScaffoldMiddleware } = require('json-rpc-engine')\nconst createFilterMiddleware = require('./index.js')\nconst { unsafeRandomBytes, incrementHexInt } = require('./hexUtils.js')\nconst getBlocksForRange = require('./getBlocksForRange.js')\n\nmodule.exports = createSubscriptionMiddleware\n\n\nfunction createSubscriptionMiddleware({ blockTracker, provider }) {\n // state and utilities for handling subscriptions\n const subscriptions = {}\n const filterManager = createFilterMiddleware({ blockTracker, provider })\n\n // internal flag\n let isDestroyed = false\n\n // create subscriptionManager api object\n const events = new SafeEventEmitter()\n const middleware = createScaffoldMiddleware({\n eth_subscribe: createAsyncMiddleware(subscribe),\n eth_unsubscribe: createAsyncMiddleware(unsubscribe),\n })\n middleware.destroy = destroy\n return { events, middleware }\n\n async function subscribe(req, res) {\n\n if (isDestroyed) throw new Error(\n 'SubscriptionManager - attempting to use after destroying'\n )\n\n const subscriptionType = req.params[0]\n // subId is 16 byte hex string\n const subId = unsafeRandomBytes(16)\n\n // create sub\n let sub\n switch (subscriptionType) {\n case 'newHeads':\n sub = createSubNewHeads({ subId })\n break\n case 'logs':\n const filterParams = req.params[1]\n const filter = await filterManager.newLogFilter(filterParams)\n sub = createSubFromFilter({ subId, filter })\n break\n default:\n throw new Error(`SubscriptionManager - unsupported subscription type \"${subscriptionType}\"`)\n\n }\n subscriptions[subId] = sub\n\n res.result = subId\n return\n\n function createSubNewHeads({ subId }) {\n const sub = {\n type: subscriptionType,\n destroy: async () => {\n blockTracker.removeListener('sync', sub.update)\n },\n update: async ({ oldBlock, newBlock }) => {\n // for newHeads\n const toBlock = newBlock\n const fromBlock = incrementHexInt(oldBlock)\n const rawBlocks = await getBlocksForRange({ provider, fromBlock, toBlock })\n const results = rawBlocks.map(normalizeBlock).filter(block => block !== null)\n results.forEach((value) => {\n _emitSubscriptionResult(subId, value)\n })\n }\n }\n // check for subscription updates on new block\n blockTracker.on('sync', sub.update)\n return sub\n }\n\n function createSubFromFilter({ subId, filter }) {\n filter.on('update', result => _emitSubscriptionResult(subId, result))\n const sub = {\n type: subscriptionType,\n destroy: async () => {\n return await filterManager.uninstallFilter(filter.idHex)\n },\n }\n return sub\n }\n }\n\n async function unsubscribe(req, res) {\n\n if (isDestroyed) throw new Error(\n 'SubscriptionManager - attempting to use after destroying'\n )\n\n const id = req.params[0]\n const subscription = subscriptions[id]\n // if missing, return \"false\" to indicate it was not removed\n if (!subscription) {\n res.result = false\n return\n }\n // cleanup subscription\n delete subscriptions[id]\n await subscription.destroy()\n res.result = true\n }\n\n function _emitSubscriptionResult(filterIdHex, value) {\n events.emit('notification', {\n jsonrpc: '2.0',\n method: 'eth_subscription',\n params: {\n subscription: filterIdHex,\n result: value,\n },\n })\n }\n\n function destroy() {\n events.removeAllListeners()\n for (const id in subscriptions) {\n subscriptions[id].destroy()\n delete subscriptions[id]\n }\n isDestroyed = true\n }\n}\n\nfunction normalizeBlock(block) {\n if (block === null || block === undefined) {\n return null;\n }\n return {\n hash: block.hash,\n parentHash: block.parentHash,\n sha3Uncles: block.sha3Uncles,\n miner: block.miner,\n stateRoot: block.stateRoot,\n transactionsRoot: block.transactionsRoot,\n receiptsRoot: block.receiptsRoot,\n logsBloom: block.logsBloom,\n difficulty: block.difficulty,\n number: block.number,\n gasLimit: block.gasLimit,\n gasUsed: block.gasUsed,\n nonce: block.nonce,\n mixHash: block.mixHash,\n timestamp: block.timestamp,\n extraData: block.extraData,\n }\n}\n","const BaseFilter = require('./base-filter')\nconst getBlocksForRange = require('./getBlocksForRange')\nconst { incrementHexInt } = require('./hexUtils')\n\nclass TxFilter extends BaseFilter {\n\n constructor ({ provider }) {\n super()\n this.type = 'tx'\n this.provider = provider\n }\n\n async update ({ oldBlock }) {\n const toBlock = oldBlock\n const fromBlock = incrementHexInt(oldBlock)\n const blocks = await getBlocksForRange({ provider: this.provider, fromBlock, toBlock })\n const blockTxHashes = []\n for (const block of blocks) {\n blockTxHashes.push(...block.transactions)\n }\n // add to results\n this.addResults(blockTxHashes)\n }\n\n}\n\nmodule.exports = TxFilter\n","const extend = require('xtend')\nconst createRandomId = require('json-rpc-random-id')()\n\nmodule.exports = EthQuery\n\n\nfunction EthQuery(provider){\n const self = this\n self.currentProvider = provider\n}\n\n//\n// base queries\n//\n\n// default block\nEthQuery.prototype.getBalance = generateFnWithDefaultBlockFor(2, 'eth_getBalance')\nEthQuery.prototype.getCode = generateFnWithDefaultBlockFor(2, 'eth_getCode')\nEthQuery.prototype.getTransactionCount = generateFnWithDefaultBlockFor(2, 'eth_getTransactionCount')\nEthQuery.prototype.getStorageAt = generateFnWithDefaultBlockFor(3, 'eth_getStorageAt')\nEthQuery.prototype.call = generateFnWithDefaultBlockFor(2, 'eth_call')\n// standard\nEthQuery.prototype.protocolVersion = generateFnFor('eth_protocolVersion')\nEthQuery.prototype.syncing = generateFnFor('eth_syncing')\nEthQuery.prototype.coinbase = generateFnFor('eth_coinbase')\nEthQuery.prototype.mining = generateFnFor('eth_mining')\nEthQuery.prototype.hashrate = generateFnFor('eth_hashrate')\nEthQuery.prototype.gasPrice = generateFnFor('eth_gasPrice')\nEthQuery.prototype.accounts = generateFnFor('eth_accounts')\nEthQuery.prototype.blockNumber = generateFnFor('eth_blockNumber')\nEthQuery.prototype.getBlockTransactionCountByHash = generateFnFor('eth_getBlockTransactionCountByHash')\nEthQuery.prototype.getBlockTransactionCountByNumber = generateFnFor('eth_getBlockTransactionCountByNumber')\nEthQuery.prototype.getUncleCountByBlockHash = generateFnFor('eth_getUncleCountByBlockHash')\nEthQuery.prototype.getUncleCountByBlockNumber = generateFnFor('eth_getUncleCountByBlockNumber')\nEthQuery.prototype.sign = generateFnFor('eth_sign')\nEthQuery.prototype.sendTransaction = generateFnFor('eth_sendTransaction')\nEthQuery.prototype.sendRawTransaction = generateFnFor('eth_sendRawTransaction')\nEthQuery.prototype.estimateGas = generateFnFor('eth_estimateGas')\nEthQuery.prototype.getBlockByHash = generateFnFor('eth_getBlockByHash')\nEthQuery.prototype.getBlockByNumber = generateFnFor('eth_getBlockByNumber')\nEthQuery.prototype.getTransactionByHash = generateFnFor('eth_getTransactionByHash')\nEthQuery.prototype.getTransactionByBlockHashAndIndex = generateFnFor('eth_getTransactionByBlockHashAndIndex')\nEthQuery.prototype.getTransactionByBlockNumberAndIndex = generateFnFor('eth_getTransactionByBlockNumberAndIndex')\nEthQuery.prototype.getTransactionReceipt = generateFnFor('eth_getTransactionReceipt')\nEthQuery.prototype.getUncleByBlockHashAndIndex = generateFnFor('eth_getUncleByBlockHashAndIndex')\nEthQuery.prototype.getUncleByBlockNumberAndIndex = generateFnFor('eth_getUncleByBlockNumberAndIndex')\nEthQuery.prototype.getCompilers = generateFnFor('eth_getCompilers')\nEthQuery.prototype.compileLLL = generateFnFor('eth_compileLLL')\nEthQuery.prototype.compileSolidity = generateFnFor('eth_compileSolidity')\nEthQuery.prototype.compileSerpent = generateFnFor('eth_compileSerpent')\nEthQuery.prototype.newFilter = generateFnFor('eth_newFilter')\nEthQuery.prototype.newBlockFilter = generateFnFor('eth_newBlockFilter')\nEthQuery.prototype.newPendingTransactionFilter = generateFnFor('eth_newPendingTransactionFilter')\nEthQuery.prototype.uninstallFilter = generateFnFor('eth_uninstallFilter')\nEthQuery.prototype.getFilterChanges = generateFnFor('eth_getFilterChanges')\nEthQuery.prototype.getFilterLogs = generateFnFor('eth_getFilterLogs')\nEthQuery.prototype.getLogs = generateFnFor('eth_getLogs')\nEthQuery.prototype.getWork = generateFnFor('eth_getWork')\nEthQuery.prototype.submitWork = generateFnFor('eth_submitWork')\nEthQuery.prototype.submitHashrate = generateFnFor('eth_submitHashrate')\n\n// network level\n\nEthQuery.prototype.sendAsync = function(opts, cb){\n const self = this\n self.currentProvider.sendAsync(createPayload(opts), function(err, response){\n if (!err && response.error) err = new Error('EthQuery - RPC Error - '+response.error.message)\n if (err) return cb(err)\n cb(null, response.result)\n })\n}\n\n// util\n\nfunction generateFnFor(methodName){\n return function(){\n const self = this\n var args = [].slice.call(arguments)\n var cb = args.pop()\n self.sendAsync({\n method: methodName,\n params: args,\n }, cb)\n }\n}\n\nfunction generateFnWithDefaultBlockFor(argCount, methodName){\n return function(){\n const self = this\n var args = [].slice.call(arguments)\n var cb = args.pop()\n // set optional default block param\n if (args.length < argCount) args.push('latest')\n self.sendAsync({\n method: methodName,\n params: args,\n }, cb)\n }\n}\n\nfunction createPayload(data){\n return extend({\n // defaults\n id: createRandomId(),\n jsonrpc: '2.0',\n params: [],\n // user-specified\n }, data)\n}\n",null,null,null,null,null,"// 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","module.exports = stringify\nstringify.default = stringify\nstringify.stable = deterministicStringify\nstringify.stableStringify = deterministicStringify\n\nvar LIMIT_REPLACE_NODE = '[...]'\nvar CIRCULAR_REPLACE_NODE = '[Circular]'\n\nvar arr = []\nvar replacerStack = []\n\nfunction defaultOptions () {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER\n }\n}\n\n// Regular stringify\nfunction stringify (obj, replacer, spacer, options) {\n if (typeof options === 'undefined') {\n options = defaultOptions()\n }\n\n decirc(obj, '', 0, [], undefined, 0, options)\n var res\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer)\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)\n }\n } catch (_) {\n return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n }\n return res\n}\n\nfunction setReplace (replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace })\n arr.push([parent, k, val, propertyDescriptor])\n } else {\n replacerStack.push([val, k, replace])\n }\n } else {\n parent[k] = replace\n arr.push([parent, k, val])\n }\n}\n\nfunction decirc (val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)\n return\n }\n }\n\n if (\n typeof options.depthLimit !== 'undefined' &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent)\n return\n }\n\n if (\n typeof options.edgesLimit !== 'undefined' &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent)\n return\n }\n\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options)\n }\n } else {\n var keys = Object.keys(val)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n decirc(val[key], key, i, stack, val, depth, options)\n }\n }\n stack.pop()\n }\n}\n\n// Stable-stringify\nfunction compareFunction (a, b) {\n if (a < b) {\n return -1\n }\n if (a > b) {\n return 1\n }\n return 0\n}\n\nfunction deterministicStringify (obj, replacer, spacer, options) {\n if (typeof options === 'undefined') {\n options = defaultOptions()\n }\n\n var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj\n var res\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer)\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)\n }\n } catch (_) {\n return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n }\n return res\n}\n\nfunction deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)\n return\n }\n }\n try {\n if (typeof val.toJSON === 'function') {\n return\n }\n } catch (_) {\n return\n }\n\n if (\n typeof options.depthLimit !== 'undefined' &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent)\n return\n }\n\n if (\n typeof options.edgesLimit !== 'undefined' &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent)\n return\n }\n\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options)\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {}\n var keys = Object.keys(val).sort(compareFunction)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n deterministicDecirc(val[key], key, i, stack, val, depth, options)\n tmp[key] = val[key]\n }\n if (typeof parent !== 'undefined') {\n arr.push([parent, k, val])\n parent[k] = tmp\n } else {\n return tmp\n }\n }\n stack.pop()\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues (replacer) {\n replacer =\n typeof replacer !== 'undefined'\n ? replacer\n : function (k, v) {\n return v\n }\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i]\n if (part[1] === key && part[0] === val) {\n val = part[2]\n replacerStack.splice(i, 1)\n break\n }\n }\n }\n return replacer.call(this, key, val)\n }\n}\n","'use strict';\nmodule.exports = function (obj, predicate) {\n\tvar ret = {};\n\tvar keys = Object.keys(obj);\n\tvar isArr = Array.isArray(predicate);\n\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\n\t\tif (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n\t\t\tret[key] = val;\n\t\t}\n\t}\n\n\treturn ret;\n};\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","module.exports = self.fetch || (self.fetch = require('unfetch').default || require('unfetch'));\n",null,null,null,null,null,null,null,"module.exports = IdIterator\n\nfunction IdIterator(opts){\n opts = opts || {}\n var max = opts.max || Number.MAX_SAFE_INTEGER\n var idCounter = typeof opts.start !== 'undefined' ? opts.start : Math.floor(Math.random() * max)\n\n return function createRandomId () {\n idCounter = idCounter % max\n return idCounter++\n }\n\n}","module.exports = require('./lib/api')(require('./lib/keccak'))\n","const createKeccak = require('./keccak')\nconst createShake = require('./shake')\n\nmodule.exports = function (KeccakState) {\n const Keccak = createKeccak(KeccakState)\n const Shake = createShake(KeccakState)\n\n return function (algorithm, options) {\n const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm\n switch (hash) {\n case 'keccak224': return new Keccak(1152, 448, null, 224, options)\n case 'keccak256': return new Keccak(1088, 512, null, 256, options)\n case 'keccak384': return new Keccak(832, 768, null, 384, options)\n case 'keccak512': return new Keccak(576, 1024, null, 512, options)\n\n case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)\n case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)\n case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)\n case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)\n\n case 'shake128': return new Shake(1344, 256, 0x1f, options)\n case 'shake256': return new Shake(1088, 512, 0x1f, options)\n\n default: throw new Error('Invald algorithm: ' + algorithm)\n }\n }\n}\n","const { Transform } = require('readable-stream')\n\nmodule.exports = (KeccakState) => class Keccak extends Transform {\n constructor (rate, capacity, delimitedSuffix, hashBitLength, options) {\n super(options)\n\n this._rate = rate\n this._capacity = capacity\n this._delimitedSuffix = delimitedSuffix\n this._hashBitLength = hashBitLength\n this._options = options\n\n this._state = new KeccakState()\n this._state.initialize(rate, capacity)\n this._finalized = false\n }\n\n _transform (chunk, encoding, callback) {\n let error = null\n try {\n this.update(chunk, encoding)\n } catch (err) {\n error = err\n }\n\n callback(error)\n }\n\n _flush (callback) {\n let error = null\n try {\n this.push(this.digest())\n } catch (err) {\n error = err\n }\n\n callback(error)\n }\n\n update (data, encoding) {\n if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')\n if (this._finalized) throw new Error('Digest already called')\n if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)\n\n this._state.absorb(data)\n\n return this\n }\n\n digest (encoding) {\n if (this._finalized) throw new Error('Digest already called')\n this._finalized = true\n\n if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix)\n let digest = this._state.squeeze(this._hashBitLength / 8)\n if (encoding !== undefined) digest = digest.toString(encoding)\n\n this._resetState()\n\n return digest\n }\n\n // remove result from memory\n _resetState () {\n this._state.initialize(this._rate, this._capacity)\n return this\n }\n\n // because sometimes we need hash right now and little later\n _clone () {\n const clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options)\n this._state.copy(clone._state)\n clone._finalized = this._finalized\n\n return clone\n }\n}\n","const { Transform } = require('readable-stream')\n\nmodule.exports = (KeccakState) => class Shake extends Transform {\n constructor (rate, capacity, delimitedSuffix, options) {\n super(options)\n\n this._rate = rate\n this._capacity = capacity\n this._delimitedSuffix = delimitedSuffix\n this._options = options\n\n this._state = new KeccakState()\n this._state.initialize(rate, capacity)\n this._finalized = false\n }\n\n _transform (chunk, encoding, callback) {\n let error = null\n try {\n this.update(chunk, encoding)\n } catch (err) {\n error = err\n }\n\n callback(error)\n }\n\n _flush () {}\n\n _read (size) {\n this.push(this.squeeze(size))\n }\n\n update (data, encoding) {\n if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')\n if (this._finalized) throw new Error('Squeeze already called')\n if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)\n\n this._state.absorb(data)\n\n return this\n }\n\n squeeze (dataByteLength, encoding) {\n if (!this._finalized) {\n this._finalized = true\n this._state.absorbLastFewBits(this._delimitedSuffix)\n }\n\n let data = this._state.squeeze(dataByteLength)\n if (encoding !== undefined) data = data.toString(encoding)\n\n return data\n }\n\n _resetState () {\n this._state.initialize(this._rate, this._capacity)\n return this\n }\n\n _clone () {\n const clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options)\n this._state.copy(clone._state)\n clone._finalized = this._finalized\n\n return clone\n }\n}\n","const P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]\n\nexports.p1600 = function (s) {\n for (let round = 0; round < 24; ++round) {\n // theta\n const lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]\n const hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]\n const lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]\n const hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]\n const lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]\n const hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]\n const lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]\n const hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]\n const lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]\n const hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]\n\n let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31)\n let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31)\n const t1slo0 = s[0] ^ lo\n const t1shi0 = s[1] ^ hi\n const t1slo5 = s[10] ^ lo\n const t1shi5 = s[11] ^ hi\n const t1slo10 = s[20] ^ lo\n const t1shi10 = s[21] ^ hi\n const t1slo15 = s[30] ^ lo\n const t1shi15 = s[31] ^ hi\n const t1slo20 = s[40] ^ lo\n const t1shi20 = s[41] ^ hi\n lo = lo0 ^ (lo2 << 1 | hi2 >>> 31)\n hi = hi0 ^ (hi2 << 1 | lo2 >>> 31)\n const t1slo1 = s[2] ^ lo\n const t1shi1 = s[3] ^ hi\n const t1slo6 = s[12] ^ lo\n const t1shi6 = s[13] ^ hi\n const t1slo11 = s[22] ^ lo\n const t1shi11 = s[23] ^ hi\n const t1slo16 = s[32] ^ lo\n const t1shi16 = s[33] ^ hi\n const t1slo21 = s[42] ^ lo\n const t1shi21 = s[43] ^ hi\n lo = lo1 ^ (lo3 << 1 | hi3 >>> 31)\n hi = hi1 ^ (hi3 << 1 | lo3 >>> 31)\n const t1slo2 = s[4] ^ lo\n const t1shi2 = s[5] ^ hi\n const t1slo7 = s[14] ^ lo\n const t1shi7 = s[15] ^ hi\n const t1slo12 = s[24] ^ lo\n const t1shi12 = s[25] ^ hi\n const t1slo17 = s[34] ^ lo\n const t1shi17 = s[35] ^ hi\n const t1slo22 = s[44] ^ lo\n const t1shi22 = s[45] ^ hi\n lo = lo2 ^ (lo4 << 1 | hi4 >>> 31)\n hi = hi2 ^ (hi4 << 1 | lo4 >>> 31)\n const t1slo3 = s[6] ^ lo\n const t1shi3 = s[7] ^ hi\n const t1slo8 = s[16] ^ lo\n const t1shi8 = s[17] ^ hi\n const t1slo13 = s[26] ^ lo\n const t1shi13 = s[27] ^ hi\n const t1slo18 = s[36] ^ lo\n const t1shi18 = s[37] ^ hi\n const t1slo23 = s[46] ^ lo\n const t1shi23 = s[47] ^ hi\n lo = lo3 ^ (lo0 << 1 | hi0 >>> 31)\n hi = hi3 ^ (hi0 << 1 | lo0 >>> 31)\n const t1slo4 = s[8] ^ lo\n const t1shi4 = s[9] ^ hi\n const t1slo9 = s[18] ^ lo\n const t1shi9 = s[19] ^ hi\n const t1slo14 = s[28] ^ lo\n const t1shi14 = s[29] ^ hi\n const t1slo19 = s[38] ^ lo\n const t1shi19 = s[39] ^ hi\n const t1slo24 = s[48] ^ lo\n const t1shi24 = s[49] ^ hi\n\n // rho & pi\n const t2slo0 = t1slo0\n const t2shi0 = t1shi0\n const t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28)\n const t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28)\n const t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29)\n const t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29)\n const t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23)\n const t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23)\n const t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14)\n const t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14)\n const t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31)\n const t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31)\n const t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20)\n const t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20)\n const t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22)\n const t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22)\n const t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19)\n const t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19)\n const t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30)\n const t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30)\n const t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2)\n const t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2)\n const t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26)\n const t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26)\n const t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21)\n const t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21)\n const t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17)\n const t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17)\n const t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3)\n const t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3)\n const t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4)\n const t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4)\n const t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9)\n const t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9)\n const t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7)\n const t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7)\n const t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11)\n const t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11)\n const t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8)\n const t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8)\n const t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5)\n const t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5)\n const t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12)\n const t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12)\n const t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25)\n const t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25)\n const t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24)\n const t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24)\n const t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18)\n const t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18)\n\n // chi\n s[0] = t2slo0 ^ (~t2slo1 & t2slo2)\n s[1] = t2shi0 ^ (~t2shi1 & t2shi2)\n s[10] = t2slo5 ^ (~t2slo6 & t2slo7)\n s[11] = t2shi5 ^ (~t2shi6 & t2shi7)\n s[20] = t2slo10 ^ (~t2slo11 & t2slo12)\n s[21] = t2shi10 ^ (~t2shi11 & t2shi12)\n s[30] = t2slo15 ^ (~t2slo16 & t2slo17)\n s[31] = t2shi15 ^ (~t2shi16 & t2shi17)\n s[40] = t2slo20 ^ (~t2slo21 & t2slo22)\n s[41] = t2shi20 ^ (~t2shi21 & t2shi22)\n s[2] = t2slo1 ^ (~t2slo2 & t2slo3)\n s[3] = t2shi1 ^ (~t2shi2 & t2shi3)\n s[12] = t2slo6 ^ (~t2slo7 & t2slo8)\n s[13] = t2shi6 ^ (~t2shi7 & t2shi8)\n s[22] = t2slo11 ^ (~t2slo12 & t2slo13)\n s[23] = t2shi11 ^ (~t2shi12 & t2shi13)\n s[32] = t2slo16 ^ (~t2slo17 & t2slo18)\n s[33] = t2shi16 ^ (~t2shi17 & t2shi18)\n s[42] = t2slo21 ^ (~t2slo22 & t2slo23)\n s[43] = t2shi21 ^ (~t2shi22 & t2shi23)\n s[4] = t2slo2 ^ (~t2slo3 & t2slo4)\n s[5] = t2shi2 ^ (~t2shi3 & t2shi4)\n s[14] = t2slo7 ^ (~t2slo8 & t2slo9)\n s[15] = t2shi7 ^ (~t2shi8 & t2shi9)\n s[24] = t2slo12 ^ (~t2slo13 & t2slo14)\n s[25] = t2shi12 ^ (~t2shi13 & t2shi14)\n s[34] = t2slo17 ^ (~t2slo18 & t2slo19)\n s[35] = t2shi17 ^ (~t2shi18 & t2shi19)\n s[44] = t2slo22 ^ (~t2slo23 & t2slo24)\n s[45] = t2shi22 ^ (~t2shi23 & t2shi24)\n s[6] = t2slo3 ^ (~t2slo4 & t2slo0)\n s[7] = t2shi3 ^ (~t2shi4 & t2shi0)\n s[16] = t2slo8 ^ (~t2slo9 & t2slo5)\n s[17] = t2shi8 ^ (~t2shi9 & t2shi5)\n s[26] = t2slo13 ^ (~t2slo14 & t2slo10)\n s[27] = t2shi13 ^ (~t2shi14 & t2shi10)\n s[36] = t2slo18 ^ (~t2slo19 & t2slo15)\n s[37] = t2shi18 ^ (~t2shi19 & t2shi15)\n s[46] = t2slo23 ^ (~t2slo24 & t2slo20)\n s[47] = t2shi23 ^ (~t2shi24 & t2shi20)\n s[8] = t2slo4 ^ (~t2slo0 & t2slo1)\n s[9] = t2shi4 ^ (~t2shi0 & t2shi1)\n s[18] = t2slo9 ^ (~t2slo5 & t2slo6)\n s[19] = t2shi9 ^ (~t2shi5 & t2shi6)\n s[28] = t2slo14 ^ (~t2slo10 & t2slo11)\n s[29] = t2shi14 ^ (~t2shi10 & t2shi11)\n s[38] = t2slo19 ^ (~t2slo15 & t2slo16)\n s[39] = t2shi19 ^ (~t2shi15 & t2shi16)\n s[48] = t2slo24 ^ (~t2slo20 & t2slo21)\n s[49] = t2shi24 ^ (~t2shi20 & t2shi21)\n\n // iota\n s[0] ^= P1600_ROUND_CONSTANTS[round * 2]\n s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]\n }\n}\n","const keccakState = require('./keccak-state-unroll')\n\nfunction Keccak () {\n // much faster than `new Array(50)`\n this.state = [\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0\n ]\n\n this.blockSize = null\n this.count = 0\n this.squeezing = false\n}\n\nKeccak.prototype.initialize = function (rate, capacity) {\n for (let i = 0; i < 50; ++i) this.state[i] = 0\n this.blockSize = rate / 8\n this.count = 0\n this.squeezing = false\n}\n\nKeccak.prototype.absorb = function (data) {\n for (let i = 0; i < data.length; ++i) {\n this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4))\n this.count += 1\n if (this.count === this.blockSize) {\n keccakState.p1600(this.state)\n this.count = 0\n }\n }\n}\n\nKeccak.prototype.absorbLastFewBits = function (bits) {\n this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4))\n if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state)\n this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4))\n keccakState.p1600(this.state)\n this.count = 0\n this.squeezing = true\n}\n\nKeccak.prototype.squeeze = function (length) {\n if (!this.squeezing) this.absorbLastFewBits(0x01)\n\n const output = Buffer.alloc(length)\n for (let i = 0; i < length; ++i) {\n output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff\n this.count += 1\n if (this.count === this.blockSize) {\n keccakState.p1600(this.state)\n this.count = 0\n }\n }\n\n return output\n}\n\nKeccak.prototype.copy = function (dest) {\n for (let i = 0; i < 50; ++i) dest.state[i] = this.state[i]\n dest.blockSize = this.blockSize\n dest.count = this.count\n dest.squeezing = this.squeezing\n}\n\nmodule.exports = Keccak\n","/**\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright JS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\n/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = isEqual;\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 16;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 17;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {preact.ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tlet parentNode = node.parentNode;\n\tif (parentNode) parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the\n * virtual node\n * @returns {VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != null) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, null);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t// _nextDom must be initialized to undefined b/c it will eventually\n\t\t// be set to dom.nextSibling which can return `null` and it is important\n\t\t// to be able to distinguish between an uninitialized _nextDom and\n\t\t// a _nextDom that has been set to `null`\n\t\t_nextDom: undefined,\n\t\t_component: null,\n\t\tconstructor: undefined,\n\t\t_original: original == null ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == null && options.vnode != null) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: null };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != null && vnode.constructor == undefined;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != null && this._nextState !== this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == null) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == null) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: null;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != null && sibling._dom != null) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : null;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet oldVNode = component._vnode,\n\t\toldDom = oldVNode._dom,\n\t\tcommitQueue = [],\n\t\trefQueue = [];\n\n\tif (component._parentDom) {\n\t\tconst newVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.ownerSVGElement !== undefined,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : null,\n\t\t\tcommitQueue,\n\t\t\toldDom == null ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != null && vnode._component != null) {\n\t\tvnode._dom = vnode._component.base = null;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != null && child._dom != null) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce !== options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {Component} a\n * @param {Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c;\n\trerenderQueue.sort(depthSort);\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile ((c = rerenderQueue.shift())) {\n\t\tif (c._dirty) {\n\t\t\tlet renderQueueLength = rerenderQueue.length;\n\t\t\trenderComponent(c);\n\t\t\tif (rerenderQueue.length > renderQueueLength) {\n\t\t\t\t// When i.e. rerendering a provider additional new items can be injected, we want to\n\t\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t\t// single pass\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL } from '../constants';\nimport options from '../options';\n\nfunction setStyle(style, key, value) {\n\tif (key[0] === '-') {\n\t\tstyle.setProperty(key, value == null ? '' : value);\n\t} else if (value == null) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, isSvg) {\n\tlet useCapture;\n\n\to: if (name === 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] !== oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] === 'o' && name[1] === 'n') {\n\t\tuseCapture =\n\t\t\tname !== (name = name.replace(/(PointerCapture)$|Capture$/i, '$1'));\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (\n\t\t\tname.toLowerCase() in dom ||\n\t\t\tname === 'onFocusOut' ||\n\t\t\tname === 'onFocusIn'\n\t\t)\n\t\t\tname = name.toLowerCase().slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue._attached = eventClock;\n\t\t\t\tdom.addEventListener(\n name,\n useCapture ? eventProxyCapture : eventProxy,\n useCapture\n );\n\t\t\t} else {\n\t\t\t\tvalue._attached = oldValue._attached;\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (isSvg) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == null ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != null && (value !== false || name[4] === '-')) {\n\t\t\tdom.setAttribute(name, value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e._dispatched == null) {\n\t\t\t\te._dispatched = eventClock++;\n\n\t\t\t\t// When `e._dispatched` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e._dispatched < eventHandler._attached) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\n\nexport let i = 0;\n\nexport function createContext(defaultValue, contextId) {\n\tcontextId = '__cC' + i++;\n\n\tconst context = {\n\t\t_id: contextId,\n\t\t_defaultValue: defaultValue,\n\t\t/** @type {FunctionComponent} */\n\t\tConsumer(props, contextValue) {\n\t\t\t// return props.children(\n\t\t\t// \tcontext[contextId] ? context[contextId].props.value : defaultValue\n\t\t\t// );\n\t\t\treturn props.children(contextValue);\n\t\t},\n\t\t/** @type {FunctionComponent} */\n\t\tProvider(props) {\n\t\t\tif (!this.getChildContext) {\n\t\t\t\t/** @type {Component[]} */\n\t\t\t\tlet subs = [];\n\t\t\t\tlet ctx = {};\n\t\t\t\tctx[contextId] = this;\n\n\t\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t\tif (this.props.value !== _props.value) {\n\t\t\t\t\t\t// I think the forced value propagation here was only needed when `options.debounceRendering` was being bypassed:\n\t\t\t\t\t\t// https://github.com/preactjs/preact/commit/4d339fb803bea09e9f198abf38ca1bf8ea4b7771#diff-54682ce380935a717e41b8bfc54737f6R358\n\t\t\t\t\t\t// In those cases though, even with the value corrected, we're double-rendering all nodes.\n\t\t\t\t\t\t// It might be better to just tell folks not to use force-sync mode.\n\t\t\t\t\t\t// Currently, using `useContext()` in a class component will overwrite its `this.context` value.\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context[contextId] = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\t\t\t\t\t\tsubs.some(c => {\n\t\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tthis.sub = c => {\n\t\t\t\t\tsubs.push(c);\n\t\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\t\tsubs.splice(subs.indexOf(c), 1);\n\t\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn props.children;\n\t\t}\n\t};\n\n\t// Devtools needs access to the context object when it\n\t// encounters a Provider. This is necessary to support\n\t// setting `displayName` on the context object instead\n\t// of on the component itself. See:\n\t// https://reactjs.org/docs/context.html#contextdisplayname\n\n\treturn (context.Provider._contextRef = context.Consumer.contextType =\n\t\tcontext);\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport { EMPTY_OBJ, EMPTY_ARR, INSERT_VNODE, MATCHED } from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\tnewParentVNode._nextDom = oldDom;\n\tconstructNewChildrenArray(newParentVNode, renderResult, oldChildren);\n\toldDom = newParentVNode._nextDom;\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (\n\t\t\tchildVNode == null ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\tif (childVNode._index === -1) {\n\t\t\toldVNode = EMPTY_OBJ;\n\t\t} else {\n\t\t\toldVNode = oldChildren[childVNode._index] || EMPTY_OBJ;\n\t\t}\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tisSvg,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, null, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == null && newDom != null) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tif (\n\t\t\tchildVNode._flags & INSERT_VNODE ||\n\t\t\toldVNode._children === childVNode._children\n\t\t) {\n\t\t\t// @ts-expect-error olDom should be present on a DOM node\n\t\t\tif (oldDom && !oldDom.isConnected) {\n\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t}\n\t\t\toldDom = insert(childVNode, oldDom, parentDom);\n\t\t} else if (\n\t\t\ttypeof childVNode.type == 'function' &&\n\t\t\tchildVNode._nextDom !== undefined\n\t\t) {\n\t\t\t// Since Fragments or components that return Fragment like VNodes can\n\t\t\t// contain multiple DOM nodes as the same level, continue the diff from\n\t\t\t// the sibling of last DOM child of this child VNode\n\t\t\toldDom = childVNode._nextDom;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Eagerly cleanup _nextDom. We don't need to persist the value because it\n\t\t// is only used by `diffChildren` to determine where to resume the diff\n\t\t// after diffing Components and Fragments. Once we store it the nextDOM\n\t\t// local var, we can clean up the property. Also prevents us hanging on to\n\t\t// DOM nodes that may have been unmounted.\n\t\tchildVNode._nextDom = undefined;\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\t// TODO: With new child diffing algo, consider alt ways to diff Fragments.\n\t// Such as dropping oldDom and moving fragments in place\n\t//\n\t// Because the newParentVNode is Fragment-like, we need to set it's\n\t// _nextDom property to the nextSibling of its last child DOM node.\n\t//\n\t// `oldDom` contains the correct value here because if the last child\n\t// is a Fragment-like, then oldDom has already been set to that child's _nextDom.\n\t// If the last child is a DOM VNode, then oldDom will be set to that DOM\n\t// node's nextSibling.\n\tnewParentVNode._nextDom = oldDom;\n\tnewParentVNode._dom = firstChildDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(newParentVNode, renderResult, oldChildren) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tconst newChildrenLength = renderResult.length;\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = [];\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == null ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = null;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.
{reuse}{reuse}
) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tnull,\n\t\t\t\tchildVNode,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (childVNode.constructor === undefined && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
\n\t\t\t//
{reuse}{reuse}
\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : null,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tchildVNode = newParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\n\t\t// Handle unmounting null placeholders, i.e. VNode => null in unkeyed children\n\t\tif (childVNode == null) {\n\t\t\toldVNode = oldChildren[skewedIndex];\n\t\t\tif (\n\t\t\t\toldVNode &&\n\t\t\t\toldVNode.key == null &&\n\t\t\t\toldVNode._dom &&\n\t\t\t\t(oldVNode._flags & MATCHED) === 0\n\t\t\t) {\n\t\t\t\tif (oldVNode._dom == newParentVNode._nextDom) {\n\t\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode, false);\n\n\t\t\t\t// Explicitly nullify this position in oldChildren instead of just\n\t\t\t\t// setting `_match=true` to prevent other routines (e.g.\n\t\t\t\t// `findMatchingIndex` or `getDomSibling`) from thinking VNodes or DOM\n\t\t\t\t// nodes in this position are still available to be used in diffing when\n\t\t\t\t// they have actually already been unmounted. For example, by only\n\t\t\t\t// setting `_match=true` here, the unmounting loop later would attempt\n\t\t\t\t// to unmount this VNode again seeing `_match==true`. Further,\n\t\t\t\t// getDomSibling doesn't know about _match and so would incorrectly\n\t\t\t\t// assume DOM nodes in this subtree are mounted and usable.\n\t\t\t\toldChildren[skewedIndex] = null;\n\t\t\t\tremainingOldChildren--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\tconst matchingIndex = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t);\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tchildVNode._index = matchingIndex;\n\n\t\toldVNode = null;\n\t\tif (matchingIndex !== -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original === null\n\t\tconst isMounting = oldVNode == null || oldVNode._original === null;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\tskew--;\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex !== skewedIndex) {\n\t\t\tif (matchingIndex === skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else if (matchingIndex > skewedIndex) {\n\t\t\t\tif (remainingOldChildren > newChildrenLength - skewedIndex) {\n\t\t\t\t\tskew += matchingIndex - skewedIndex;\n\t\t\t\t} else {\n\t\t\t\t\tskew--;\n\t\t\t\t}\n\t\t\t} else if (matchingIndex < skewedIndex) {\n\t\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\t\tskew = matchingIndex - skewedIndex;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tskew = 0;\n\t\t\t}\n\n\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t// match the new skew index (i + new skew)\n\t\t\tif (matchingIndex !== i + skew) {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != null && (oldVNode._flags & MATCHED) === 0) {\n\t\t\t\tif (oldVNode._dom == newParentVNode._nextDom) {\n\t\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tparentDom.insertBefore(parentVNode._dom, oldDom || null);\n\t\toldDom = parentVNode._dom;\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != null && oldDom.nodeType === 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == null || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet x = skewedIndex - 1;\n\tlet y = skewedIndex + 1;\n\tlet oldVNode = oldChildren[skewedIndex];\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\tlet shouldSearch =\n\t\tremainingOldChildren >\n\t\t(oldVNode != null && (oldVNode._flags & MATCHED) === 0 ? 1 : 0);\n\n\tif (\n\t\toldVNode === null ||\n\t\t(oldVNode &&\n\t\t\tkey == oldVNode.key &&\n\t\t\ttype === oldVNode.type &&\n\t\t\t(oldVNode._flags & MATCHED) === 0)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tif (x >= 0) {\n\t\t\t\toldVNode = oldChildren[x];\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\t(oldVNode._flags & MATCHED) === 0 &&\n\t\t\t\t\tkey == oldVNode.key &&\n\t\t\t\t\ttype === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\treturn x;\n\t\t\t\t}\n\t\t\t\tx--;\n\t\t\t}\n\n\t\t\tif (y < oldChildren.length) {\n\t\t\t\toldVNode = oldChildren[y];\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\t(oldVNode._flags & MATCHED) === 0 &&\n\t\t\t\t\tkey == oldVNode.key &&\n\t\t\t\t\ttype === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\treturn y;\n\t\t\t\t}\n\t\t\t\ty++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_OBJ,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tRESET_MODE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {boolean} isSvg Whether or not this element is an SVG node\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== undefined) return null;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tc.props = newProps;\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc.context = componentContext;\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (c._nextState == null) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (newType.getDerivedStateFromProps != null) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tc.componentWillMount != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidMount != null) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t!c._force &&\n\t\t\t\t\t((c.shouldComponentUpdate != null &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false) ||\n\t\t\t\t\t\tnewVNode._original === oldVNode._original)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original !== oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.forEach(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != null) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidUpdate != null) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != null) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (!isNew && c.getSnapshotBeforeUpdate != null) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != null && tmp.type === Fragment && tmp.key == null;\n\t\t\tlet renderResult = isTopLevelFragment ? tmp.props.children : tmp;\n\n\t\t\tdiffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = null;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tnewVNode._original = null;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != null) {\n\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t: MODE_HYDRATE;\n\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = null;\n\t\t\t\t// ^ could possibly be simplified to:\n\t\t\t\t// excessDomChildren.length = 0;\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t}\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == null &&\n\t\tnewVNode._original === oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\tnewVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tisSvg,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\troot._nextDom = undefined;\n\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting SVG namespace when descending through the tree.\n\tif (nodeType === 'svg') isSvg = true;\n\n\tif (excessDomChildren != null) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value === !!nodeType &&\n\t\t\t\t(nodeType ? value.localName === nodeType : value.nodeType === 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == null) {\n\t\tif (nodeType === null) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tif (isSvg) {\n\t\t\tdom = document.createElementNS('http://www.w3.org/2000/svg', nodeType);\n\t\t} else {\n\t\t\tdom = document.createElement(nodeType, newProps.is && newProps);\n\t\t}\n\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = null;\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tisHydrating = false;\n\t}\n\n\tif (nodeType === null) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\toldProps = oldVNode.props || EMPTY_OBJ;\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != null) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (i !== 'key' && !(i in newProps)) {\n\t\t\t\tsetProperty(dom, i, null, value, isSvg);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\ti !== 'key' &&\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], isSvg);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html !== oldHtml.__html &&\n\t\t\t\t\t\tnewHtml.__html !== dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\tdom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg && nodeType !== 'foreignObject',\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tif (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating) {\n\t\t\ti = 'value';\n\t\t\tif (\n\t\t\t\tinputValue !== undefined &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType === 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix