@rango-dev/provider-ledger 0.21.1-next.2 → 0.21.1-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-HLLU77MH.js → Eth-Y5JFGVQA.js} +2 -2
- package/dist/{chunk-OOX2UCLJ.js → Solana-UB4SGWQ3.js} +2 -2
- package/dist/{TransportWebHID-HV53OYSS.js → TransportWebHID-JLT4ETY3.js} +2 -2
- package/dist/mod.js +1 -1
- package/dist/mod.js.map +4 -4
- package/dist/provider-ledger.build.json +1 -1
- package/package.json +3 -2
- package/src/signer.ts +3 -7
- package/src/signers/ethereum.ts +19 -9
- package/src/signers/solana.ts +13 -4
- package/src/utils.ts +15 -11
- package/dist/Eth-5PCPPYSI.js +0 -2
- package/dist/Eth-5PCPPYSI.js.map +0 -7
- package/dist/Solana-NJS3LWGA.js +0 -2
- package/dist/Solana-NJS3LWGA.js.map +0 -7
- package/dist/chunk-I25CJMQS.js +0 -2
- package/dist/chunk-I25CJMQS.js.map +0 -7
- package/dist/ethereum-J6U6B3NU.js +0 -2
- package/dist/ethereum-J6U6B3NU.js.map +0 -7
- package/dist/solana-Q7LP23TP.js +0 -2
- package/dist/solana-Q7LP23TP.js.map +0 -7
- /package/dist/{chunk-HLLU77MH.js.map → Eth-Y5JFGVQA.js.map} +0 -0
- /package/dist/{chunk-OOX2UCLJ.js.map → Solana-UB4SGWQ3.js.map} +0 -0
- /package/dist/{TransportWebHID-HV53OYSS.js.map → TransportWebHID-JLT4ETY3.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/state.ts", "../../core/src/legacy/types.ts", "../../core/src/legacy/persistor.ts", "../../core/src/legacy/helpers.ts", "../../core/src/legacy/utils.ts", "../../core/src/legacy/wallet.ts", "../../../node_modules/caip/src/spec.ts", "../../../node_modules/caip/src/utils.ts", "../../../node_modules/caip/src/chain.ts", "../../../node_modules/caip/src/account.ts", "../../../node_modules/caip/src/assetName.ts", "../../../node_modules/caip/src/assetType.ts", "../../../node_modules/caip/src/assetId.ts", "../../core/node_modules/zustand/esm/vanilla.mjs", "../../../node_modules/immer/src/utils/env.ts", "../../../node_modules/immer/src/utils/errors.ts", "../../../node_modules/immer/src/utils/common.ts", "../../../node_modules/immer/src/utils/plugins.ts", "../../../node_modules/immer/src/core/scope.ts", "../../../node_modules/immer/src/core/finalize.ts", "../../../node_modules/immer/src/core/proxy.ts", "../../../node_modules/immer/src/core/immerClass.ts", "../../../node_modules/immer/src/core/current.ts", "../../../node_modules/immer/src/plugins/patches.ts", "../../../node_modules/immer/src/plugins/mapset.ts", "../../../node_modules/immer/src/immer.ts", "../../core/src/namespaces/solana/actions.ts", "../../core/src/namespaces/common/actions.ts", "../../core/src/namespaces/solana/constants.ts", "../../core/src/namespaces/solana/utils.ts", "../../core/src/namespaces/solana/hooks.ts", "../../core/src/namespaces/solana/after.ts", "../../core/src/namespaces/common/after.ts", "../../core/src/namespaces/solana/and.ts", "../../core/src/hub/store/store.ts", "../../core/src/hub/store/namespaces.ts", "../../core/src/hub/store/providers.ts", "../../core/src/builders/action.ts", "../../core/src/utils/mod.ts", "../../core/src/namespaces/common/helpers.ts", "../../core/src/namespaces/common/and.ts", "../../core/src/namespaces/common/before.ts", "../../core/src/namespaces/solana/before.ts", "../../core/src/namespaces/solana/builders.ts", "../../core/src/namespaces/common/hooks/changeAccountSubscriber.ts", "../src/utils.ts", "../../core/src/hub/helpers.ts", "../../core/src/hub/namespaces/errors.ts", "../../core/src/hub/namespaces/namespace.ts", "../../core/src/hub/provider/provider.ts", "../../core/src/hub/hub.ts", "../../core/src/hub/store/selectors.ts", "../../core/src/hub/store/store.ts", "../../core/src/hub/store/extend.ts", "../../core/src/hub/store/hub.ts", "../../core/src/hub/store/namespaces.ts", "../../core/src/hub/store/events.ts", "../../core/src/hub/store/providers.ts", "../../core/src/builders/namespace.ts", "../../core/src/builders/provider.ts", "../../core/src/builders/action.ts", "../../core/src/utils/mod.ts", "../../core/src/utils/versions.ts", "../src/constants.ts", "../src/signer.ts"],
|
|
4
|
-
"sourcesContent": ["// We keep derivationPath here because we need to maintain it for signing transactions after it is set in connect method\nlet derivationPath = '';\n\nexport function setDerivationPath(path: string) {\n derivationPath = path;\n}\n\nexport function getDerivationPath() {\n return derivationPath;\n}\n", "import type { State as WalletState } from './wallet.js';\nimport type { GenerateDeepLink } from '../mod.js';\nimport type { Namespace } from '../namespaces/common/mod.js';\nimport type { BlockchainMeta, SignerFactory } from 'rango-types';\n\nexport enum Networks {\n BTC = 'BTC',\n BSC = 'BSC',\n LTC = 'LTC',\n THORCHAIN = 'THOR',\n BCH = 'BCH',\n BINANCE = 'BNB',\n ETHEREUM = 'ETH',\n POLYGON = 'POLYGON',\n TERRA = 'TERRA',\n POLKADOT = '',\n TRON = 'TRON',\n DOGE = 'DOGE',\n HARMONY = 'HARMONY',\n AVAX_CCHAIN = 'AVAX_CCHAIN',\n FANTOM = 'FANTOM',\n MOONBEAM = 'MOONBEAM',\n ARBITRUM = 'ARBITRUM',\n BOBA = 'BOBA',\n OPTIMISM = 'OPTIMISM',\n FUSE = 'FUSE',\n CRONOS = 'CRONOS',\n SOLANA = 'SOLANA',\n MOONRIVER = 'MOONRIVER',\n GNOSIS = 'GNOSIS',\n COSMOS = 'COSMOS',\n OSMOSIS = 'OSMOSIS',\n AXELAR = 'AXELAR',\n MARS = 'MARS',\n STRIDE = 'STRIDE',\n MAYA = 'MAYA',\n AKASH = 'AKASH',\n IRIS = 'IRIS',\n PERSISTENCE = 'PERSISTENCE',\n SENTINEL = 'SENTINEL',\n REGEN = 'REGEN',\n CRYPTO_ORG = 'CRYPTO_ORG',\n SIF = 'SIF',\n CHIHUAHUA = 'CHIHUAHUA',\n JUNO = 'JUNO',\n KUJIRA = 'KUJIRA',\n STARNAME = 'STARNAME',\n COMDEX = 'COMDEX',\n STARGAZE = 'STARGAZE',\n DESMOS = 'DESMOS',\n BITCANNA = 'BITCANNA',\n SECRET = 'SECRET',\n INJECTIVE = 'INJECTIVE',\n LUMNETWORK = 'LUMNETWORK',\n BANDCHAIN = 'BANDCHAIN',\n EMONEY = 'EMONEY',\n BITSONG = 'BITSONG',\n KI = 'KI',\n MEDIBLOC = 'MEDIBLOC',\n KONSTELLATION = 'KONSTELLATION',\n UMEE = 'UMEE',\n STARKNET = 'STARKNET',\n TON = 'TON',\n BASE = 'BASE',\n SUI = 'SUI',\n // Using instead of null\n Unknown = 'Unkown',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstanceType = any;\n\nexport type NamespaceData = {\n namespace: Namespace;\n derivationPath?: string;\n};\n\nexport type WalletType = string;\nexport type Network = string;\n\nexport type InstallObjects = {\n CHROME?: string;\n FIREFOX?: string;\n EDGE?: string;\n BRAVE?: string;\n DEFAULT: string;\n};\n\nexport type NamespaceMeta = {\n label: string;\n /**\n * By using a matched `blockchain.name` (in meta) and `id`, we show logo in Namespace modal\n * e.g. ETH\n */\n id: string;\n value: Namespace;\n unsupported?: boolean;\n getSupportedChains: (chains: BlockchainMeta[]) => BlockchainMeta[];\n};\n\ninterface NeedsNamespace {\n selection: 'single' | 'multiple';\n data: NamespaceMeta[];\n}\n\ninterface NeedsDerivationPath {\n data: {\n id: string;\n label: string;\n namespace: Namespace;\n generateDerivationPath: (index: string) => string;\n }[];\n}\n\nexport type WalletInfo = {\n name: string;\n img: string;\n installLink: InstallObjects | string;\n /**\n * @deprecated we don't use this value anymore.\n */\n color: string;\n supportedChains: BlockchainMeta[];\n showOnMobile?: boolean;\n isContractWallet?: boolean;\n mobileWallet?: boolean;\n generateDeepLink?: GenerateDeepLink;\n needsDerivationPath?: NeedsDerivationPath;\n needsNamespace?: NeedsNamespace;\n};\n\nexport type State = {\n [key: string]: WalletState | undefined;\n};\n\nexport type ConnectResult = {\n accounts: string[] | null;\n network: Network | null;\n provider: InstanceType;\n};\n\nexport type Providers = { [type in WalletType]?: InstanceType };\nexport type NetworkProviderMap = Map<Networks, unknown>;\n\nexport enum Events {\n CONNECTED = 'connected',\n CONNECTING = 'connecting',\n REACHABLE = 'reachable',\n INSTALLED = 'installed',\n ACCOUNTS = 'accounts',\n NETWORK = 'network',\n // Hub only events\n NAMESPACE_DISCONNECTED = 'namespace_disconnected',\n\n PROVIDER_DISCONNECTED = 'provider_disconnected',\n}\n\nexport type ProviderConnectResult = {\n accounts: string[];\n chainId: string;\n derivationPath?: string;\n};\n\nexport type GetInstanceOptions = {\n network?: Network;\n currentProvider: InstanceType;\n meta: BlockchainMeta[];\n getState: () => WalletState;\n /**\n * We always get the instance once and reuse it whenever we needs. By using this option\n * We can force the library to get a new instance and replace it with the old one.\n *\n * Originally, we used this option for wallet connect 1 and its switching network challenge.\n */\n force?: boolean;\n updateChainId: (chainId: number | string) => void;\n};\n\nexport type GetInstance =\n | (() => InstanceType)\n | ((options: GetInstanceOptions) => Promise<InstanceType>);\n\nexport type TryGetInstance =\n | (() => InstanceType)\n | ((\n options: Pick<GetInstanceOptions, 'force' | 'network'>\n ) => Promise<InstanceType>);\n\nexport type Connect = (options: {\n instance: InstanceType;\n network?: Network;\n meta: BlockchainMeta[];\n namespaces?: NamespaceData[];\n}) => Promise<ProviderConnectResult | ProviderConnectResult[]>;\n\nexport type Disconnect = (options: {\n instance: InstanceType;\n destroyInstance: () => void;\n}) => Promise<void>;\n\ntype CleanupSubscribe = () => void;\n\nexport type Subscribe = (options: {\n instance: InstanceType;\n state: WalletState;\n meta: BlockchainMeta[];\n updateChainId: (chainId: string) => void;\n updateAccounts: (accounts: string[], chainId?: string) => void;\n connect: (network?: Network) => void;\n disconnect: () => void;\n}) => CleanupSubscribe | void;\n\nexport type SwitchNetwork = (options: {\n instance: InstanceType;\n network: Network;\n meta: BlockchainMeta[];\n newInstance?: TryGetInstance;\n getState?: () => WalletState;\n updateChainId: (chainId: string) => void;\n}) => Promise<void>;\n\nexport type Suggest = (options: {\n instance: InstanceType;\n network: Network;\n meta: BlockchainMeta[];\n}) => Promise<void>;\n\nexport type CanSwitchNetwork = (options: {\n network: Network;\n meta: BlockchainMeta[];\n provider: InstanceType;\n}) => boolean;\n\nexport type CanEagerConnect = (options: {\n instance: InstanceType;\n meta: BlockchainMeta[];\n}) => Promise<boolean>;\n\nexport type EagerConnectResult<I = unknown> = {\n accounts: string[] | null;\n network: string | null;\n provider: I | null;\n};\n\nexport interface WalletActions {\n connect: Connect;\n getInstance: InstanceType;\n disconnect?: Disconnect;\n subscribe?: Subscribe;\n // unsubscribe, // coupled to subscribe.\n\n // Optional, but should be provided at the same time.\n suggest?: Suggest;\n switchNetwork?: SwitchNetwork;\n getSigners: (provider: InstanceType) => Promise<SignerFactory>;\n canSwitchNetworkTo?: CanSwitchNetwork;\n canEagerConnect?: CanEagerConnect;\n getWalletInfo(allBlockChains: BlockchainMeta[]): WalletInfo;\n}\n\nexport interface WalletConfig {\n type: WalletType;\n defaultNetwork?: Network;\n checkInstallation?: boolean;\n isAsyncInstance?: boolean;\n isAsyncSwitchNetwork?: boolean;\n}\n\nexport type WalletProviders = Map<\n WalletType,\n {\n actions: WalletActions;\n config: WalletConfig;\n }\n>;\n\nexport type ProviderInterface = { config: WalletConfig } & WalletActions;\n\n// it comes from wallets.ts and `connect`\ntype NetworkTypeFromLegacyConnect = Network | undefined;\n\nexport type NamespaceInputForConnect<T extends Namespace = Namespace> = {\n /**\n * By default, you should specify namespace (e.g. evm).\n */\n namespace: T;\n /**\n * In some cases, we need to connect a specific network on a namespace. e.g. Polygon on EVM.\n */\n network: NetworkTypeFromLegacyConnect;\n derivationPath?: string;\n};\n", "export interface PersistStorage<T> {\n getItem: (name: string) => T | null;\n setItem: (name: string, value: T) => void;\n removeItem: (name: string) => void;\n}\n\nexport class Persistor<T> implements PersistStorage<T> {\n getItem(name: string) {\n const item = localStorage.getItem(name);\n const parsedItem = item ? (JSON.parse(item) as T) : null;\n return parsedItem;\n }\n setItem(name: string, value: T) {\n localStorage.setItem(name, JSON.stringify(value));\n }\n removeItem(name: string) {\n localStorage.removeItem(name);\n }\n}\n", "import type { Network } from './types.js';\nimport type { Options } from './wallet.js';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport { Networks } from './types.js';\n\nexport function formatAddressWithNetwork(\n address: string,\n network?: Network | null\n) {\n return `${network || ''}:${address}`;\n}\n\nexport function accountAddressesWithNetwork(\n addresses: string[] | null,\n network?: Network | null\n) {\n if (!addresses) {\n return [];\n }\n\n return addresses.map((address) => {\n return formatAddressWithNetwork(address, network);\n });\n}\n\nexport function readAccountAddress(addressWithNetwork: string): {\n address: string;\n network: Network;\n} {\n const [network, address] = addressWithNetwork.split(':');\n\n return {\n network,\n address,\n };\n}\n\nexport function needsCheckInstallation(options: Options) {\n const { checkInstallation = true } = options.config;\n return checkInstallation;\n}\n\nexport const getBlockChainNameFromId = (\n chainId: string | number,\n blockchains: BlockchainMeta[]\n): Network | null => {\n chainId =\n typeof chainId === 'string' && chainId.startsWith('0x')\n ? parseInt(chainId)\n : chainId;\n\n /*\n * Sometimes providers are passing `Network` as chainId.\n * If chainId is a `Network`, we return itself.\n */\n const allNetworks = Object.values(Networks);\n if (allNetworks.includes(String(chainId) as Networks)) {\n return chainId as Networks;\n }\n\n if (chainId === 'Binance-Chain-Tigris') {\n return Networks.BINANCE;\n }\n return (\n blockchains\n .filter((blockchainMeta) => !!blockchainMeta.chainId)\n .find((blockchainMeta) => {\n const blockchainChainId = blockchainMeta.chainId?.startsWith('0x')\n ? parseInt(blockchainMeta.chainId)\n : blockchainMeta.chainId;\n return blockchainChainId == chainId;\n })?.name || null\n );\n};\n", "import type { NamespaceInputForConnect } from './types.js';\n\nexport async function eagerConnectHandler<R = unknown>(params: {\n canEagerConnect: () => Promise<boolean>;\n connectHandler: () => Promise<R>;\n providerName: string;\n}) {\n // Check if we can eagerly connect to the wallet\n if (await params.canEagerConnect()) {\n // Connect to wallet as usual\n return await params.connectHandler();\n }\n throw new Error(`can't restore connection for ${params.providerName}.`);\n}\n\nexport function isEvmNamespace(\n namespace: NamespaceInputForConnect\n): namespace is NamespaceInputForConnect<'EVM'> {\n return namespace.namespace === 'EVM';\n}\n", "import type {\n EagerConnectResult,\n GetInstanceOptions,\n NamespaceData,\n Network,\n WalletActions,\n WalletConfig,\n WalletType,\n} from './types.js';\nimport type { Namespace } from '../namespaces/common/types.js';\nimport type { BlockchainMeta } from 'rango-types';\n\nimport {\n accountAddressesWithNetwork,\n getBlockChainNameFromId,\n needsCheckInstallation,\n} from './helpers.js';\nimport { Events, Networks } from './types.js';\nimport { eagerConnectHandler } from './utils.js';\n\nexport type EventHandler = (\n type: WalletType,\n event: Events,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value: any,\n coreState: State,\n info: EventInfo\n) => void;\n\nexport type EventInfo = {\n supportedBlockchains: BlockchainMeta[];\n isContractWallet: boolean;\n\n // Hub fields\n isHub: boolean;\n // will be set alongside ACCOUNT event\n namespace?: Namespace;\n derivationPath?: string;\n};\n\nexport interface State {\n connected: boolean;\n connecting: boolean;\n /**\n * @depreacted it always returns `false`. don't use it.\n */\n reachable: boolean;\n installed: boolean;\n accounts: string[] | null;\n network: Network | null;\n derivationPath?: string;\n}\n\nexport interface Options {\n config: WalletConfig;\n handler: EventHandler;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nclass Wallet<InstanceType = any> {\n public provider: InstanceType | null;\n private actions: WalletActions;\n private state: State;\n private options: Options;\n private info: EventInfo;\n private cleanupSubscribe?: (() => void) | void;\n\n constructor(options: Options, actions: WalletActions) {\n this.actions = actions;\n this.options = options;\n this.provider = null;\n this.info = {\n supportedBlockchains: [],\n isContractWallet: false,\n isHub: false,\n };\n this.state = {\n connected: false,\n connecting: false,\n // TODO: Remove\n reachable: false,\n installed: false,\n accounts: null,\n network: null,\n };\n\n if (!needsCheckInstallation(options)) {\n this.setInstalledAs(true);\n }\n }\n\n async suggestAndConnect(network: Network) {\n if (this.actions.suggest) {\n await this.actions.suggest({\n instance: this.provider,\n meta: this.info.supportedBlockchains,\n network,\n });\n }\n return await this.connect(network);\n }\n\n async connect(network?: Network, namespaces?: NamespaceData[]) {\n // If it's connecting, nothing do.\n if (this.state.connecting) {\n throw new Error('Connecting...');\n }\n\n const connectionFromState = await this.getConnectionFromState();\n const currentNetwork = this.state.network;\n /*\n * If a network hasn't been provided and also we have `lastNetwork`\n * We will use lastNetwork to make sure we will not\n * Ask the user to switch his network wrongly.\n */\n const requestedNetwork =\n network || currentNetwork || this.options.config.defaultNetwork;\n\n if (connectionFromState) {\n const networkChanged =\n currentNetwork !== requestedNetwork && !!requestedNetwork;\n\n // Reuse current connection if nothing has changed and we already have the connection in memory.\n if (currentNetwork === requestedNetwork) {\n return connectionFromState;\n }\n\n let canSwitch = true;\n if (this.actions.canSwitchNetworkTo) {\n canSwitch = this.actions.canSwitchNetworkTo({\n provider: this.provider,\n meta: this.info.supportedBlockchains,\n network: requestedNetwork || '',\n });\n }\n\n if (networkChanged && canSwitch && !!this.actions.switchNetwork) {\n await this.actions.switchNetwork({\n instance: this.provider,\n meta: this.info.supportedBlockchains,\n // TODO: Fix type error\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n network: requestedNetwork,\n newInstance: this.tryGetInstance.bind(this),\n getState: this.getState.bind(this),\n updateChainId: this.updateChainId.bind(this),\n });\n\n /*\n * We assume if we reach here (`switchNetwork` not throwing error), Switch successfully has been done.\n * But for providers with async switch network like wallet-connect, we need to wait for chain change\n * event before changing network.\n */\n if (\n requestedNetwork !== this.state.network &&\n !this.options.config.isAsyncSwitchNetwork\n ) {\n this.updateState({\n network,\n });\n }\n\n return {\n // Only network has been changed, so we reuse accounts from what we have already.\n accounts: connectionFromState.accounts,\n network: requestedNetwork,\n provider: this.provider,\n };\n }\n\n // If none of the above conditions didn't match, continute to connect.\n }\n\n // We are connecting to wallet for the first time\n\n // Trying to get wallet's instance, if it's not available, raise an error.\n const instance = await this.tryGetInstance({ network });\n\n // Instance exists, trying to connect\n this.updateState({\n connecting: true,\n });\n this.setInstalledAs(true);\n\n try {\n // eslint-disable-next-line no-var\n var connectResult = await this.actions.connect({\n instance,\n network: requestedNetwork || undefined,\n meta: this.info.supportedBlockchains || [],\n namespaces,\n });\n } catch (e) {\n this.resetState();\n throw e;\n }\n\n this.updateState({\n connected: true,\n reachable: true,\n connecting: false,\n });\n\n // TODO: Handle accounts.length > 0\n\n // Inserting accounts into our state.\n let nextAccounts: string[] = [];\n let nextNetwork: Network | null | undefined = null;\n let nextDerivationPath: string | undefined = undefined;\n if (Array.isArray(connectResult)) {\n let activeEvmNetwork: Network | null = null;\n const accounts = connectResult.flatMap((blockchain) => {\n const chainId = blockchain.chainId || Networks.Unknown;\n // Try to map chainId with a Network, if not found, we use chainId directly.\n const network =\n getBlockChainNameFromId(chainId, this.info.supportedBlockchains) ||\n Networks.Unknown;\n nextDerivationPath = blockchain.derivationPath\n ? blockchain.derivationPath\n : nextDerivationPath;\n\n /*\n * When connecting to an evm instance, it will return address and wallet's active chain.\n * On switch network we are comparing state's network and what passed as requestedNetwork.\n * This code is for making sure we are setting correct active chain in state if it's evm.\n */\n if (!activeEvmNetwork && network !== Networks.Unknown) {\n const blockchainMeta = this.info.supportedBlockchains.find(\n (blockchain) => blockchain.name === network\n );\n if (blockchainMeta?.info?.infoType === 'EvmMetaInfo') {\n activeEvmNetwork = network;\n }\n }\n // TODO: second parameter should be `string` when we decided to open source the package.\n return accountAddressesWithNetwork(blockchain.accounts, network);\n });\n nextAccounts = accounts.filter(Boolean);\n nextNetwork =\n activeEvmNetwork ||\n requestedNetwork ||\n this.options.config.defaultNetwork;\n } else {\n const chainId = connectResult.chainId || Networks.Unknown;\n const network =\n getBlockChainNameFromId(chainId, this.info.supportedBlockchains) ||\n Networks.Unknown;\n const derivationPath = connectResult.derivationPath;\n\n // We fallback to current active network if `chainId` not provided.\n nextAccounts = accountAddressesWithNetwork(\n connectResult.accounts,\n network\n );\n nextNetwork = network;\n nextDerivationPath = derivationPath;\n }\n\n if (nextAccounts.length > 0) {\n this.updateState({\n accounts: nextAccounts,\n network: nextNetwork,\n derivationPath: nextDerivationPath,\n });\n }\n\n return {\n accounts: this.state.accounts,\n network: this.state.network,\n provider: this.provider,\n };\n }\n\n async disconnect() {\n this.resetState();\n\n if (this.actions.disconnect) {\n void this.actions.disconnect({\n instance: this.provider,\n // On wallet connect, we need to destory the instance and get a whole new instance when we are going to connect\n destroyInstance: () => {\n this.setProvider(null);\n },\n });\n }\n }\n\n // This method is only used for auto connection\n async eagerConnect(): Promise<EagerConnectResult<InstanceType>> {\n const instance = await this.tryGetInstance({ network: undefined });\n const { canEagerConnect } = this.actions;\n const providerName = this.options.config.type;\n\n return await eagerConnectHandler({\n canEagerConnect: async () => {\n if (!canEagerConnect) {\n throw new Error(\n `${providerName} provider hasn't implemented canEagerConnect.`\n );\n }\n\n return await canEagerConnect({\n instance: instance,\n meta: this.info.supportedBlockchains,\n });\n },\n connectHandler: async () => {\n const result = await this.connect();\n return result;\n },\n providerName,\n });\n }\n\n async getSigners(provider: InstanceType) {\n return await this.actions.getSigners(provider);\n }\n getWalletInfo(allBlockChains: BlockchainMeta[]) {\n return this.actions.getWalletInfo(allBlockChains);\n }\n canSwitchNetworkTo(network: Network, provider: InstanceType) {\n const switchTo = this.actions.canSwitchNetworkTo;\n if (!switchTo) {\n return false;\n }\n\n return switchTo({\n network,\n meta: this.info.supportedBlockchains,\n provider,\n });\n }\n\n onInit() {\n // some times functions can be overridden by wallets. see rf-2119\n if (!this.actions.getInstance) {\n throw new Error(\n `Provider hasn't defined how to get wallet's instance. provider: ${this.options.config.type} on: onInit`\n );\n }\n\n if (!this.options.config.isAsyncInstance) {\n const instance = this.actions.getInstance();\n if (!!instance && !this.state.installed) {\n this.setInstalledAs(true);\n }\n } else if (needsCheckInstallation(this.options)) {\n this.actions.getInstance().then((data: unknown) => {\n if (data) {\n this.setInstalledAs(true);\n }\n });\n }\n }\n\n setProvider(value: InstanceType | null) {\n this.provider = value;\n if (!!value && !!this.actions.subscribe) {\n const cleanup = this.actions.subscribe({\n instance: value,\n state: this.state,\n meta: this.info.supportedBlockchains,\n connect: this.connect.bind(this),\n disconnect: this.disconnect.bind(this),\n updateAccounts: (accounts, chainId) => {\n let network = this.state.network;\n if (chainId) {\n network =\n getBlockChainNameFromId(\n chainId,\n this.info.supportedBlockchains\n ) || Networks.Unknown;\n }\n\n const nextAccounts = accountAddressesWithNetwork(accounts, network);\n if (nextAccounts.length > 0) {\n this.updateState({\n accounts: nextAccounts,\n });\n }\n },\n updateChainId: this.updateChainId.bind(this),\n });\n this.cleanupSubscribe = cleanup;\n } else if (!value && this.cleanupSubscribe) {\n this.cleanupSubscribe();\n }\n }\n\n setInfo(info: Partial<EventInfo>) {\n if (typeof info.supportedBlockchains !== 'undefined') {\n this.info.supportedBlockchains = info.supportedBlockchains;\n }\n if (typeof info.isContractWallet !== 'undefined') {\n this.info.isContractWallet = info.isContractWallet;\n }\n }\n\n setHandler(handler: EventHandler) {\n this.options.handler = handler;\n }\n\n getState(): State {\n return this.state;\n }\n\n updateState(states: Partial<State>) {\n /*\n * We will notify handler after updating all the states.\n * Because when we call `handler` it will has latest states.\n */\n const updates: [Events, unknown][] = [];\n\n if (typeof states.connected !== 'undefined') {\n this.state.connected = states.connected;\n updates.push([Events.CONNECTED, states.connected]);\n }\n if (typeof states.connecting !== 'undefined') {\n this.state.connecting = states.connecting;\n updates.push([Events.CONNECTING, states.connecting]);\n }\n if (typeof states.reachable !== 'undefined') {\n this.state.reachable = states.reachable;\n updates.push([Events.REACHABLE, states.reachable]);\n }\n if (typeof states.installed !== 'undefined') {\n this.state.installed = states.installed;\n updates.push([Events.INSTALLED, states.installed]);\n }\n if (typeof states.accounts !== 'undefined') {\n this.state.accounts = states.accounts;\n this.state.derivationPath = states.derivationPath;\n updates.push([Events.ACCOUNTS, states.accounts]);\n }\n if (typeof states.network !== 'undefined') {\n this.state.network = states.network;\n updates.push([Events.NETWORK, states.network]);\n }\n\n const state = this.getState();\n updates.forEach(([name, value]) => {\n const eventInfo: EventInfo = {\n supportedBlockchains: this.info.supportedBlockchains,\n isContractWallet: this.info.isContractWallet,\n isHub: false,\n };\n this.options.handler(\n this.options.config.type,\n name,\n value,\n state,\n eventInfo\n );\n });\n }\n\n resetState() {\n this.updateState({\n connected: false,\n connecting: false,\n reachable: false,\n accounts: null,\n network: null,\n });\n }\n\n private async getConnectionFromState() {\n // Already connected, so we return provider that we have in memory.\n\n /*\n * For switching network on Trust Wallet (WalletConnect),\n * We only kill the session (and not restting the whole state)\n * So we are relying on this.provider for achieving this functionality.\n */\n if (this.state.connected && !!this.provider) {\n return {\n accounts: this.state.accounts,\n network: this.state.network,\n provider: this.provider,\n };\n }\n\n return null;\n }\n\n private updateChainId(chainId: string | number) {\n const network = chainId\n ? getBlockChainNameFromId(chainId, this.info.supportedBlockchains)\n : Networks.Unknown;\n\n this.updateState({\n network,\n });\n }\n\n private setInstalledAs(value: boolean) {\n if (!needsCheckInstallation(this.options) && value === false) {\n return;\n }\n\n this.updateState({\n installed: value,\n });\n }\n // eslint-disable-next-line destructuring/in-methods-params\n private async tryGetInstance({\n network,\n force,\n }: {\n network?: Network;\n force?: boolean;\n }) {\n let instance = null;\n /*\n * For switching network on Trust Wallet (WalletConnect),\n * We only kill the session (and not restting the whole state)\n * So we are relying on this.provider for achieving this functionality.\n */\n this.setProvider(null);\n if (this.options.config.isAsyncInstance) {\n // Trying to connect\n const instanceOptions: GetInstanceOptions = {\n currentProvider: this.provider,\n meta: this.info.supportedBlockchains,\n force: force || false,\n updateChainId: this.updateChainId.bind(this),\n getState: this.getState.bind(this),\n };\n\n if (network) {\n instanceOptions.network = network;\n }\n instance = await this.actions.getInstance(instanceOptions);\n } else {\n instance = this.actions.getInstance();\n }\n\n if (!instance) {\n this.setInstalledAs(false);\n this.resetState();\n\n const error_message = `It seems your selected wallet (${this.options.config.type}) isn't installed.`;\n throw new Error(error_message);\n }\n\n this.setProvider(instance);\n return instance;\n }\n}\n\nexport default Wallet;\n", "import { IdentifierSpec } from \"./types\";\n\nconst CAIP2: IdentifierSpec = {\n name: \"chainId\",\n regex: \"[-:a-zA-Z0-9]{5,41}\",\n parameters: {\n delimiter: \":\",\n values: {\n 0: {\n name: \"namespace\",\n regex: \"[-a-z0-9]{3,8}\",\n },\n 1: {\n name: \"reference\",\n regex: \"[-a-zA-Z0-9]{1,32}\",\n },\n },\n },\n};\n\nconst CAIP10: IdentifierSpec = {\n name: \"accountId\",\n regex: \"[-:a-zA-Z0-9]{7,106}\",\n parameters: {\n delimiter: \":\",\n values: {\n 0: {\n name: \"namespace\",\n regex: \"[-a-z0-9]{3,8}\",\n },\n 1: {\n name: \"reference\",\n regex: \"[-a-zA-Z0-9]{1,32}\",\n },\n 2: {\n name: \"address\",\n regex: \"[a-zA-Z0-9]{1,64}\",\n },\n },\n },\n};\n\n// represents namespace:reference in CAIP-19\nconst AssetName: IdentifierSpec = {\n name: \"assetName\",\n regex: \"[-:a-zA-Z0-9]{5,73}\",\n parameters: {\n delimiter: \":\",\n values: {\n 0: {\n name: \"namespace\",\n regex: \"[-a-z0-9]{3,8}\",\n },\n 1: {\n name: \"reference\",\n regex: \"[-a-zA-Z0-9]{1,64}\",\n },\n },\n },\n};\n\nconst CAIP19AssetType: IdentifierSpec = {\n name: \"assetType\",\n regex: \"[-:a-zA-Z0-9]{11,115}\",\n parameters: {\n delimiter: \"/\",\n values: {\n 0: CAIP2,\n 1: AssetName,\n },\n },\n};\n\nconst CAIP19AssetId: IdentifierSpec = {\n name: \"assetId\",\n regex: \"[-:a-zA-Z0-9]{13,148}\",\n parameters: {\n delimiter: \"/\",\n values: {\n 0: CAIP2,\n 1: AssetName,\n 2: {\n name: \"tokenId\",\n regex: \"[-a-zA-Z0-9]{1,32}\",\n },\n },\n },\n};\n\nexport const CAIP = {\n \"2\": CAIP2,\n \"10\": CAIP10,\n \"19\": {\n assetName: AssetName,\n assetType: CAIP19AssetType,\n assetId: CAIP19AssetId,\n },\n};\n", "import { IdentifierSpec, Params } from \"./types\";\n\nexport function splitParams(id: string, spec: IdentifierSpec): string[] {\n return id.split(spec.parameters.delimiter);\n}\n\nexport function getParams<T>(id: string, spec: IdentifierSpec): T {\n const arr = splitParams(id, spec);\n const params = {};\n arr.forEach((value, index) => {\n params[spec.parameters.values[index].name] = value;\n });\n return params as T;\n}\n\nexport function joinParams(params: Params, spec: IdentifierSpec): string {\n return Object.values(spec.parameters.values)\n .map(parameter => {\n const param = params[parameter.name];\n return typeof param === \"string\"\n ? param\n : joinParams(param, parameter as IdentifierSpec);\n })\n .join(spec.parameters.delimiter);\n}\n\nexport function isValidId(id: string, spec: IdentifierSpec): boolean {\n // console.log(\"id\", id);\n // console.log(\"spec\", spec);\n // console.log(\"before regex\");\n if (!new RegExp(spec.regex).test(id)) return false;\n // console.log(\"after regex\");\n // console.log(\"before split\");\n const params = splitParams(id, spec);\n // console.log(\"after split\");\n // console.log(\"params\", params);\n // console.log(\"before length\");\n if (params.length !== Object.keys(spec.parameters.values).length)\n return false;\n // console.log(\"after length\");\n // console.log(\"before matches\");\n const matches = params\n .map((param, index) =>\n new RegExp(spec.parameters.values[index].regex).test(param)\n )\n .filter(x => !!x);\n if (matches.length !== params.length) return false;\n // console.log(\"after matches\");\n return true;\n}\n", "import { CAIP } from \"./spec\";\nimport { IdentifierSpec } from \"./types\";\nimport { isValidId, joinParams, getParams } from \"./utils\";\n\nexport interface ChainIdParams {\n namespace: string;\n reference: string;\n}\n\nexport class ChainId {\n public static spec: IdentifierSpec = CAIP[\"2\"];\n\n public static parse(id: string): ChainIdParams {\n if (!isValidId(id, this.spec)) {\n throw new Error(`Invalid ${this.spec.name} provided: ${id}`);\n }\n return new ChainId(getParams<ChainIdParams>(id, this.spec)).toJSON();\n }\n\n public static format(params: ChainIdParams): string {\n return joinParams(params as any, this.spec);\n }\n\n public namespace: string;\n public reference: string;\n\n constructor(params: ChainIdParams | string) {\n if (typeof params === \"string\") {\n params = ChainId.parse(params);\n }\n\n this.namespace = params.namespace;\n this.reference = params.reference;\n }\n\n public toString(): string {\n return ChainId.format(this.toJSON());\n }\n\n public toJSON(): ChainIdParams {\n return {\n namespace: this.namespace,\n reference: this.reference,\n };\n }\n}\n", "import { ChainId, ChainIdParams } from \"./chain\";\nimport { CAIP } from \"./spec\";\nimport { IdentifierSpec } from \"./types\";\nimport { isValidId, joinParams, getParams } from \"./utils\";\n\nexport interface AccountIdSplitParams extends ChainIdParams {\n address: string;\n}\nexport interface AccountIdParams {\n chainId: string | ChainIdParams;\n address: string;\n}\n\nexport class AccountId {\n public static spec: IdentifierSpec = CAIP[\"10\"];\n\n public static parse(id: string): AccountIdParams {\n if (!isValidId(id, this.spec)) {\n throw new Error(`Invalid ${this.spec.name} provided: ${id}`);\n }\n const { namespace, reference, address } = getParams<AccountIdSplitParams>(\n id,\n this.spec\n );\n const chainId = new ChainId({ namespace, reference });\n return new AccountId({ chainId, address }).toJSON();\n }\n\n public static format(params: AccountIdParams): string {\n const chainId = new ChainId(params.chainId);\n const splitParams: AccountIdSplitParams = {\n ...chainId.toJSON(),\n address: params.address,\n };\n return joinParams(splitParams as any, this.spec);\n }\n\n public chainId: ChainId;\n public address: string;\n\n constructor(params: AccountIdParams | string) {\n if (typeof params === \"string\") {\n params = AccountId.parse(params);\n }\n\n this.chainId = new ChainId(params.chainId);\n this.address = params.address;\n }\n\n public toString(): string {\n return AccountId.format(this.toJSON());\n }\n\n public toJSON(): AccountIdParams {\n return {\n chainId: this.chainId.toJSON(),\n address: this.address,\n };\n }\n}\n", "import { CAIP } from \"./spec\";\nimport { IdentifierSpec } from \"./types\";\nimport { isValidId, joinParams, getParams } from \"./utils\";\n\nexport interface AssetNameParams {\n namespace: string;\n reference: string;\n}\n\nexport class AssetName {\n public static spec: IdentifierSpec = CAIP[\"19\"].assetName;\n\n public static parse(id: string): AssetNameParams {\n if (!isValidId(id, this.spec)) {\n throw new Error(`Invalid ${this.spec.name} provided: ${id}`);\n }\n return new AssetName(getParams<AssetNameParams>(id, this.spec)).toJSON();\n }\n\n public static format(params: AssetNameParams): string {\n return joinParams(params as any, this.spec);\n }\n\n public namespace: string;\n public reference: string;\n\n constructor(params: AssetNameParams | string) {\n if (typeof params === \"string\") {\n params = AssetName.parse(params);\n }\n\n this.namespace = params.namespace;\n this.reference = params.reference;\n }\n\n public toString(): string {\n return AssetName.format(this.toJSON());\n }\n\n public toJSON(): AssetNameParams {\n return {\n namespace: this.namespace,\n reference: this.reference,\n };\n }\n}\n", "import { AssetName, AssetNameParams } from \"./assetName\";\nimport { ChainId, ChainIdParams } from \"./chain\";\nimport { CAIP } from \"./spec\";\nimport { IdentifierSpec } from \"./types\";\nimport { isValidId, joinParams, getParams } from \"./utils\";\n\nexport interface AssetTypeParams {\n chainId: string | ChainIdParams;\n assetName: string | AssetNameParams;\n}\n\nexport class AssetType {\n public static spec: IdentifierSpec = CAIP[\"19\"].assetType;\n\n public static parse(id: string): AssetTypeParams {\n if (!isValidId(id, this.spec)) {\n throw new Error(`Invalid ${this.spec.name} provided: ${id}`);\n }\n return new AssetType(getParams<AssetTypeParams>(id, this.spec)).toJSON();\n }\n\n public static format(params: AssetTypeParams): string {\n return joinParams(params as any, this.spec);\n }\n\n public chainId: ChainId;\n public assetName: AssetName;\n\n constructor(params: AssetTypeParams | string) {\n if (typeof params === \"string\") {\n params = AssetType.parse(params);\n }\n\n this.chainId = new ChainId(params.chainId);\n this.assetName = new AssetName(params.assetName);\n }\n\n public toString(): string {\n return AssetType.format(this.toJSON());\n }\n\n public toJSON(): AssetTypeParams {\n return {\n chainId: this.chainId.toJSON(),\n assetName: this.assetName,\n };\n }\n}\n", "import { AssetName, AssetNameParams } from \"./assetName\";\nimport { ChainId, ChainIdParams } from \"./chain\";\nimport { CAIP } from \"./spec\";\nimport { IdentifierSpec } from \"./types\";\nimport { isValidId, joinParams, getParams } from \"./utils\";\n\nexport interface AssetIdParams {\n chainId: string | ChainIdParams;\n assetName: string | AssetNameParams;\n tokenId: string;\n}\n\nexport class AssetId {\n public static spec: IdentifierSpec = CAIP[\"19\"].assetId;\n\n public static parse(id: string): AssetIdParams {\n if (!isValidId(id, this.spec)) {\n throw new Error(`Invalid ${this.spec.name} provided: ${id}`);\n }\n return new AssetId(getParams<AssetIdParams>(id, this.spec)).toJSON();\n }\n\n public static format(params: AssetIdParams): string {\n return joinParams(params as any, this.spec);\n }\n\n public chainId: ChainId;\n public assetName: AssetName;\n public tokenId: string;\n\n constructor(params: AssetIdParams | string) {\n if (typeof params === \"string\") {\n params = AssetId.parse(params);\n }\n\n this.chainId = new ChainId(params.chainId);\n this.assetName = new AssetName(params.assetName);\n this.tokenId = params.tokenId;\n }\n\n public toString(): string {\n return AssetId.format(this.toJSON());\n }\n\n public toJSON(): AssetIdParams {\n return {\n chainId: this.chainId.toJSON(),\n assetName: this.assetName.toJSON(),\n tokenId: this.tokenId,\n };\n }\n}\n", "const createStoreImpl = (createState) => {\n let state;\n const listeners = /* @__PURE__ */ new Set();\n const setState = (partial, replace) => {\n const nextState = typeof partial === \"function\" ? partial(state) : partial;\n if (!Object.is(nextState, state)) {\n const previousState = state;\n state = (replace != null ? replace : typeof nextState !== \"object\" || nextState === null) ? nextState : Object.assign({}, state, nextState);\n listeners.forEach((listener) => listener(state, previousState));\n }\n };\n const getState = () => state;\n const getInitialState = () => initialState;\n const subscribe = (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n const destroy = () => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected.\"\n );\n }\n listeners.clear();\n };\n const api = { setState, getState, getInitialState, subscribe, destroy };\n const initialState = state = createState(setState, getState, api);\n return api;\n};\nconst createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;\nvar vanilla = (createState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'.\"\n );\n }\n return createStore(createState);\n};\n\nexport { createStore, vanilla as default };\n", "// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n", "export const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = typeof e === \"function\" ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n", "import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nexport const getPrototypeOf = Object.getPrototypeOf\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n * Regardless whether they are enumerable or symbols\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void\n): void\nexport function each(obj: any, iter: any) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\tReflect.ownKeys(obj).forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: Array.isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === ArchType.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (t === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc.writable === false) {\n\t\t\t\tdesc.writable = true\n\t\t\t\tdesc.configurable = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\t\tvalue: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn Object.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = Object.create(proto)\n\t\treturn Object.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.entries (only string-like, enumerables) instead of each()\n\t\tObject.entries(obj).forEach(([key, value]) => freeze(value, true))\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\treturn Object.isFrozen(obj)\n}\n", "import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\tbase: any,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\t}\n\tMapSet?: {\n\t\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T\n\t\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map<any, boolean> | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n", "import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n", "import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(value, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path)\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result = state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\t// And we let finalizeProperty know it needs to re-add non-draft children back to the target\n\t\tlet resultEach = result\n\t\tlet isSet = false\n\t\tif (state.type_ === ArchType.Set) {\n\t\t\tresultEach = new Set(result)\n\t\t\tresult.clear()\n\t\t\tisSet = true\n\t\t}\n\t\teach(resultEach, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path, isSet)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath,\n\ttargetIsSet?: boolean\n) {\n\tif (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n\t\tdie(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ArchType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t} else if (targetIsSet) {\n\t\ttargetObject.add(childValue)\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// Immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\t// Per #590, we never freeze symbolic properties. Just to make sure don't accidentally interfere\n\t\t// with other frameworks.\n\t\tif (\n\t\t\t(!parentState || !parentState.scope_.parent_) &&\n\t\t\ttypeof prop !== \"symbol\" &&\n\t\t\tObject.prototype.propertyIsEnumerable.call(targetObject, prop)\n\t\t)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n", "import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\tImmerScope\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted<T, ProxyState> {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(value, state))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {\n\tbase_: any\n\tcopy_: any\n\tscope_: ImmerScope\n}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n", "import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\";\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t}) {\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t\tif (typeof config?.useStrictShallowCopy === \"boolean\")\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip)\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n", "import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(copy, (key, childValue) => {\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n", "import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\")\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n", "// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n", "import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft<T>(value: T): Draft<T> {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable<T>(value: T): Immutable<T> {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\n", "import type { ProviderAPI, SolanaActions } from './types.js';\nimport type { Context } from '../../hub/namespaces/mod.js';\nimport type { CaipAccount } from '../../types/accounts.js';\nimport type { FunctionWithContext } from '../../types/actions.js';\n\nimport { AccountId } from 'caip';\n\nimport { recommended as commonRecommended } from '../common/actions.js';\n\nimport { CAIP_NAMESPACE, CAIP_SOLANA_CHAIN_ID } from './constants.js';\nimport { getAccounts } from './utils.js';\n\nexport const recommended = [...commonRecommended];\n\nexport function connect(\n instance: () => ProviderAPI\n): FunctionWithContext<SolanaActions['connect'], Context> {\n return async () => {\n const solanaInstance = instance();\n const result = await getAccounts(solanaInstance);\n\n if (Array.isArray(result)) {\n throw new Error(\n 'Expecting solana response to be a single value, not an array.'\n );\n }\n\n return result.accounts.map(\n (account) =>\n AccountId.format({\n address: account,\n chainId: {\n namespace: CAIP_NAMESPACE,\n reference: CAIP_SOLANA_CHAIN_ID,\n },\n }) as CaipAccount\n );\n };\n}\n", "import type { Context } from '../../hub/namespaces/mod.js';\n\nexport function disconnect(context: Context): void {\n const [, setState] = context.state();\n setState('network', null);\n setState('accounts', null);\n setState('connected', false);\n setState('connecting', false);\n}\n\nexport const recommended = [['disconnect', disconnect] as const];\n", "export const CAIP_NAMESPACE = 'solana';\nexport const CAIP_SOLANA_CHAIN_ID = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';\n", "import type { ProviderAPI } from './types.js';\nimport type { CaipAccount } from '../../types/accounts.js';\n\nimport { AccountId } from 'caip';\n\nimport { LegacyNetworks } from '../../legacy/mod.js';\n\nimport { CAIP_NAMESPACE, CAIP_SOLANA_CHAIN_ID } from './constants.js';\n\nexport async function getAccounts(provider: ProviderAPI) {\n const solanaResponse = await provider.connect();\n const account = solanaResponse.publicKey.toString();\n return {\n accounts: [account],\n chainId: LegacyNetworks.SOLANA,\n };\n}\n\nexport function formatAccountsToCAIP(accounts: string[]) {\n return accounts.map(\n (account) =>\n AccountId.format({\n address: account.toString(),\n chainId: {\n namespace: CAIP_NAMESPACE,\n reference: CAIP_SOLANA_CHAIN_ID,\n },\n }) as CaipAccount\n );\n}\n", "import type { ProviderAPI, SolanaActions } from './types.js';\nimport type { Subscriber, SubscriberCleanUp } from '../../mod.js';\n\nimport { builders } from './mod.js';\n\nexport function changeAccountSubscriber(\n instance: () => ProviderAPI\n): [Subscriber<SolanaActions>, SubscriberCleanUp<SolanaActions>] {\n return builders.changeAccountSubscriber(instance).build();\n}\n", "import { recommended as commonRecommended } from '../common/after.js';\n\nexport const recommended = [...commonRecommended];\n", "import type { Context } from '../../hub/namespaces/mod.js';\n\nexport function intoConnectionFinished(context: Context) {\n const [, setState] = context.state();\n setState('connecting', false);\n}\n\nexport const recommended = [['connect', intoConnectionFinished] as const];\n", "import { connectAndUpdateStateForSingleNetwork } from '../common/mod.js';\n\nexport const recommended = [\n ['connect', connectAndUpdateStateForSingleNetwork] as const,\n];\n", "import type { StoreApi } from 'zustand/vanilla';\n\nimport { createStore as createZustandStore } from 'zustand/vanilla';\n\nimport { extend, type Store } from './extend.js';\nimport { hubStore, type HubStore } from './hub.js';\nimport { namespacesStore, type NamespaceStore } from './namespaces.js';\nimport { providersStore, type ProviderStore } from './providers.js';\n\n/************ State ************/\n\nexport interface State {\n hub: HubStore;\n providers: ProviderStore;\n namespaces: NamespaceStore;\n}\n\nexport type RawStore = StoreApi<State>;\n\nexport const createStore = (): Store => {\n const store = createZustandStore<State>((...api) => {\n return {\n hub: hubStore(...api),\n providers: providersStore(...api),\n namespaces: namespacesStore(...api),\n };\n });\n\n return extend(store);\n};\n", "/************ Namespace ************/\n\nimport type { StateCreator } from 'zustand';\n\nimport { produce } from 'immer';\n\nimport {\n ConsumableEvents,\n type NamespaceConnectedEvent,\n type NamespaceDisconnectedEvent,\n type NamespaceSwitchedAccountEvent,\n type NamespaceSwitchedNetworkEvent,\n} from './events.js';\nimport { namespaceStateSelector, type State } from './mod.js';\n\n// Currently, namespace doesn't has any config.\nexport type NamespaceConfig = object;\n\nexport interface NamespaceData {\n accounts: null | string[];\n network: null | string;\n connected: boolean;\n connecting: boolean;\n}\n\ninterface NamespaceInfo {\n providerId: string;\n namespaceId: string;\n}\n\ninterface NamespaceItem {\n info: NamespaceInfo;\n data: NamespaceData;\n error: unknown;\n}\n\ntype NamespaceState = {\n events: InstanceType<typeof ConsumableEvents>;\n list: Record<string, NamespaceItem>;\n};\n\ninterface NamespaceActions {\n addNamespace: (id: string, config: NamespaceInfo) => void;\n updateStatus: <K extends keyof NamespaceData>(\n id: string,\n key: K,\n value: NamespaceData[K]\n ) => void;\n\n _produceEventsWhenUpdatingStatus: <K extends keyof NamespaceData>(\n namespace: NamespaceItem,\n id: string,\n key: K,\n value: NamespaceData[K]\n ) => void;\n}\ninterface NamespaceSelectors {\n getNamespaceData(storeId: string): NamespaceData;\n}\n\nexport type NamespaceStore = NamespaceState &\n NamespaceActions &\n NamespaceSelectors;\ntype NamespaceStateCreator = StateCreator<State, [], [], NamespaceStore>;\n\nconst namespacesStore: NamespaceStateCreator = (set, get) => ({\n events: new ConsumableEvents(),\n\n list: {},\n addNamespace: (id, info) => {\n const data: NamespaceData = {\n accounts: null,\n network: null,\n connected: false,\n connecting: false,\n };\n\n const item = {\n data,\n error: '',\n info,\n };\n\n set(\n produce((state: State) => {\n state.namespaces.list[id] = item;\n })\n );\n },\n updateStatus: (id, key, value) => {\n const ns = get().namespaces.list[id];\n if (!ns) {\n throw new Error(`No namespace with '${id}' found.`);\n }\n\n get().namespaces._produceEventsWhenUpdatingStatus(ns, id, key, value);\n\n // Updating state\n set(\n produce((state: State) => {\n state.namespaces.list[id].data[key] = value;\n })\n );\n },\n getNamespaceData(storeId) {\n return namespaceStateSelector(get(), storeId);\n },\n\n _produceEventsWhenUpdatingStatus: (namespace, id, key, value) => {\n if (key === 'accounts') {\n // check for both null and empty array\n const isAccountsEmpty =\n Object.is(value, null) || (Array.isArray(value) && value.length === 0);\n\n if (isAccountsEmpty) {\n const currentConnectedStatus = get().namespaces.list[id].data.connected;\n if (currentConnectedStatus) {\n const event: NamespaceDisconnectedEvent = {\n type: 'namespace_disconnected',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n };\n\n get().namespaces.events.push(event);\n }\n // Skip emitting disconnect event, if the `connected` is false\n } else {\n const currentAccounts = get().namespaces.list[id].data.accounts;\n\n if (!currentAccounts) {\n const event: NamespaceConnectedEvent = {\n type: 'namespace_connected',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n accounts: value as string[],\n };\n\n get().namespaces.events.push(event);\n } else {\n const areSameAccounts =\n currentAccounts.sort().toString() ===\n (value as string[]).sort().toString();\n\n if (!areSameAccounts) {\n const event: NamespaceSwitchedAccountEvent = {\n type: 'namespace_account_switched',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n previousAccounts: currentAccounts,\n accounts: value as string[],\n };\n\n get().namespaces.events.push(event);\n }\n }\n }\n } else if (key === 'network') {\n const currentNetwork = get().namespaces.list[id].data.network;\n\n const event: NamespaceSwitchedNetworkEvent = {\n type: 'namespace_network_switched',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n network: value as string,\n previousNetwork: currentNetwork,\n };\n\n get().namespaces.events.push(event);\n }\n },\n});\n\nexport { namespacesStore };\n", "import type { Namespace } from '../../namespaces/common/types.js';\nimport type {\n GenerateDeepLink,\n State as InternalProviderState,\n} from '../provider/mod.js';\nimport type { BlockchainMeta, SignerFactory } from 'rango-types';\nimport type { StateCreator } from 'zustand';\n\nimport { produce } from 'immer';\n\nimport { ConsumableEvents, type ProviderDetectedEvent } from './events.js';\nimport { guessProviderStateSelector, type State } from './mod.js';\n\ntype Browsers = 'firefox' | 'chrome' | 'edge' | 'brave' | 'homepage';\ntype Property<N extends string, V> = { name: N; value: V };\n\ntype NamespacesProperty = Property<\n 'namespaces',\n {\n selection: 'single' | 'multiple';\n data: {\n label: string;\n id: string;\n value: Namespace;\n unsupported?: boolean;\n getSupportedChains: (chains: BlockchainMeta[]) => BlockchainMeta[];\n }[];\n }\n>;\ntype DerivationPathProperty = Property<\n 'derivationPath',\n {\n data: {\n id: string;\n label: string;\n namespace: Namespace;\n generateDerivationPath: (index: string) => string;\n }[];\n }\n>;\ntype DetailsProperty = Property<\n 'details',\n {\n mobileWallet?: boolean;\n showOnMobile?: boolean;\n isContractWallet?: boolean;\n }\n>;\ntype SignersProperty = Property<\n 'signers',\n {\n getSigners: () => Promise<SignerFactory>;\n }\n>;\n\nexport type ProviderMetadata = {\n name: string;\n icon: string;\n extensions: Partial<Record<Browsers, string>>;\n properties?: Array<\n | NamespacesProperty\n | DerivationPathProperty\n | DetailsProperty\n | SignersProperty\n >;\n};\n\nexport interface ProviderConfig {\n metadata: ProviderMetadata;\n deepLink?: GenerateDeepLink;\n}\n\nexport type ProviderInfo = ProviderConfig;\n\ninterface ProviderData {\n installed: boolean;\n}\n\ninterface ProviderItem {\n config: ProviderConfig;\n data: ProviderData;\n error: unknown;\n}\n\ntype ProviderState = {\n events: ConsumableEvents;\n list: Record<string, ProviderItem>;\n};\ninterface ProviderActions {\n addProvider: (id: string, config: ProviderConfig) => void;\n removeProvider: (id: string) => void;\n updateStatus: <K extends keyof ProviderData>(\n id: string,\n key: K,\n value: ProviderData[K]\n ) => void;\n\n _produceEventsWhenUpdatingStatus: <K extends keyof ProviderData>(\n provider: ProviderItem,\n id: string,\n key: K,\n value: ProviderData[K]\n ) => void;\n}\n\ninterface ProviderSelectors {\n /**\n * Provider has a limited state to itself, to be compatible with legacy, we try to produce same object as legacy\n * which includes namespace state as well.\n */\n guessNamespacesState: (id: string) => InternalProviderState;\n}\n\nexport type ProviderStore = ProviderState & ProviderActions & ProviderSelectors;\ntype ProvidersStateCreator = StateCreator<State, [], [], ProviderStore>;\n\nconst providersStore: ProvidersStateCreator = (set, get) => ({\n events: new ConsumableEvents(),\n\n list: {},\n addProvider: (id, config) => {\n const item = {\n data: {\n installed: false,\n },\n error: '',\n config,\n };\n\n set(\n produce((state: State) => {\n state.providers.list[id] = item;\n })\n );\n },\n removeProvider: (id) => {\n set(\n produce((state: State) => {\n delete state.providers.list[id];\n })\n );\n },\n updateStatus: (id, key, value) => {\n const provider = get().providers.list[id];\n if (!provider) {\n throw new Error(`No namespace namespace with '${id}' found.`);\n }\n\n get().providers._produceEventsWhenUpdatingStatus(provider, id, key, value);\n\n set(\n produce((state: State) => {\n state.providers.list[id].data[key] = value;\n })\n );\n },\n guessNamespacesState: (providerId: string): InternalProviderState => {\n return guessProviderStateSelector(get(), providerId);\n },\n\n _produceEventsWhenUpdatingStatus: (_provider, id, key, _value) => {\n if (key === 'installed') {\n const event: ProviderDetectedEvent = {\n type: 'provider_detected',\n provider: id,\n };\n\n get().providers.events.push(event);\n }\n },\n});\n\nexport { providersStore };\n", "import type { Actions, Context, Operators } from '../hub/namespaces/types.js';\nimport type { AnyFunction, FunctionWithContext } from '../types/actions.js';\n\nexport interface ActionByBuilder<T, Context> {\n actionName: keyof T;\n and: Operators<T>;\n or: Operators<T>;\n after: Operators<T>;\n before: Operators<T>;\n action: FunctionWithContext<T[keyof T], Context>;\n}\n\n/*\n * TODO:\n * Currently, to use this builder you will write something like this:\n * new ActionBuilder<EvmActions, 'disconnect'>('disconnect').after(....)\n *\n * I couldn't figure it out to be able typescript infer the constructor value as key of actions.\n * Ideal usage:\n * new ActionBuilder<EvmActions>('disconnect').after(....)\n *\n */\nexport class ActionBuilder<T extends Actions<T>, K extends keyof T> {\n readonly name: K;\n #and: Operators<T> = new Map();\n #or: Operators<T> = new Map();\n #after: Operators<T> = new Map();\n #before: Operators<T> = new Map();\n #action: FunctionWithContext<T[keyof T], Context<T>> | undefined;\n\n constructor(name: K) {\n this.name = name;\n }\n\n public and(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#and.has(this.name)) {\n this.#and.set(this.name, []);\n }\n this.#and.get(this.name)?.push(action);\n return this;\n }\n\n public or(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#or.has(this.name)) {\n this.#or.set(this.name, []);\n }\n this.#or.get(this.name)?.push(action);\n return this;\n }\n\n public before(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#before.has(this.name)) {\n this.#before.set(this.name, []);\n }\n this.#before.get(this.name)?.push(action);\n return this;\n }\n\n public after(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#after.has(this.name)) {\n this.#after.set(this.name, []);\n }\n this.#after.get(this.name)?.push(action);\n return this;\n }\n\n public action(action: FunctionWithContext<T[keyof T], Context<T>>) {\n this.#action = action;\n return this;\n }\n\n public build(): ActionByBuilder<T, Context<T>> {\n if (!this.#action) {\n throw new Error('Your action builder should includes an action.');\n }\n\n return {\n actionName: this.name,\n action: this.#action,\n before: this.#before,\n after: this.#after,\n and: this.#and,\n or: this.#or,\n };\n }\n}\n", "/*\n * It is not a good idea to re-export all of CAIP because if they have a breaking change, we will break as well.\n * It would be better to create an abstraction over them and export our own interface to ensure it is under our control.\n */\nexport * as CAIP from 'caip';\n\nexport { generateStoreId } from '../hub/helpers.js';\nexport * from './versions.js';\n", "import { AccountId } from 'caip';\n\nexport function isValidCaipAddress(address: string): boolean {\n try {\n AccountId.parse(address);\n return true;\n } catch {\n return false;\n }\n}\n", "import type {\n Accounts,\n AccountsWithActiveChain,\n} from './../../types/accounts.js';\nimport type { Context } from '../../hub/namespaces/mod.js';\n\nimport { isValidCaipAddress } from './helpers.js';\n\nexport function connectAndUpdateStateForSingleNetwork(\n context: Context,\n accounts: Accounts\n) {\n if (!accounts.every(isValidCaipAddress)) {\n throw new Error(\n `Your provider should format account addresses in CAIP-10 format. Your provided accounts: ${accounts}`\n );\n }\n\n const [, setState] = context.state();\n setState('accounts', accounts);\n setState('connected', true);\n return accounts;\n}\n\nexport function connectAndUpdateStateForMultiNetworks(\n context: Context,\n accounts: AccountsWithActiveChain\n) {\n if (!accounts.accounts.every(isValidCaipAddress)) {\n throw new Error(\n `Your provider should format account addresses in CAIP-10 format. Your provided accounts: ${accounts.accounts}`\n );\n }\n\n const [, setState] = context.state();\n setState('accounts', accounts.accounts);\n setState('network', accounts.network);\n setState('connected', true);\n return accounts;\n}\n\nexport const recommended = [];\n", "import type { Context } from '../../hub/namespaces/mod.js';\n\nexport function intoConnecting(context: Context) {\n const [, setState] = context.state();\n setState('connecting', true);\n}\n\n// Please consider if you are going to add something here, make sure it works on all namespaces.\nexport const recommended = [['connect', intoConnecting] as const];\n", "import { recommended as commonRecommended } from '../common/before.js';\n\nexport const recommended = [...commonRecommended];\n", "import type { ProviderAPI, SolanaActions } from './types.js';\n\nimport { ActionBuilder } from '../../mod.js';\nimport { ChangeAccountSubscriberBuilder } from '../common/hooks/changeAccountSubscriber.js';\nimport {\n connectAndUpdateStateForSingleNetwork,\n intoConnecting,\n intoConnectionFinished,\n} from '../common/mod.js';\n\nimport { formatAccountsToCAIP } from './utils.js';\n\n// Actions\nexport const connect = () =>\n new ActionBuilder<SolanaActions, 'connect'>('connect')\n .and(connectAndUpdateStateForSingleNetwork)\n .before(intoConnecting)\n .after(intoConnectionFinished);\n\n// Hooks\nexport const changeAccountSubscriber = (getInstance: () => ProviderAPI) =>\n new ChangeAccountSubscriberBuilder<string, ProviderAPI>()\n .getInstance(getInstance)\n .validateEventPayload(\n (accounts) =>\n /*\n * In some wallets, when a user switches to an account not yet connected to the dApp, it returns null.\n * A null value indicates no access to the account, requiring a disconnect and user reconnection.\n */\n !!accounts\n )\n .format(async (_, accounts) => formatAccountsToCAIP([accounts]))\n .addEventListener((instance, callback) => {\n instance.on('accountChanged', callback);\n })\n .removeEventListener((instance, callback) => {\n instance.off('accountChanged', callback);\n });\n", "import type {\n Actions,\n SubscriberCleanUp,\n} from '../../../hub/namespaces/types.js';\nimport type { Subscriber } from '../../../mod.js';\nimport type { AutoImplementedActionsByRecommended } from '../types.js';\n\nexport class ChangeAccountSubscriberBuilder<EventType, ProviderAPI> {\n #getInstance: (() => ProviderAPI) | null = null;\n #format:\n | ((instance: ProviderAPI, event: EventType) => Promise<string[]>)\n | null = null;\n #validateEventPayload: ((event: EventType) => boolean) | null = null;\n\n #addEventListener:\n | ((\n instance: ProviderAPI,\n callback: (event: EventType) => void\n ) => (() => void) | void)\n | null = null;\n #removeEventListener:\n | ((instance: ProviderAPI, callback: (event: EventType) => void) => void)\n | null = null;\n\n /**\n * Sets the function that provides the provider API instance.\n *\n * @param operator - Function that returns the provider API instance\n * @returns The builder instance for method chaining\n * @example\n * ```typescript\n * builder.getInstance(() => window.ethereum)\n * ```\n */\n public getInstance(operator: () => ProviderAPI) {\n this.#getInstance = operator;\n return this;\n }\n\n /**\n * Sets the formatter function that converts provider events to account strings.\n *\n * @param operator - Function that takes a provider instance and event, returns array of account strings\n * @returns The builder instance for method chaining\n * @example\n * ```typescript\n * builder.format(async (instance, event) => event.accounts || [])\n * ```\n */\n public format(\n operator: (instance: ProviderAPI, event: EventType) => Promise<string[]>\n ) {\n this.#format = operator;\n return this;\n }\n\n /**\n * Sets the event payload validation function (optional).\n *\n * @param operator - Function that validates if an event payload is valid\n * @returns The builder instance for method chaining\n * @example\n * ```typescript\n * builder.validateEventPayload(event => !!event)\n * ```\n */\n public validateEventPayload(operator: (event: EventType) => boolean) {\n this.#validateEventPayload = operator;\n return this;\n }\n\n /**\n * Sets the event listener attachment function.\n *\n * @param operator - Function that attaches an event listener and optionally returns a cleanup function\n * @returns The builder instance for method chaining\n * @example\n * ```typescript\n * builder.addEventListener((instance, callback) => {\n * return instance.on('accountsChanged', callback);\n * })\n * ```\n */\n public addEventListener(\n operator: (\n instance: ProviderAPI,\n callback: (event: EventType) => void\n ) => (() => void) | void\n ) {\n this.#addEventListener = operator;\n return this;\n }\n\n /**\n * Sets the event listener removal function.\n *\n * @param operator - Function that removes an event listener from the provider\n * @returns The builder instance for method chaining\n * @example\n * ```typescript\n * builder.removeEventListener((instance, callback) => instance.off('accountsChanged', callback))\n * ```\n */\n public removeEventListener(\n operator: (\n instance: ProviderAPI,\n callback: (event: EventType) => void\n ) => void\n ) {\n this.#removeEventListener = operator;\n return this;\n }\n public build<\n ActionsType extends Actions<ActionsType> &\n Actions<AutoImplementedActionsByRecommended>\n >(): [Subscriber<ActionsType>, SubscriberCleanUp<ActionsType>] {\n if (this.#getInstance === null) {\n throw new Error(this.#getErrorMessage('getInstance'));\n }\n if (this.#format === null) {\n throw new Error(this.#getErrorMessage('format'));\n }\n if (this.#addEventListener === null) {\n throw new Error(this.#getErrorMessage('addEventListener'));\n }\n if (this.#removeEventListener === null) {\n throw new Error(this.#getErrorMessage('removeEventListener'));\n }\n\n /**\n * Capture current operator state at build time to ensure immutability.\n *\n * This creates a snapshot of all operators, preventing the built subscriber\n * from being affected by subsequent changes to the builder instance.\n * Each call to build() gets its own isolated set of operators, allowing\n * the builder to be reused for creating multiple independent subscribers.\n */\n const getInstance = this.#getInstance;\n const format = this.#format;\n const addEventListener = this.#addEventListener;\n const removeEventListener = this.#removeEventListener;\n const validateEventPayload = this.#validateEventPayload;\n let subscriber: (event: EventType) => void;\n let unsubscribe: (() => void) | void;\n return [\n async (context) => {\n const [, setState] = context.state();\n const instance = getInstance();\n\n if (!instance) {\n throw new Error(\n 'Trying to subscribe to your wallet, but seems its instance is not available.'\n );\n }\n subscriber = async (event) => {\n if (!!validateEventPayload && !validateEventPayload(event)) {\n context.action('disconnect');\n return;\n }\n setState('accounts', await format(instance, event));\n };\n unsubscribe = addEventListener(instance, subscriber);\n },\n (_, err) => {\n /**\n * Call the cleanup function if addEventListener returned one.\n * This handles providers that return an unsubscribe function from their event listeners.\n */\n if (unsubscribe && typeof unsubscribe === 'function') {\n unsubscribe();\n }\n const instance = getInstance();\n\n /**\n * Always call removeEventListener as well to handle the on/off pattern.\n * This ensures cleanup works regardless of which pattern the provider uses.\n */\n removeEventListener(instance, subscriber);\n\n // subscriber can be passed to `or`, it will get the error and should rethrow error to pass the error to next `or` or throw error.\n return err;\n },\n ];\n }\n #getErrorMessage(operatorName: string) {\n return `Required \"${operatorName}\" operation has not been set for \"changeAccountSubscriber\"`;\n }\n}\n", "import type Transport from '@ledgerhq/hw-transport';\n\nimport { getAltStatusMessage } from '@ledgerhq/errors';\nimport { LegacyNetworks } from '@rango-dev/wallets-core/legacy';\nimport { CAIP_SOLANA_CHAIN_ID } from '@rango-dev/wallets-core/namespaces/solana';\nimport {\n dynamicImportWithRefinedError,\n ETHEREUM_CHAIN_ID,\n type ProviderConnectResult,\n} from '@rango-dev/wallets-shared';\nimport bs58 from 'bs58';\n\nimport { HEXADECIMAL_BASE } from './constants.js';\nimport { getDerivationPath } from './state.js';\n\nexport type Provider = Map<string, unknown>;\n\nexport function ledger(): Provider | null {\n /*\n * Instances have a required property which is `chainId` and is using in swap execution.\n * Here we are setting it as Ethereum always since we are supporting only eth for now.\n */\n const instances = new Map();\n\n instances.set(LegacyNetworks.ETHEREUM, { chainId: ETHEREUM_CHAIN_ID });\n instances.set(LegacyNetworks.SOLANA, { chainId: LegacyNetworks.SOLANA });\n\n return instances;\n}\n\nconst ledgerFrequentErrorMessages: { [statusCode: number]: string } = {\n 0x5515: 'The device is locked',\n 0x650f: 'Related application is not ready on your device',\n 0x6985: 'Action denied by user',\n};\n\nfunction getLedgerErrorMessage(statusCode: number): string {\n if (ledgerFrequentErrorMessages[statusCode]) {\n return ledgerFrequentErrorMessages[statusCode];\n } else if (getAltStatusMessage(statusCode)) {\n return getAltStatusMessage(statusCode) as string;\n }\n\n return `Ledger device unknown error 0x${statusCode.toString(\n HEXADECIMAL_BASE\n )}`; // Hexadecimal numbers are more commonly recognized and utilized for representing ledger error codes\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getLedgerError(error: any) {\n if (error?.statusCode) {\n return new Error(getLedgerErrorMessage(error.statusCode));\n }\n\n if (error?.code === 'INSUFFICIENT_FUNDS') {\n return new Error('Insufficient funds for transaction');\n }\n return error;\n}\n\nexport function standardizeAndThrowLedgerError(_: unknown, error: unknown) {\n throw getLedgerError(error);\n}\n\nexport async function getEthereumAccounts(): Promise<ProviderConnectResult> {\n try {\n const transport = await transportConnect();\n const derivationPath = getDerivationPath();\n\n const eth = new (\n await dynamicImportWithRefinedError(\n async () => await import('@ledgerhq/hw-app-eth')\n )\n ).default(transport);\n\n const accounts: string[] = [];\n\n const result = await eth.getAddress(derivationPath, false, true);\n accounts.push(result.address);\n\n return {\n accounts: accounts,\n chainId: ETHEREUM_CHAIN_ID,\n derivationPath,\n };\n } catch (error: unknown) {\n throw getLedgerError(error);\n } finally {\n await transportDisconnect();\n }\n}\n\nexport async function getSolanaAccounts(): Promise<ProviderConnectResult> {\n try {\n const transport = await transportConnect();\n const derivationPath = getDerivationPath();\n\n const solana = new (\n await dynamicImportWithRefinedError(\n async () => await import('@ledgerhq/hw-app-solana')\n )\n ).default(transport);\n\n const accounts: string[] = [];\n\n const result = await solana.getAddress(derivationPath);\n accounts.push(bs58.encode(result.address));\n\n return {\n accounts: accounts,\n chainId: CAIP_SOLANA_CHAIN_ID,\n derivationPath,\n };\n } catch (error: unknown) {\n throw getLedgerError(error);\n } finally {\n await transportDisconnect();\n }\n}\n\nlet transportConnection: Transport | null = null;\n\nexport async function transportConnect() {\n transportConnection = await (\n await import('@ledgerhq/hw-transport-webhid')\n ).default.create();\n\n return transportConnection;\n}\n\nexport async function transportDisconnect() {\n if (transportConnection) {\n await transportConnection.close();\n transportConnection = null;\n }\n}\n", "/**\n * Note: This only works native async, if we are going to support for old transpilers like Babel.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isAsync(fn: Function) {\n return fn.constructor.name === 'AsyncFunction';\n}\n\nexport function generateStoreId(providerId: string, namespace: string) {\n return `${providerId}$$${namespace}`;\n}\n", "export const ACTION_NOT_FOUND_ERROR = (name: string) =>\n `Couldn't find \"${name}\" action. Are you sure you've added the action?`;\n\nexport const OR_ELSE_ACTION_FAILED_ERROR = (name: string) =>\n `An error occurred during running ${name}`;\n\nexport const BEFORE_ACTION_FAILED_ERROR = (name: string) =>\n `An error occurred during running before for \"${name}\" action`;\n\nexport const NO_STORE_FOUND_ERROR =\n 'For setup store, you should set `store` first.';\n", "import type {\n Actions,\n Context,\n GetState,\n HooksWithOptions,\n Operators,\n RegisteredActions,\n SetState,\n State,\n} from './types.js';\nimport type {\n AndFunction,\n AnyFunction,\n FunctionWithContext,\n} from '../../types/actions.js';\nimport type { NamespaceConfig, Store } from '../store/mod.js';\n\nimport { generateStoreId, isAsync } from '../helpers.js';\n\nimport {\n ACTION_NOT_FOUND_ERROR,\n BEFORE_ACTION_FAILED_ERROR,\n NO_STORE_FOUND_ERROR,\n OR_ELSE_ACTION_FAILED_ERROR,\n} from './errors.js';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Params = any[];\n\n/**\n *\n * A Namespace is a unit of wallets where usually handles connecting, signing, accounts, ...\n * It will be injected by wallet in its object, for example, `window.phantom.ethereum` or `window.phantom.solana`\n * Each namespace (like solana) has its own functionality which is not shared between all the blockchains.\n * For example in EVM namespaces, you can have different networks (e.g. Ethereum,Polygon, ...) and there are specific flows to handle connecting to them or add a network and etc.\n * But Solana doesn't have this concept and you will directly always connect to solana itself.\n * This is true for signing a transaction, getting information about blockchain and more.\n * So by creating a namespace for each of these, we can define a custom namespace based on blockchain's properties.\n *\n */\nclass Namespace<T extends Actions<T>> {\n /** it will be used for `store` and accessing to store by its id mainly. */\n public readonly namespaceId: string;\n /** it will be used for `store` and accessing to store by its id mainly. */\n public readonly providerId: string;\n\n #actions: RegisteredActions<T>;\n #andOperators: Operators<T> = new Map();\n #orOperators: Operators<T> = new Map();\n // `context` for these two can be Namespace context or Provider context\n #beforeHooks: HooksWithOptions<T> = new Map();\n #afterHooks: HooksWithOptions<T> = new Map();\n\n #initiated = false;\n #store: Store | undefined;\n // Namespace doesn't has any configs now, but we will need the feature in future\n // eslint-disable-next-line no-unused-private-class-members\n #configs: NamespaceConfig;\n\n constructor(\n id: string,\n providerId: string,\n options: {\n store?: Store;\n configs?: NamespaceConfig;\n actions: RegisteredActions<T>;\n }\n ) {\n const { configs, actions } = options;\n\n this.namespaceId = id;\n this.providerId = providerId;\n\n this.#configs = configs || new Map();\n this.#actions = actions;\n\n if (options.store) {\n this.store(options.store);\n }\n }\n\n /**\n * This is an special action that will be called **only once**.\n * We don't call this in `constructor` and developer should call this manually. we only ensure it will be called once.\n *\n * ```ts\n * const myInit = () => { whatever; }\n * const actions = new Map();\n * actions.set(\"init\", myInit)\n * const ns = new Namespace(..., {actions});\n *\n * // Will run `myInit`\n * ns.init()\n *\n * // Will not run `myInit` anymore.\n * ns.init()\n * ns.init()\n * ```\n */\n public init(): void {\n if (this.#initiated) {\n return;\n }\n\n const definedInitByUser = this.#actions.get('init');\n\n if (definedInitByUser) {\n definedInitByUser(this.#context());\n }\n // else, this namespace doesn't have any `init` implemented.\n\n this.#initiated = true;\n }\n\n /**\n * Reading states from store and also update them.\n *\n * @example\n * ```ts\n * const ns = new Namespace(...);\n * const [getState, setState] = ns.state();\n * ```\n */\n public state(): [GetState, SetState] {\n const store = this.#store;\n if (!store) {\n throw new Error(\n 'You need to set your store using `.store` method first.'\n );\n }\n\n const id = this.#storeId();\n const setState: SetState = (name, value) => {\n store.getState().namespaces.updateStatus(id, name, value);\n };\n\n const getState: GetState = <K extends keyof State>(name?: K) => {\n const state: State = store.getState().namespaces.getNamespaceData(id);\n\n if (!name) {\n return state;\n }\n\n return state[name];\n };\n\n return [getState, setState];\n }\n\n /**\n * For keeping state, we need a store. all the states will be write to/read from store.\n *\n * Note: Store can be setup on constructor as well.\n *\n * @example\n * ```ts\n * const myStore = createStore();\n * const ns = new Namespace(...);\n * ns.store(myStore);\n * ```\n */\n public store(store: Store): this {\n if (this.#store) {\n console.warn(\n \"You've already set an store for your Namespace. Old store will be replaced by the new one.\"\n );\n }\n this.#store = store;\n this.#setupStore();\n\n return this;\n }\n\n /**\n * It's a boolean operator to run a sync function if action ran successfully.\n * For example, if we have a `connect` action, we can add function to be run after `connect` if it ran successfully.\n *\n * @example\n * ```ts\n * const ns = new Namespace(..);\n *\n * ns.and_then('connect', (context) => {\n * ...\n * });\n * ```\n *\n */\n public and_then<K extends keyof T>(\n actionName: K,\n operatorFn: FunctionWithContext<AndFunction<T, K>, Context>\n ): this {\n const currentAndOperators = this.#andOperators.get(actionName) || [];\n this.#andOperators.set(actionName, currentAndOperators.concat(operatorFn));\n\n return this;\n }\n\n /**\n * It's a boolean operator to run a function to handle when an action fails.\n * For example, if we have a `connect` action, we can add function to be run when `connect` fails (throw an error).\n *\n * @example\n * ```ts\n * const ns = new Namespace(..);\n *\n * ns.or_else('connect', (context, error) => {\n * ...\n * });\n * ```\n */\n public or_else<K extends keyof T>(\n actionName: K,\n operatorFn: FunctionWithContext<AnyFunction, Context>\n ): this {\n const currentOrOperators = this.#orOperators.get(actionName) || [];\n this.#orOperators.set(actionName, currentOrOperators.concat(operatorFn));\n\n return this;\n }\n\n /**\n * Running a function after a specific action\n *\n * Note: the context can be set from outside as well. this is useful for Provider to set its context instead of namespace context.\n *\n * @example\n * ```ts\n * const ns = new Namespace(...);\n *\n * ns.after(\"connect\", (context) => {});\n * ```\n */\n public after<K extends keyof T, C = unknown>(\n actionName: K,\n hook: FunctionWithContext<AnyFunction, C>,\n options?: { context?: C }\n ): this {\n const currentAfterHooks = this.#afterHooks.get(actionName) || [];\n const hookWithOptions = {\n hook,\n options: {\n context: options?.context,\n },\n };\n\n this.#afterHooks.set(actionName, currentAfterHooks.concat(hookWithOptions));\n return this;\n }\n\n /**\n * Running a function before a specific action\n *\n * Note: the context can be set from outside as well. this is useful for Provider to set its context instead of using namespace context.\n *\n * @example\n * ```ts\n * const ns = new Namespace(...);\n *\n * ns.before(\"connect\", (context) => {});\n * ```\n */\n public before<K extends keyof T, C = unknown>(\n actionName: K,\n hook: FunctionWithContext<AnyFunction, C>,\n options?: { context?: C }\n ): this {\n const currentBeforeHooks = this.#beforeHooks.get(actionName) || [];\n const hookWithOptions = {\n hook,\n options: {\n context: options?.context,\n },\n };\n this.#beforeHooks.set(\n actionName,\n currentBeforeHooks.concat(hookWithOptions)\n );\n\n return this;\n }\n public has<K extends keyof T>(actionName: K): boolean {\n return !!this.#actions.get(actionName);\n }\n /**\n *\n * Registered actions will be called using `run`. it will run an action and all the operators or hooks that assigned.\n *\n * @example\n * ```ts\n * const actions = new Map();\n * actions.set('connect', connectAction);\n *\n * const ns = new Namespace(NAMESPACE, PROVIDER_ID, {\n * actions: actions,\n * });\n *\n * ns.run(\"action\");\n * ```\n */\n public run<K extends keyof T>(\n actionName: K,\n ...args: Params\n ): unknown | Promise<unknown> {\n const action = this.#actions.get(actionName);\n if (!action) {\n throw new Error(ACTION_NOT_FOUND_ERROR(actionName.toString()));\n }\n\n /*\n * Action can be both, sync or async. To simplify the process we can not make `sync` mode to async\n * Since every user's sync action will be an async function and affect what user expect,\n * it makes all the actions async and it doesn't match with Namespace interface (e.g. EvmActions)\n *\n * To avoid this issue and also not duplicating code, I broke the process into smaller methods\n * and two main methods to run actions: tryRunAsyncAction & tryRunAction.\n */\n const result = isAsync(action)\n ? this.#tryRunAsyncAction(actionName, args)\n : this.#tryRunAction(actionName, args);\n\n return result;\n }\n\n #tryRunAction<K extends keyof T>(actionName: K, params: Params): unknown {\n try {\n this.#tryRunBeforeHooks(actionName);\n } catch (error) {\n this.#tryRunAfterHooks(actionName);\n throw new Error(BEFORE_ACTION_FAILED_ERROR(actionName.toString()), {\n cause: error,\n });\n }\n\n const action = this.#actions.get(actionName);\n if (!action) {\n throw new Error(ACTION_NOT_FOUND_ERROR(actionName.toString()));\n }\n\n const context = this.#context();\n\n let result;\n try {\n result = action(context, ...params);\n result = this.#tryRunAndOperators(actionName, result);\n } catch (e) {\n result = this.#tryRunOrOperators(actionName, e);\n } finally {\n this.#tryRunAfterHooks(actionName);\n }\n\n return result;\n }\n\n async #tryRunAsyncAction<K extends keyof T>(\n actionName: K,\n params: Params\n ): Promise<unknown> {\n try {\n this.#tryRunBeforeHooks(actionName);\n } catch (error) {\n this.#tryRunAfterHooks(actionName);\n throw new Error(BEFORE_ACTION_FAILED_ERROR(actionName.toString()), {\n cause: error,\n });\n }\n\n const action = this.#actions.get(actionName);\n if (!action) {\n throw new Error(ACTION_NOT_FOUND_ERROR(actionName.toString()));\n }\n\n const context = this.#context();\n return await action(context, ...params)\n .then((result: unknown) => this.#tryRunAndOperators(actionName, result))\n .catch((e: unknown) => this.#tryRunOrOperators(actionName, e))\n .finally(() => this.#tryRunAfterHooks(actionName));\n }\n\n #tryRunAfterHooks<K extends keyof T>(actionName: K) {\n const afterActions = this.#afterHooks.get(actionName);\n\n if (afterActions) {\n afterActions.forEach((afterAction) => {\n const context = afterAction.options?.context || this.#context();\n afterAction.hook(context);\n });\n }\n }\n\n #tryRunBeforeHooks<K extends keyof T>(actionName: K): void {\n const beforeActions = this.#beforeHooks.get(actionName);\n if (beforeActions) {\n beforeActions.forEach((beforeAction) => {\n const context = beforeAction.options?.context || this.#context();\n beforeAction.hook(context);\n });\n }\n }\n\n #tryRunAndOperators<K extends keyof T>(\n actionName: K,\n result: unknown\n ): unknown {\n const andActions = this.#andOperators.get(actionName);\n\n if (andActions) {\n const context = this.#context();\n result = andActions.reduce((prev, andAction) => {\n return andAction(context, prev);\n }, result);\n }\n return result;\n }\n\n #tryRunOrOperators<K extends keyof T>(\n actionName: K,\n actionError: unknown\n ): unknown {\n const orActions = this.#orOperators.get(actionName);\n\n if (orActions) {\n try {\n const context = this.#context();\n return orActions.reduce((prev, orAction) => {\n return orAction(context, prev);\n }, actionError);\n } catch (orActionError) {\n if (orActionError instanceof Error) {\n orActionError.cause = actionError;\n throw orActionError;\n }\n const errorMessage = OR_ELSE_ACTION_FAILED_ERROR(\n `${actionName.toString()} for ${this.namespaceId} namespace.`\n );\n const standardOrActionError = new Error(String(orActionError), {\n cause: actionError,\n });\n throw new Error(errorMessage, { cause: standardOrActionError });\n }\n } else {\n throw actionError;\n }\n }\n\n #setupStore(): void {\n const store = this.#store;\n if (!store) {\n throw new Error(NO_STORE_FOUND_ERROR);\n }\n\n const id = this.#storeId();\n store.getState().namespaces.addNamespace(id, {\n namespaceId: this.namespaceId,\n providerId: this.providerId,\n });\n }\n\n #storeId() {\n return generateStoreId(this.providerId, this.namespaceId);\n }\n\n #context(): Context<T> {\n return {\n state: this.state.bind(this),\n action: this.run.bind(this),\n };\n }\n}\n\nexport { Namespace };\n", "import type {\n CommonNamespaces,\n Context,\n ExtendableInternalActions,\n GetState,\n RegisteredNamespaces,\n SetState,\n State,\n} from './types.js';\nimport type { FindProxiedNamespace } from '../../builders/mod.js';\nimport type { AnyFunction, FunctionWithContext } from '../../types/actions.js';\nimport type { ProviderConfig, ProviderInfo, Store } from '../store/mod.js';\n\nconst VERSION = '1.0';\n\nexport class Provider {\n public readonly id: string;\n public readonly version = VERSION;\n\n #namespaces: RegisteredNamespaces<keyof CommonNamespaces, CommonNamespaces>;\n #initiated = false;\n #extendInternalActions: ExtendableInternalActions = {};\n #store: Store | undefined;\n #configs: ProviderConfig;\n\n constructor(\n id: string,\n namespaces: RegisteredNamespaces<keyof CommonNamespaces, CommonNamespaces>,\n configs: ProviderConfig,\n options?: {\n /**\n * There are some cases we need to have a behavior like initializing a provider which will be run when we are creating an instance.\n * These internal steps and behaviors will be useful for library user to extend the behavior by running a specific code.\n */\n extendInternalActions?: ExtendableInternalActions;\n store?: Store;\n }\n ) {\n this.id = id;\n this.#configs = configs;\n // it should be only created here, to make sure `after/before` will work properly.\n this.#extendInternalActions = options?.extendInternalActions || {};\n this.#namespaces = namespaces;\n\n /**\n * Our assumption is that the store will be optional for the provider.\n * If a store is provided in the options, it will be initialized and set up.\n */\n if (options?.store) {\n this.#store = options.store;\n this.#setupStore();\n }\n }\n\n /**\n * This is an special callback that will be called **only once**.\n * We don't call this in `constructor` and developer should call this manually. we only ensure it will be called once.\n *\n * ```ts\n * const myInit = () => { whatever; } *\n * const provider = new Provider(..., {extendInternalActions: {init: myInit} });\n *\n * // Will run `myInit`\n * provider.init()\n *\n * // Will not run `myInit` anymore.\n * provider.init()\n * provider.init()\n * ```\n */\n public init(): void {\n if (this.#initiated) {\n return;\n }\n\n const definedInitByUser = this.#extendInternalActions.init;\n if (definedInitByUser) {\n definedInitByUser(this.#context());\n }\n\n this.#initiated = true;\n }\n\n /**\n * Getting state of a provider\n *\n * **Note:**\n * Each namespace has it's own state as well, in Legacy we didn't have this separation and all of them was accessible through Provider itself\n * To be compatible with legacy, `getState` has a logic to guess the final state to produce same state as legacy.\n *\n * @example\n * ```ts\n * const provider = new Provider(...);\n * const [getState, setState] = provider.state();\n *\n * getState('installed');\n * // or\n * getState().installed;\n * ```\n *\n */\n public state(): [GetState, SetState] {\n const store = this.#store;\n if (!store) {\n throw new Error(\n `Any store detected for ${this.id}. You need to set your store using '.store' method first.`\n );\n }\n\n /**\n * State updater\n */\n const setState: SetState = (name, value) => {\n switch (name) {\n case 'installed':\n return store.getState().providers.updateStatus(this.id, name, value);\n default:\n throw new Error(\n `Unhandled state update for provider. (provider id: ${this.id}, state name: ${name})`\n );\n }\n };\n\n /**\n * State getter\n */\n const getState: GetState = <K extends keyof State>(name?: K) => {\n const state: State = store\n .getState()\n .providers.guessNamespacesState(this.id);\n\n if (!name) {\n return state;\n }\n\n switch (name) {\n case 'installed':\n case 'connected':\n case 'connecting':\n return state[name];\n default:\n throw new Error('Unhandled state for provider');\n }\n };\n\n return [getState, setState];\n }\n\n /**\n * For keeping state, we need a store. all the states will be write to/read from store.\n *\n * **Note: When you are setting an store for provider, it will be set for its namespaces automatically as well**\n *\n * @example\n * ```ts\n * const myStore = createStore();\n * const provider = new Provider(...);\n * provider.store(myStore); // or it can be passed to Provider constructor;\n * ```\n */\n public store(store: Store): this {\n if (this.#store) {\n console.warn(\n \"You've already set an store for your Provider. Old store will be replaced by the new one.\"\n );\n }\n this.#store = store;\n this.#setupStore();\n return this;\n }\n\n /**\n * Getting information about a provider which has been set on constructing Provider.\n *\n * @example\n * ```ts\n * const walletInfo = {name: \"Garbage wallet\", ...}\n * const provider = new Provider(..., {info: walletInfo});\n *\n * provider.info();\n * ```\n */\n public info(): ProviderInfo | undefined {\n const store = this.#store;\n if (!store) {\n return this.#configs;\n }\n const config = store.getState().providers.list[this.id].config;\n\n return { metadata: config.metadata, deepLink: config.deepLink };\n }\n\n /**\n * A list of registered _proxied_ namespaces.\n *\n * @example\n * ```ts\n * const provider = new Provider(...);\n * const allNamespaces = provider.getAll();\n * ```\n */\n public getAll(): RegisteredNamespaces<\n keyof CommonNamespaces,\n CommonNamespaces\n > {\n return this.#namespaces;\n }\n\n /**\n * Get a registered namespace in provider by its **namespace key**.\n *\n * Note: difference between namespace key and namespace id is the first one is setting from a predefined list the second one can be anything and will be chosen by library's user.\n *\n * @param {string} id - evm, solana, cosmos, ... (CommonActions)\n */\n public get<K extends keyof CommonNamespaces>(\n id: K\n ): FindProxiedNamespace<K, CommonNamespaces> | undefined {\n return this.#namespaces.get(id) as unknown as\n | FindProxiedNamespace<K, CommonNamespaces>\n | undefined;\n }\n\n /**\n *\n * Get a registered namespace by its **namespaceId**.\n *\n * Note: difference between namespace key and namespace id is the first one is setting from a predefined list the second one can be anything and will be chosen by library's user.\n *\n * @example\n * ```ts\n * const provider = new Provider(...);\n * provider.findByNamespace(\"whatever-id-i-set-for-namespace\")\n * ```\n */\n public findByNamespace<K extends keyof CommonNamespaces>(\n namespaceLookingFor: K | string\n ): FindProxiedNamespace<K, CommonNamespaces> | undefined {\n // If we didn't found any match, we will return `undefined`.\n let result: object | undefined = undefined;\n\n this.#namespaces.forEach((namespace) => {\n if (namespace.namespaceId === namespaceLookingFor) {\n result = namespace;\n }\n });\n\n return result;\n }\n\n /**\n * Running a hook function _after_ a specific action for **all registered namespaces**.\n *\n * **Note:** the context can be set from outside as well. this is useful for Provider to set its context instead of namespace context.\n *\n * @example\n * ```ts\n * const provider = new Provider(...);\n *\n * provider.after(\"connect\", (context) => {});\n * ```\n */\n public before(\n actionName: string,\n hookFn: FunctionWithContext<AnyFunction, Context>\n ): this {\n this.#addHook('before', actionName, hookFn);\n return this;\n }\n\n /**\n * Running a hook function _before_ a specific action for **all registered namespaces**.\n *\n * **Note:** the context can be set from outside as well. this is useful for Provider to set its context instead of namespace context.\n *\n * @example\n * ```ts\n * const provider = new Provider(...);\n *\n * provider.after(\"connect\", (context) => {});\n * ```\n */\n public after(\n actionName: string,\n hookFn: FunctionWithContext<AnyFunction, Context>\n ): this {\n this.#addHook('after', actionName, hookFn);\n return this;\n }\n\n #addHook(\n hookName: 'after' | 'before',\n actionName: string,\n cb: FunctionWithContext<AnyFunction, Context>\n ): this {\n const context = {\n state: this.state.bind(this),\n };\n\n this.#namespaces.forEach((namespace) => {\n if (hookName === 'after') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n namespace.after(actionName as any, cb, {\n context,\n });\n } else if (hookName === 'before') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n namespace.before(actionName as any, cb, {\n context,\n });\n } else {\n throw new Error(`You hook name is invalid: ${hookName}`);\n }\n });\n\n return this;\n }\n\n #setupStore(): void {\n const store = this.#store;\n if (!store) {\n throw new Error('For setup store, you should set `store` first.');\n }\n store.getState().providers.addProvider(this.id, this.#configs);\n this.#namespaces.forEach((provider) => {\n provider.store(store);\n });\n }\n\n #context(): Context {\n return {\n state: this.state.bind(this),\n };\n }\n}\n", "import type { Namespace, State as NamespaceState } from './namespaces/mod.js';\nimport type { Provider, State as ProviderState } from './provider/mod.js';\nimport type { Store } from './store/mod.js';\n\ntype HubState = {\n [key in string]: ProviderState & {\n namespaces: NamespaceState[];\n };\n};\n\ntype RunAllResult = {\n id: string;\n provider: unknown;\n namespaces: unknown[];\n};\n\ninterface HubOptions {\n store?: Store;\n}\nexport class Hub {\n #providers = new Map<string, Provider>();\n #options: HubOptions;\n\n constructor(options?: HubOptions) {\n this.#options = options ?? {};\n }\n\n init() {\n this.runAll('init');\n }\n\n /*\n * Running a specific action (e.g. init) on all namespaces and providers one by one.\n *\n * TODO: Some of methods may accepts args, with this implementation we only limit to those one without any argument.\n */\n runAll(action: string): RunAllResult[] {\n const output: RunAllResult[] = [];\n\n // run action on all providers eagerConnect, disconnect\n const providers = this.#providers.values();\n\n for (const provider of providers) {\n // Calling `action` on `Provider` if exists.\n const providerOutput: RunAllResult = {\n id: provider.id,\n provider: undefined,\n namespaces: [],\n };\n\n const providerMethod = provider[action as keyof Provider];\n if (typeof providerMethod === 'function') {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n providerOutput.provider = providerMethod.call(provider);\n }\n\n // Namespace instances can have their own `action` as well. we will call them as well.\n const namespaces = provider.getAll().values();\n for (const namespace of namespaces) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n const namespaceMethod = namespace[action];\n if (typeof namespaceMethod === 'function') {\n const result = namespaceMethod();\n providerOutput.namespaces.push(result);\n }\n }\n\n output.push(providerOutput);\n }\n\n return output;\n }\n\n add(id: string, provider: Provider) {\n if (this.#options.store) {\n provider.store(this.#options.store);\n }\n this.#providers.set(id, provider);\n return this;\n }\n remove(id: string) {\n const providerToRemove = this.#providers.get(id);\n\n if (!providerToRemove) {\n throw new Error(`Provider not found: No provider exists with ID \"${id}\"`);\n }\n\n this.#options.store?.getState().providers.removeProvider(id);\n this.#providers.delete(id);\n\n return this;\n }\n\n get(providerId: string): Provider | undefined {\n return this.#providers.get(providerId);\n }\n\n getAll() {\n return this.#providers;\n }\n\n state(): HubState {\n const output = this.runAll('state');\n const res: HubState = {};\n\n output.forEach((result) => {\n const namespaces: NamespaceState[] = [];\n result.namespaces.forEach((b) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const [getNamespaceState] = b as ReturnType<Namespace<any>['state']>;\n\n namespaces.push(getNamespaceState());\n });\n\n const [getProviderState] = result.provider as ReturnType<\n Provider['state']\n >;\n\n res[result.id] = {\n ...(getProviderState() || {}),\n namespaces: namespaces,\n };\n });\n return res;\n }\n}\n", "/**\n * Note: Zustand has some difficulty when you are trying to `previous` state on `subscribe`.\n * If these selectors define inside store directly and use `get()` for accessing state, it will get the latest state\n * instead of previous state which desired.\n * So make them a helper will let us to reuse them both in store and outside of store in a `subscribe`.\n */\nimport type { State } from '../mod.js';\nimport type { State as InternalProviderState } from '../provider/mod.js';\n\n/**\n * Legacy provider state includes `connecting` and `connected` values. It hadn't a separation layer for `namespaces`.\n * For compatibility reasons, we should produce these two values somehow.\n *\n * Currently, We return `true` if any of namespaces return true. We are missing failed namespace here.\n * But if we want to solve that, we should migrate our client code to use `namespace` state directly and not from `provider`\n */\nexport function guessProviderStateSelector(\n state: State,\n providerId: string\n): InternalProviderState {\n /*\n * We keep namespaces in a separate branch than providers.\n * We should look at all of them and find all the namespaces that for our current proivder.\n */\n const allNamespaces = state.namespaces.list;\n const currentProviderNamespaces = Object.keys(allNamespaces).filter(\n (key) => allNamespaces[key].info.providerId === providerId\n );\n\n // Returning provider state value directly.\n const installed = !!state.providers.list[providerId]?.data.installed;\n\n /*\n * If any namespaces returns `true`, we consider the whole provider for this field to be `true`.\n * it has a downside regarding errors which explained on top of the function.\n */\n const connected =\n currentProviderNamespaces.length > 0\n ? currentProviderNamespaces.some(\n (key) => allNamespaces[key].data.connected\n )\n : false;\n const connecting =\n currentProviderNamespaces.length > 0\n ? currentProviderNamespaces.some(\n (key) => allNamespaces[key].data.connecting\n )\n : false;\n\n return {\n installed,\n connected,\n connecting,\n };\n}\n\nexport function namespaceStateSelector(state: State, storeId: string) {\n return state.namespaces.list[storeId].data;\n}\n", "import type { StoreApi } from 'zustand/vanilla';\n\nimport { createStore as createZustandStore } from 'zustand/vanilla';\n\nimport { extend, type Store } from './extend.js';\nimport { hubStore, type HubStore } from './hub.js';\nimport { namespacesStore, type NamespaceStore } from './namespaces.js';\nimport { providersStore, type ProviderStore } from './providers.js';\n\n/************ State ************/\n\nexport interface State {\n hub: HubStore;\n providers: ProviderStore;\n namespaces: NamespaceStore;\n}\n\nexport type RawStore = StoreApi<State>;\n\nexport const createStore = (): Store => {\n const store = createZustandStore<State>((...api) => {\n return {\n hub: hubStore(...api),\n providers: providersStore(...api),\n namespaces: namespacesStore(...api),\n };\n });\n\n return extend(store);\n};\n", "import type {\n Event,\n ProviderConnectedEvent,\n ProviderConnectingEvent,\n ProviderDisconnectedEvent,\n} from './events.js';\nimport type { RawStore, State } from './store.js';\n\nimport { guessProviderStateSelector } from './selectors.js';\n\nexport interface Store extends Omit<RawStore, 'subscribe'> {\n subscribe(listener: (event: Event, state: State, prevState: State) => void): {\n flushEvents(): void;\n };\n}\n\n/**\n * Zustand's store provides a set of built-in functionalities,\n * but it may not meet all our requirements.\n * This function modifies the interface and adds or updates the available methods.\n */\nexport function extend(store: RawStore): Store {\n const extendedSubscribe: (store: RawStore) => Store['subscribe'] =\n (store) => (listener) => {\n const executeListener = (\n events: Event[],\n state: State,\n prevState: State\n ) => {\n for (const ev of events) {\n listener(ev, state, prevState);\n }\n };\n\n /*\n * only known changes will fire event for lib users\n * so all the changes in store won't trigger a user-face event\n */\n store.subscribe((state, prevState) => {\n const eventsLike = getEventsLike(state, prevState);\n const events = tryConsumeEvents(state);\n const allQueuedEvents = [...events, ...eventsLike];\n executeListener(allQueuedEvents, state, prevState);\n });\n\n return {\n /**\n * Manually run pending events.\n * This useful when use `subscribe` method after sometime and when store initialized.\n *\n * Note: Please consider both current and previous state will be same and we don't have access to previous state in a such scenario.\n */\n flushEvents: () => {\n const state = store.getState();\n const events = tryConsumeEvents(state);\n executeListener(events, state, state);\n },\n };\n };\n\n return new Proxy(store, {\n get: function (target, prop, receiver) {\n if (prop === 'subscribe') {\n return extendedSubscribe(target);\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as unknown as Store;\n}\n\n/**\n * Retrieves the ConsumableEvent from the store and returns its values.\n * The values will be consumed by iterating over the field.\n */\nfunction tryConsumeEvents(state: State): Event[] {\n return [...state.providers.events, ...state.namespaces.events];\n}\n\n/**\n * In certain cases, adding events to the store is not possible (e.g., namespace or provider layer).\n * In these cases, we observe store changes and treat specific patterns as events when detected.\n *\n * Note: This approach should be avoided in most cases. It is used here to maintain backward compatibility\n * with the provider's legacy interface.\n */\nfunction getEventsLike(state: State, prevState: State): Event[] {\n const events: Event[] = [];\n\n for (const providerId of Object.keys(state.providers.list)) {\n const currentProviderState = guessProviderStateSelector(state, providerId);\n const previousProviderState = guessProviderStateSelector(\n prevState,\n providerId\n );\n\n if (previousProviderState.connecting !== currentProviderState.connecting) {\n const ev: ProviderConnectingEvent = {\n type: 'provider_connecting',\n provider: providerId,\n value: currentProviderState.connecting,\n };\n events.push(ev);\n }\n\n if (!previousProviderState.connected && currentProviderState.connected) {\n const ev: ProviderConnectedEvent = {\n type: 'provider_connected',\n provider: providerId,\n };\n\n events.push(ev);\n }\n\n if (previousProviderState.connected && !currentProviderState.connected) {\n const ev: ProviderDisconnectedEvent = {\n type: 'provider_disconnected',\n provider: providerId,\n };\n\n events.push(ev);\n }\n }\n\n return events;\n}\n", "/************ Hub ************/\n\nimport type { State } from './mod.js';\nimport type { StateCreator } from 'zustand';\n\ntype HubConfig = object;\n\nexport interface HubStore {\n config: HubConfig;\n}\n\ntype HubStateCreator = StateCreator<State, [], [], HubStore>;\n\nconst hubStore: HubStateCreator = () => ({\n config: {},\n});\n\nexport { hubStore };\n", "/************ Namespace ************/\n\nimport type { StateCreator } from 'zustand';\n\nimport { produce } from 'immer';\n\nimport {\n ConsumableEvents,\n type NamespaceConnectedEvent,\n type NamespaceDisconnectedEvent,\n type NamespaceSwitchedAccountEvent,\n type NamespaceSwitchedNetworkEvent,\n} from './events.js';\nimport { namespaceStateSelector, type State } from './mod.js';\n\n// Currently, namespace doesn't has any config.\nexport type NamespaceConfig = object;\n\nexport interface NamespaceData {\n accounts: null | string[];\n network: null | string;\n connected: boolean;\n connecting: boolean;\n}\n\ninterface NamespaceInfo {\n providerId: string;\n namespaceId: string;\n}\n\ninterface NamespaceItem {\n info: NamespaceInfo;\n data: NamespaceData;\n error: unknown;\n}\n\ntype NamespaceState = {\n events: InstanceType<typeof ConsumableEvents>;\n list: Record<string, NamespaceItem>;\n};\n\ninterface NamespaceActions {\n addNamespace: (id: string, config: NamespaceInfo) => void;\n updateStatus: <K extends keyof NamespaceData>(\n id: string,\n key: K,\n value: NamespaceData[K]\n ) => void;\n\n _produceEventsWhenUpdatingStatus: <K extends keyof NamespaceData>(\n namespace: NamespaceItem,\n id: string,\n key: K,\n value: NamespaceData[K]\n ) => void;\n}\ninterface NamespaceSelectors {\n getNamespaceData(storeId: string): NamespaceData;\n}\n\nexport type NamespaceStore = NamespaceState &\n NamespaceActions &\n NamespaceSelectors;\ntype NamespaceStateCreator = StateCreator<State, [], [], NamespaceStore>;\n\nconst namespacesStore: NamespaceStateCreator = (set, get) => ({\n events: new ConsumableEvents(),\n\n list: {},\n addNamespace: (id, info) => {\n const data: NamespaceData = {\n accounts: null,\n network: null,\n connected: false,\n connecting: false,\n };\n\n const item = {\n data,\n error: '',\n info,\n };\n\n set(\n produce((state: State) => {\n state.namespaces.list[id] = item;\n })\n );\n },\n updateStatus: (id, key, value) => {\n const ns = get().namespaces.list[id];\n if (!ns) {\n throw new Error(`No namespace with '${id}' found.`);\n }\n\n get().namespaces._produceEventsWhenUpdatingStatus(ns, id, key, value);\n\n // Updating state\n set(\n produce((state: State) => {\n state.namespaces.list[id].data[key] = value;\n })\n );\n },\n getNamespaceData(storeId) {\n return namespaceStateSelector(get(), storeId);\n },\n\n _produceEventsWhenUpdatingStatus: (namespace, id, key, value) => {\n if (key === 'accounts') {\n // check for both null and empty array\n const isAccountsEmpty =\n Object.is(value, null) || (Array.isArray(value) && value.length === 0);\n\n if (isAccountsEmpty) {\n const currentConnectedStatus = get().namespaces.list[id].data.connected;\n if (currentConnectedStatus) {\n const event: NamespaceDisconnectedEvent = {\n type: 'namespace_disconnected',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n };\n\n get().namespaces.events.push(event);\n }\n // Skip emitting disconnect event, if the `connected` is false\n } else {\n const currentAccounts = get().namespaces.list[id].data.accounts;\n\n if (!currentAccounts) {\n const event: NamespaceConnectedEvent = {\n type: 'namespace_connected',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n accounts: value as string[],\n };\n\n get().namespaces.events.push(event);\n } else {\n const areSameAccounts =\n currentAccounts.sort().toString() ===\n (value as string[]).sort().toString();\n\n if (!areSameAccounts) {\n const event: NamespaceSwitchedAccountEvent = {\n type: 'namespace_account_switched',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n previousAccounts: currentAccounts,\n accounts: value as string[],\n };\n\n get().namespaces.events.push(event);\n }\n }\n }\n } else if (key === 'network') {\n const currentNetwork = get().namespaces.list[id].data.network;\n\n const event: NamespaceSwitchedNetworkEvent = {\n type: 'namespace_network_switched',\n provider: namespace.info.providerId,\n namespace: namespace.info.namespaceId,\n network: value as string,\n previousNetwork: currentNetwork,\n };\n\n get().namespaces.events.push(event);\n }\n },\n});\n\nexport { namespacesStore };\n", "export type NamespaceDisconnectedEvent = {\n type: 'namespace_disconnected';\n provider: string;\n namespace: string;\n};\n\nexport type NamespaceConnectedEvent = {\n type: 'namespace_connected';\n provider: string;\n namespace: string;\n accounts: string[];\n};\n\nexport type NamespaceSwitchedAccountEvent = {\n type: 'namespace_account_switched';\n provider: string;\n namespace: string;\n accounts: string[];\n previousAccounts: string[];\n};\n\nexport type NamespaceSwitchedNetworkEvent = {\n type: 'namespace_network_switched';\n provider: string;\n namespace: string;\n network: string;\n previousNetwork: string | null;\n};\n\nexport type ProviderDetectedEvent = {\n type: 'provider_detected';\n provider: string;\n};\n\nexport type ProviderConnectingEvent = {\n type: 'provider_connecting';\n provider: string;\n value: boolean;\n};\n\nexport type ProviderConnectedEvent = {\n type: 'provider_connected';\n provider: string;\n};\n\nexport type ProviderDisconnectedEvent = {\n type: 'provider_disconnected';\n provider: string;\n};\n\nexport type Event =\n | NamespaceDisconnectedEvent\n | NamespaceConnectedEvent\n | NamespaceSwitchedAccountEvent\n | NamespaceSwitchedNetworkEvent\n | ProviderDetectedEvent\n | ProviderConnectingEvent\n | ProviderConnectedEvent\n | ProviderDisconnectedEvent;\n\n/**\n *\n * Keeping an array of Event and when iterates over its values, it will be removed (consume) from the array.\n *\n */\nexport class ConsumableEvents {\n #data: Event[] = [];\n\n push(val: Event) {\n this.#data.push(val);\n }\n\n [Symbol.iterator](): Iterator<Event> {\n return {\n next: (): IteratorResult<Event> => {\n if (this.#data.length == 0) {\n return { done: true, value: undefined };\n }\n\n // Typescript can not narrow the type, but we have a runtime check to ensure it will never be an empty list\n const value = this.#data.shift()!;\n return {\n done: false,\n value,\n };\n },\n };\n }\n}\n", "import type { Namespace } from '../../namespaces/common/types.js';\nimport type {\n GenerateDeepLink,\n State as InternalProviderState,\n} from '../provider/mod.js';\nimport type { BlockchainMeta, SignerFactory } from 'rango-types';\nimport type { StateCreator } from 'zustand';\n\nimport { produce } from 'immer';\n\nimport { ConsumableEvents, type ProviderDetectedEvent } from './events.js';\nimport { guessProviderStateSelector, type State } from './mod.js';\n\ntype Browsers = 'firefox' | 'chrome' | 'edge' | 'brave' | 'homepage';\ntype Property<N extends string, V> = { name: N; value: V };\n\ntype NamespacesProperty = Property<\n 'namespaces',\n {\n selection: 'single' | 'multiple';\n data: {\n label: string;\n id: string;\n value: Namespace;\n unsupported?: boolean;\n getSupportedChains: (chains: BlockchainMeta[]) => BlockchainMeta[];\n }[];\n }\n>;\ntype DerivationPathProperty = Property<\n 'derivationPath',\n {\n data: {\n id: string;\n label: string;\n namespace: Namespace;\n generateDerivationPath: (index: string) => string;\n }[];\n }\n>;\ntype DetailsProperty = Property<\n 'details',\n {\n mobileWallet?: boolean;\n showOnMobile?: boolean;\n isContractWallet?: boolean;\n }\n>;\ntype SignersProperty = Property<\n 'signers',\n {\n getSigners: () => Promise<SignerFactory>;\n }\n>;\n\nexport type ProviderMetadata = {\n name: string;\n icon: string;\n extensions: Partial<Record<Browsers, string>>;\n properties?: Array<\n | NamespacesProperty\n | DerivationPathProperty\n | DetailsProperty\n | SignersProperty\n >;\n};\n\nexport interface ProviderConfig {\n metadata: ProviderMetadata;\n deepLink?: GenerateDeepLink;\n}\n\nexport type ProviderInfo = ProviderConfig;\n\ninterface ProviderData {\n installed: boolean;\n}\n\ninterface ProviderItem {\n config: ProviderConfig;\n data: ProviderData;\n error: unknown;\n}\n\ntype ProviderState = {\n events: ConsumableEvents;\n list: Record<string, ProviderItem>;\n};\ninterface ProviderActions {\n addProvider: (id: string, config: ProviderConfig) => void;\n removeProvider: (id: string) => void;\n updateStatus: <K extends keyof ProviderData>(\n id: string,\n key: K,\n value: ProviderData[K]\n ) => void;\n\n _produceEventsWhenUpdatingStatus: <K extends keyof ProviderData>(\n provider: ProviderItem,\n id: string,\n key: K,\n value: ProviderData[K]\n ) => void;\n}\n\ninterface ProviderSelectors {\n /**\n * Provider has a limited state to itself, to be compatible with legacy, we try to produce same object as legacy\n * which includes namespace state as well.\n */\n guessNamespacesState: (id: string) => InternalProviderState;\n}\n\nexport type ProviderStore = ProviderState & ProviderActions & ProviderSelectors;\ntype ProvidersStateCreator = StateCreator<State, [], [], ProviderStore>;\n\nconst providersStore: ProvidersStateCreator = (set, get) => ({\n events: new ConsumableEvents(),\n\n list: {},\n addProvider: (id, config) => {\n const item = {\n data: {\n installed: false,\n },\n error: '',\n config,\n };\n\n set(\n produce((state: State) => {\n state.providers.list[id] = item;\n })\n );\n },\n removeProvider: (id) => {\n set(\n produce((state: State) => {\n delete state.providers.list[id];\n })\n );\n },\n updateStatus: (id, key, value) => {\n const provider = get().providers.list[id];\n if (!provider) {\n throw new Error(`No namespace namespace with '${id}' found.`);\n }\n\n get().providers._produceEventsWhenUpdatingStatus(provider, id, key, value);\n\n set(\n produce((state: State) => {\n state.providers.list[id].data[key] = value;\n })\n );\n },\n guessNamespacesState: (providerId: string): InternalProviderState => {\n return guessProviderStateSelector(get(), providerId);\n },\n\n _produceEventsWhenUpdatingStatus: (_provider, id, key, _value) => {\n if (key === 'installed') {\n const event: ProviderDetectedEvent = {\n type: 'provider_detected',\n provider: id,\n };\n\n get().providers.events.push(event);\n }\n },\n});\n\nexport { providersStore };\n", "import type { ActionByBuilder } from './action.js';\nimport type { ProxiedNamespace } from './types.js';\nimport type { Actions, ActionsMap, Context } from '../hub/namespaces/mod.js';\nimport type { NamespaceConfig } from '../hub/store/mod.js';\nimport type { FunctionWithContext } from '../types/actions.js';\n\nimport { Namespace } from '../hub/mod.js';\n\n/**\n * There are Namespace's methods that should be called directly on Proxy object.\n * The Proxy object is creating in `.build`.\n */\nexport const allowedMethods = [\n 'init',\n 'state',\n 'after',\n 'before',\n 'and_then',\n 'or_else',\n 'store',\n] as const;\n/**\n * List of value types that are considered safe to return directly when\n * accessing properties on a proxied `Namespace`.\n *\n * This is useful for allowing public values like `version` to be accessed.\n * If a property's value is of one of these types (e.g.,`'string'`, `'number'`),\n * it will be returned as-is.\n *\n * @const {Array<'string' | 'number'>} allowedPublicValues\n */\nconst allowedPublicValues = ['string', 'number'];\n\nexport class NamespaceBuilder<T extends Actions<T>> {\n #id: string;\n #providerId: string;\n #actions: ActionsMap<T> = new Map();\n /*\n * We keep a list of `ActionBuilder` outputs here to use them in separate phases.\n * Actually, `ActionBuilder` is packing action and its hooks in one place, here we should expand them and them in appropriate places.\n * Eventually, action will be added to `#actions` and its hooks will be added to `Namespace`.\n */\n #actionBuilders: ActionByBuilder<T, Context<T>>[] = [];\n #configs: NamespaceConfig;\n\n constructor(id: string, providerId: string) {\n this.#id = id;\n this.#providerId = providerId;\n this.#configs = {};\n }\n\n /** There are some predefined configs that can be set for each namespace separately */\n public config<K extends keyof NamespaceConfig>(\n name: K,\n value: NamespaceConfig[K]\n ) {\n this.#configs[name] = value;\n return this;\n }\n\n /**\n * Getting a list of actions.\n *\n * e.g.:\n * ```ts\n * .action([\n * [\"connect\", () => {}],\n * [\"disconnect\", () => {}]\n * ])\n * ```\n *\n */\n public action<K extends keyof T>(\n action: (readonly [K, FunctionWithContext<T[K], Context<T>>])[]\n ): NamespaceBuilder<T>;\n\n /**\n *\n * Add a single action\n *\n * e.g.:\n * ```ts\n * .action( [\"connect\", () => {}] )\n * ```\n */\n public action<K extends keyof T>(\n action: K,\n actionFn: FunctionWithContext<T[K], Context<T>>\n ): NamespaceBuilder<T>;\n\n public action(action: ActionByBuilder<T, Context<T>>): NamespaceBuilder<T>;\n\n /**\n *\n * Actions are piece of functionality that a namespace can have, for example it can be a `connect` function\n * or a sign function or even a function for updating namespace's internal state. Actions are flexible and can be anything.\n *\n * Generally, each standard namespace (e.g. evm) has an standard interface defined in `src/namespaces/`\n * and provider (which includes namespaces) authors will implement those actions.\n *\n * You can call this function by a list of actions or a single action.\n *\n */\n public action<K extends keyof T>(\n action: (readonly [K, FunctionWithContext<T[K], Context<T>>])[] | K,\n actionFn?: FunctionWithContext<T[K], Context<T>>\n ) {\n // List mode\n if (Array.isArray(action)) {\n action.forEach(([name, actionFnForItem]) => {\n this.#actions.set(name, actionFnForItem);\n });\n return this;\n }\n\n // Action builder mode\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (typeof action === 'object' && !!action?.actionName) {\n this.#actionBuilders.push(action);\n return this;\n }\n\n // Single action mode\n if (!!actionFn) {\n this.#actions.set(action, actionFn);\n }\n\n return this;\n }\n\n /**\n * By calling build, an instance of Namespace will be built.\n *\n * Note: it's not exactly a `Namespace`, it returns a Proxy which add more convenient use like `namespace.connect()` instead of `namespace.run(\"connect\")`\n */\n public build(): ProxiedNamespace<T> {\n if (this.#isConfigsValid(this.#configs)) {\n return this.#buildApi(this.#configs);\n }\n\n throw new Error(`You namespace config isn't valid.`);\n }\n\n // Currently, namespace doesn't has any config.\n #isConfigsValid(_config: NamespaceConfig): boolean {\n return true;\n }\n\n /*\n * Extracting hooks and add them to `Namespace` for the action.\n *\n * Note: this should be called after `addActionsFromActionBuilders` to ensure the action is added first.\n */\n #addHooksFromActionBuilders(namespace: Namespace<T>) {\n this.#actionBuilders.forEach((actionByBuild) => {\n actionByBuild.after.forEach((afterHooks) => {\n afterHooks.map((action) => {\n namespace.after(actionByBuild.actionName, action);\n });\n });\n\n actionByBuild.before.forEach((beforeHooks) => {\n beforeHooks.map((action) => {\n namespace.before(actionByBuild.actionName, action);\n });\n });\n\n actionByBuild.and.forEach((andHooks) => {\n andHooks.map((action) => {\n namespace.and_then(actionByBuild.actionName, action);\n });\n });\n\n actionByBuild.or.forEach((orHooks) => {\n orHooks.map((action) => {\n namespace.or_else(actionByBuild.actionName, action);\n });\n });\n });\n }\n\n /**\n * Iterate over `actionBuilders` and add them to exists `actions`.\n * Note: Hooks will be added in a separate phase.\n */\n #addActionsFromActionBuilders() {\n this.#actionBuilders.forEach((actionByBuild) => {\n this.#actions.set(actionByBuild.actionName, actionByBuild.action);\n });\n }\n\n /**\n * Build a Proxy object to call actions in a more convenient way. e.g `.connect()` instead of `.run(connect)`\n */\n #buildApi(configs: NamespaceConfig): ProxiedNamespace<T> {\n this.#addActionsFromActionBuilders();\n const namespace = new Namespace<T>(this.#id, this.#providerId, {\n configs,\n actions: this.#actions,\n });\n this.#addHooksFromActionBuilders(namespace);\n\n const api = new Proxy(namespace, {\n has: (_, property) => {\n if (typeof property !== 'string') {\n throw new Error(\n 'You can use string as your property on Namespace instance.'\n );\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n if (allowedMethods.includes(property)) {\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n if (allowedPublicValues.includes(typeof namespace[property])) {\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n return namespace.has(property);\n },\n get: (_, property) => {\n if (typeof property !== 'string') {\n throw new Error(\n 'You can use string as your property on Namespace instance.'\n );\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n const targetValue = namespace[property];\n\n if (\n allowedMethods.includes(property as (typeof allowedMethods)[number])\n ) {\n return targetValue.bind(namespace);\n }\n /*\n * This is useful accessing values like `version`, If we don't do this, we should whitelist\n * All the values as well, So it can be confusing for someone that only wants to add a public value to `Namespace`\n */\n if (allowedPublicValues.includes(typeof targetValue)) {\n return targetValue;\n }\n\n return namespace.run.bind(namespace, property as keyof T);\n },\n set: () => {\n throw new Error('You can not set anything on this object.');\n },\n });\n\n return api as unknown as ProxiedNamespace<T>;\n }\n}\n", "import type { FindProxiedNamespace } from './types.js';\nimport type {\n CommonNamespaces,\n ExtendableInternalActions,\n ProviderBuilderOptions,\n} from '../hub/provider/mod.js';\nimport type { ProviderConfig } from '../hub/store/mod.js';\n\nimport { Provider } from '../hub/provider/mod.js';\n\nexport class ProviderBuilder {\n #id: string;\n #namespaces = new Map();\n #methods: ExtendableInternalActions = {};\n #configs: Partial<ProviderConfig> = {};\n #options: Partial<ProviderBuilderOptions>;\n\n constructor(id: string, options?: ProviderBuilderOptions) {\n this.#id = id;\n this.#options = options || {};\n }\n\n public add<K extends keyof CommonNamespaces>(\n id: K,\n namespace: FindProxiedNamespace<K, CommonNamespaces>\n ) {\n if (this.#options.store) {\n namespace.store(this.#options.store);\n }\n this.#namespaces.set(id, namespace);\n return this;\n }\n\n public config<K extends keyof ProviderConfig>(\n name: K,\n value: ProviderConfig[K]\n ) {\n this.#configs[name] = value;\n return this;\n }\n\n public init(cb: Exclude<ExtendableInternalActions['init'], undefined>) {\n this.#methods.init = cb;\n return this;\n }\n\n public build(): Provider {\n if (this.#isConfigsValid(this.#configs)) {\n return new Provider(this.#id, this.#namespaces, this.#configs, {\n extendInternalActions: this.#methods,\n store: this.#options.store,\n });\n }\n\n throw new Error('You need to set all required configs.');\n }\n\n #isConfigsValid(config: Partial<ProviderConfig>): config is ProviderConfig {\n return !!config.metadata;\n }\n}\n", "import type { Actions, Context, Operators } from '../hub/namespaces/types.js';\nimport type { AnyFunction, FunctionWithContext } from '../types/actions.js';\n\nexport interface ActionByBuilder<T, Context> {\n actionName: keyof T;\n and: Operators<T>;\n or: Operators<T>;\n after: Operators<T>;\n before: Operators<T>;\n action: FunctionWithContext<T[keyof T], Context>;\n}\n\n/*\n * TODO:\n * Currently, to use this builder you will write something like this:\n * new ActionBuilder<EvmActions, 'disconnect'>('disconnect').after(....)\n *\n * I couldn't figure it out to be able typescript infer the constructor value as key of actions.\n * Ideal usage:\n * new ActionBuilder<EvmActions>('disconnect').after(....)\n *\n */\nexport class ActionBuilder<T extends Actions<T>, K extends keyof T> {\n readonly name: K;\n #and: Operators<T> = new Map();\n #or: Operators<T> = new Map();\n #after: Operators<T> = new Map();\n #before: Operators<T> = new Map();\n #action: FunctionWithContext<T[keyof T], Context<T>> | undefined;\n\n constructor(name: K) {\n this.name = name;\n }\n\n public and(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#and.has(this.name)) {\n this.#and.set(this.name, []);\n }\n this.#and.get(this.name)?.push(action);\n return this;\n }\n\n public or(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#or.has(this.name)) {\n this.#or.set(this.name, []);\n }\n this.#or.get(this.name)?.push(action);\n return this;\n }\n\n public before(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#before.has(this.name)) {\n this.#before.set(this.name, []);\n }\n this.#before.get(this.name)?.push(action);\n return this;\n }\n\n public after(action: FunctionWithContext<AnyFunction, Context<T>>) {\n if (!this.#after.has(this.name)) {\n this.#after.set(this.name, []);\n }\n this.#after.get(this.name)?.push(action);\n return this;\n }\n\n public action(action: FunctionWithContext<T[keyof T], Context<T>>) {\n this.#action = action;\n return this;\n }\n\n public build(): ActionByBuilder<T, Context<T>> {\n if (!this.#action) {\n throw new Error('Your action builder should includes an action.');\n }\n\n return {\n actionName: this.name,\n action: this.#action,\n before: this.#before,\n after: this.#after,\n and: this.#and,\n or: this.#or,\n };\n }\n}\n", "/*\n * It is not a good idea to re-export all of CAIP because if they have a breaking change, we will break as well.\n * It would be better to create an abstraction over them and export our own interface to ensure it is under our control.\n */\nexport * as CAIP from 'caip';\n\nexport { generateStoreId } from '../hub/helpers.js';\nexport * from './versions.js';\n", "import type { Provider } from '../hub/mod.js';\nimport type { LegacyProviderInterface } from '../legacy/mod.js';\n\ntype LegacyVersioned = ['0.0.0', LegacyProviderInterface];\ntype HubVersioned = ['1.0.0', Provider];\ntype AvailableVersionedProviders = LegacyVersioned | HubVersioned;\nexport type VersionedProviders = AvailableVersionedProviders[];\nexport type VersionInterface<T extends AvailableVersionedProviders[]> = T[1];\n\ntype SemVer<T extends [string, any]> = T extends [infer U, any] ? U : never;\ntype MatchVersion<T extends VersionedProviders, Version> = Extract<\n T[number],\n [Version, any]\n>;\n\nexport function pickVersion<\n L extends VersionedProviders,\n V extends SemVer<VersionedProviders[number]>\n>(list: L, targetVersion: V): MatchVersion<L, V> {\n if (!targetVersion) {\n throw new Error(`You should provide a valid semver, e.g 1.0.0.`);\n }\n\n const target = list.find(([version]) => version === targetVersion);\n\n if (!target) {\n throw new Error(\n `You target version hasn't been found. Available versions: ${Object.keys(\n list\n ).join(', ')}`\n );\n }\n return target as MatchVersion<L, V>;\n}\n\ninterface DefineVersionsApi {\n version: <T extends SemVer<VersionedProviders[number]>>(\n semver: T,\n value: VersionInterface<MatchVersion<VersionedProviders, T>>\n ) => DefineVersionsApi;\n build: () => VersionedProviders;\n}\n\nexport function defineVersions(): DefineVersionsApi {\n const versions: VersionedProviders = [];\n const api: DefineVersionsApi = {\n version: (semver, value) => {\n versions.push([semver, value]);\n return api;\n },\n build: () => {\n return versions;\n },\n };\n return api;\n}\n\nexport function legacyProviderImportsToVersionsInterface(\n provider: LegacyProviderInterface\n): VersionedProviders {\n return defineVersions().version('0.0.0', provider).build();\n}\n", "import { type ProviderMetadata } from '@rango-dev/wallets-core';\nimport { LegacyNetworks } from '@rango-dev/wallets-core/legacy';\nimport { Networks } from '@rango-dev/wallets-shared';\nimport { type BlockchainMeta } from 'rango-types';\n\nimport getSigners from './signer.js';\n\nexport const EVM_SUPPORTED_CHAINS = [\n LegacyNetworks.ETHEREUM,\n LegacyNetworks.POLYGON,\n LegacyNetworks.BASE,\n];\n\nexport const HEXADECIMAL_BASE = 16;\nexport const WALLET_ID = 'ledger';\n\nexport const metadata: ProviderMetadata = {\n name: 'Ledger',\n icon: 'https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/ledger/icon.svg',\n extensions: {\n homepage:\n 'https://support.ledger.com/hc/en-us/articles/4404389606417-Download-and-install-Ledger-Live?docs=true',\n },\n properties: [\n {\n name: 'namespaces',\n value: {\n selection: 'single',\n data: [\n {\n label: 'Ethereum',\n value: 'EVM',\n id: 'ETH',\n getSupportedChains: (allBlockchains: BlockchainMeta[]) =>\n allBlockchains.filter(\n (chain) => chain.name === Networks.ETHEREUM\n ),\n },\n {\n label: 'Solana',\n value: 'Solana',\n id: 'SOLANA',\n getSupportedChains: (allBlockchains: BlockchainMeta[]) =>\n allBlockchains.filter((chain) => chain.name === Networks.SOLANA),\n },\n ],\n },\n },\n {\n name: 'derivationPath',\n value: {\n data: [\n {\n id: 'metamask',\n label: `Metamask (m/44'/60'/0'/0/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/0/${index}`,\n },\n {\n id: 'ledgerLive',\n label: `LedgerLive (m/44'/60'/index'/0/0)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/${index}'/0/0`,\n },\n {\n id: 'legacy',\n label: `Legacy (m/44'/60'/0'/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/${index}`,\n },\n {\n id: `(m/44'/501'/index')`,\n label: `(m/44'/501'/index')`,\n namespace: 'Solana',\n generateDerivationPath: (index: string) => `44'/501'/${index}'`,\n },\n {\n id: `(m/44'/501'/0'/index)`,\n label: `(m/44'/501'/0'/index)`,\n namespace: 'Solana',\n generateDerivationPath: (index: string) => `44'/501'/0'/${index}`,\n },\n ],\n },\n },\n {\n name: 'signers',\n value: { getSigners: async () => getSigners() },\n },\n ],\n};\n", "import type { SignerFactory } from 'rango-types';\n\nimport { dynamicImportWithRefinedError } from '@rango-dev/wallets-shared';\nimport { DefaultSignerFactory, TransactionType as TxType } from 'rango-types';\n\nexport default async function getSigners(): Promise<SignerFactory> {\n const signers = new DefaultSignerFactory();\n const { EthereumSigner } = await dynamicImportWithRefinedError(\n async () => await import('./signers/ethereum.js')\n );\n const { SolanaSigner } = await dynamicImportWithRefinedError(\n async () => await import('./signers/solana.js')\n );\n signers.registerSigner(TxType.EVM, new EthereumSigner());\n signers.registerSigner(TxType.SOLANA, new SolanaSigner());\n return signers;\n}\n"],
|
|
5
|
-
"mappings": "uDACA,IAAIA,GAAiB,GAEd,SAASC,GAAkBC,EAAc,CAC9CF,GAAiBE,CACnB,CAFgBC,EAAAF,GAAA,qBAIT,SAASG,GAAoB,CAClC,OAAOJ,EACT,CAFgBG,EAAAC,EAAA,yGCFJC,GAAAA,IACVA,EAAA,IAAM,MACNA,EAAA,IAAM,MACNA,EAAA,IAAM,MACNA,EAAA,UAAY,OACZA,EAAA,IAAM,MACNA,EAAA,QAAU,MACVA,EAAA,SAAW,MACXA,EAAA,QAAU,UACVA,EAAA,MAAQ,QACRA,EAAA,SAAW,GACXA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,YAAc,cACdA,EAAA,OAAS,SACTA,EAAA,SAAW,WACXA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,UAAY,YACZA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,KAAO,OACPA,EAAA,OAAS,SACTA,EAAA,KAAO,OACPA,EAAA,MAAQ,QACRA,EAAA,KAAO,OACPA,EAAA,YAAc,cACdA,EAAA,SAAW,WACXA,EAAA,MAAQ,QACRA,EAAA,WAAa,aACbA,EAAA,IAAM,MACNA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,OAAS,SACTA,EAAA,SAAW,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O,sBAAyB,CACpD,GACA,QAAQL,CAAS,EAEbM,EAAqB,CAAC,EAEtBC,EAAS,MAAMG,EAAO,WAAWR,CAAc,EACrD,OAAAI,EAAS,KAAKK,GAAK,OAAOJ,EAAO,OAAO,CAAC,EAElC,CACL,SAAUD,EACV,QAASM,EACT,eAAAV,CACF,CACF,OAASN,EAAgB,CACvB,MAAMD,GAAeC,CAAK,CAC5B,QAAE,CACA,MAAMY,GAAoB,CAC5B,CACF,CA1BsBnB,EAAAoB,GAAA,qBA4BtB,IAAII,EAAwC,KAE5C,eAAsBZ,IAAmB,CACvC,OAAAY,EAAsB,MACpB,KAAM,QAAO,+BAA+B,GAC5C,QAAQ,OAAO,EAEVA,CACT,CANsBxB,EAAAY,GAAA,oBAQtB,eAAsBO,IAAsB,CACtCK,IACF,MAAMA,EAAoB,MAAM,EAChCA,EAAsB,KAE1B,CALsBxB,EAAAmB,GAAA",
|
|
6
|
-
"names": ["derivationPath", "setDerivationPath", "path", "__name", "getDerivationPath", "Networks", "Events", "Persistor", "__name", "name", "item", "value", "formatAddressWithNetwork", "address", "network", "accountAddressesWithNetwork", "addresses", "readAccountAddress", "addressWithNetwork", "needsCheckInstallation", "options", "checkInstallation", "getBlockChainNameFromId", "chainId", "blockchains", "blockchainMeta", "eagerConnectHandler", "params", "isEvmNamespace", "namespace", "Wallet", "actions", "namespaces", "connectionFromState", "currentNetwork", "requestedNetwork", "networkChanged", "canSwitch", "instance", "connectResult", "e", "nextAccounts", "nextNetwork", "nextDerivationPath", "activeEvmNetwork", "blockchain", "derivationPath", "canEagerConnect", "providerName", "provider", "allBlockChains", "switchTo", "data", "cleanup", "accounts", "info", "handler", "states", "updates", "state", "eventInfo", "force", "instanceOptions", "error_message", "CAIP2", "name", "regex", "parameters", "delimiter", "values", "CAIP10", "AssetName", "CAIP19AssetType", "CAIP19AssetId", "CAIP", "assetName", "assetType", "assetId", "splitParams", "id", "spec", "split", "getParams", "arr", "params", "forEach", "value", "index", "joinParams", "Object", "map", "parameter", "param", "join", "isValidId", "RegExp", "test", "length", "keys", "matches", "filter", "x", "ChainId", "parse", "namespace", "reference", "__name", "Error", "toJSON", "format", "_proto", "toString", "AccountId", "chainId", "address", "_getParams", "_extends", "AssetType", "AssetId", "tokenId", "createStoreImpl", "__name", "createState", "state", "listeners", "setState", "partial", "replace", "nextState", "previousState", "listener", "getState", "api", "initialState", "createStore", "NOTHING", "DRAFTABLE", "DRAFT_STATE", "die", "error", "args", "__name", "getPrototypeOf", "isDraft", "value", "DRAFT_STATE", "isDraftable", "isPlainObject", "DRAFTABLE", "isMap", "isSet", "objectCtorString", "proto", "Ctor", "each", "obj", "iter", "getArchtype", "key", "entry", "index", "__name", "thing", "state", "DRAFT_STATE", "isMap", "isSet", "has", "prop", "set", "thing", "propOrOldValue", "value", "t", "getArchtype", "__name", "is", "x", "y", "isMap", "target", "isSet", "latest", "state", "shallowCopy", "base", "strict", "isPlain", "isPlainObject", "descriptors", "DRAFT_STATE", "keys", "i", "key", "desc", "getPrototypeOf", "proto", "obj", "freeze", "deep", "isFrozen", "isDraft", "isDraftable", "dontMutateFrozenCollections", "die", "plugins", "getPlugin", "pluginKey", "plugin", "currentScope", "getCurrentScope", "__name", "createScope", "parent_", "immer_", "usePatchesInScope", "scope", "patchListener", "getPlugin", "revokeScope", "leaveScope", "revokeDraft", "enterScope", "immer", "draft", "state", "DRAFT_STATE", "processResult", "result", "baseDraft", "die", "isDraftable", "finalize", "maybeFreeze", "NOTHING", "rootScope", "value", "path", "isFrozen", "each", "key", "childValue", "finalizeProperty", "resultEach", "isSet", "parentState", "targetObject", "prop", "rootPath", "targetIsSet", "isDraft", "has", "res", "set", "deep", "freeze", "createProxyProxy", "base", "parent", "isArray", "target", "traps", "objectTraps", "arrayTraps", "revoke", "proxy", "source", "latest", "readPropFromProto", "peek", "prepareCopy", "createProxy", "desc", "getDescriptorFromProto", "current", "currentState", "is", "markChanged", "owner", "getPrototypeOf", "fn", "proto", "shallowCopy", "Immer", "config", "recipe", "defaultBase", "self", "args", "hasError", "p", "ip", "patches", "inversePatches", "i", "patch", "applyPatchesImpl", "isMap", "currentImpl", "copy", "immer", "Immer", "produce", "produceWithPatches", "setAutoFreeze", "setUseStrictShallowCopy", "applyPatches", "createDraft", "finishDraft", "actions_exports", "__export", "connect", "recommended", "disconnect", "context", "setState", "__name", "CAIP_NAMESPACE", "CAIP_SOLANA_CHAIN_ID", "getAccounts", "provider", "formatAccountsToCAIP", "accounts", "account", "AccountId", "instance", "solanaInstance", "result", "hooks_exports", "changeAccountSubscriber", "builders_exports", "after_exports", "intoConnectionFinished", "and_exports", "ActionBuilder", "#and", "#or", "#after", "#before", "#action", "name", "action", "isValidCaipAddress", "address", "connectAndUpdateStateForSingleNetwork", "intoConnecting", "before_exports", "ChangeAccountSubscriberBuilder", "#getInstance", "#format", "#validateEventPayload", "#addEventListener", "#removeEventListener", "operator", "#getErrorMessage", "getInstance", "format", "addEventListener", "removeEventListener", "validateEventPayload", "subscriber", "unsubscribe", "event", "_", "err", "operatorName", "callback", "dynamicImportWithRefinedError", "ETHEREUM_CHAIN_ID", "bs58", "isAsync", "fn", "__name", "generateStoreId", "providerId", "namespace", "ACTION_NOT_FOUND_ERROR", "name", "OR_ELSE_ACTION_FAILED_ERROR", "BEFORE_ACTION_FAILED_ERROR", "NO_STORE_FOUND_ERROR", "Namespace", "#actions", "#andOperators", "#orOperators", "#beforeHooks", "#afterHooks", "#initiated", "#store", "#configs", "id", "options", "configs", "actions", "definedInitByUser", "#context", "store", "#storeId", "state", "value", "#setupStore", "actionName", "operatorFn", "currentAndOperators", "currentOrOperators", "hook", "currentAfterHooks", "hookWithOptions", "currentBeforeHooks", "args", "action", "#tryRunAsyncAction", "#tryRunAction", "params", "#tryRunBeforeHooks", "error", "#tryRunAfterHooks", "context", "result", "#tryRunAndOperators", "e", "#tryRunOrOperators", "afterActions", "afterAction", "beforeActions", "beforeAction", "andActions", "prev", "andAction", "actionError", "orActions", "orAction", "orActionError", "errorMessage", "standardOrActionError", "VERSION", "Provider", "#namespaces", "#extendInternalActions", "namespaces", "config", "namespaceLookingFor", "hookFn", "#addHook", "hookName", "cb", "provider", "Hub", "#providers", "#options", "output", "providers", "providerOutput", "providerMethod", "namespaceMethod", "res", "b", "getNamespaceState", "getProviderState", "guessProviderStateSelector", "allNamespaces", "currentProviderNamespaces", "key", "installed", "connected", "connecting", "namespaceStateSelector", "storeId", "extend", "extendedSubscribe", "listener", "executeListener", "events", "prevState", "ev", "eventsLike", "getEventsLike", "allQueuedEvents", "tryConsumeEvents", "target", "prop", "receiver", "currentProviderState", "previousProviderState", "hubStore", "ConsumableEvents", "#data", "val", "namespacesStore", "set", "get", "info", "item", "produce", "ns", "event", "currentAccounts", "currentNetwork", "providersStore", "_provider", "_value", "createStore", "createZustandStore", "api", "allowedMethods", "allowedPublicValues", "NamespaceBuilder", "#id", "#providerId", "#actionBuilders", "actionFn", "actionFnForItem", "#isConfigsValid", "#buildApi", "_config", "#addHooksFromActionBuilders", "actionByBuild", "afterHooks", "beforeHooks", "andHooks", "orHooks", "#addActionsFromActionBuilders", "_", "property", "targetValue", "ProviderBuilder", "#methods", "ActionBuilder", "#and", "#or", "#after", "#before", "#action", "pickVersion", "list", "targetVersion", "version", "defineVersions", "versions", "semver", "Networks", "dynamicImportWithRefinedError", "DefaultSignerFactory", "TxType", "getSigners", "signers", "DefaultSignerFactory", "EthereumSigner", "dynamicImportWithRefinedError", "SolanaSigner", "TxType", "__name", "EVM_SUPPORTED_CHAINS", "f", "HEXADECIMAL_BASE", "WALLET_ID", "metadata", "allBlockchains", "chain", "Networks", "index", "getSigners", "ledger", "instances", "f", "ETHEREUM_CHAIN_ID", "__name", "ledgerFrequentErrorMessages", "getLedgerErrorMessage", "statusCode", "getAltStatusMessage", "HEXADECIMAL_BASE", "getLedgerError", "error", "standardizeAndThrowLedgerError", "_", "getEthereumAccounts", "transport", "transportConnect", "derivationPath", "getDerivationPath", "eth", "dynamicImportWithRefinedError", "accounts", "result", "transportDisconnect", "getSolanaAccounts", "solana", "bs58", "c", "transportConnection"]
|
|
7
|
-
}
|