@joai/warps 4.16.0 → 4.16.1

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/index.d.cts CHANGED
@@ -10,6 +10,18 @@ type WarpI18nText = {
10
10
  [language: string]: string;
11
11
  };
12
12
 
13
+ type WarpBrandSiteRoute = {
14
+ path: string;
15
+ warp: string;
16
+ label: WarpI18nText;
17
+ nav?: boolean;
18
+ };
19
+ type WarpBrandSiteConfig = {
20
+ enabled: boolean;
21
+ auth?: boolean;
22
+ indexPath: string;
23
+ routes: WarpBrandSiteRoute[];
24
+ };
13
25
  type WarpBrand = {
14
26
  protocol: string;
15
27
  name: WarpText;
@@ -805,7 +817,7 @@ declare const WarpProtocolVersions: {
805
817
  declare const WarpConfig: {
806
818
  LatestWarpSchemaUrl: string;
807
819
  LatestBrandSchemaUrl: string;
808
- DefaultClientUrl: (env: WarpChainEnv) => "https://usewarp.to" | "https://testnet.usewarp.to" | "https://devnet.usewarp.to";
820
+ DefaultClientUrl: (env: WarpChainEnv) => "https://joai.ai" | "https://devnet.joai.ai" | "https://testnet.joai.ai";
809
821
  SuperClientUrls: string[];
810
822
  AvailableActionInputSources: WarpActionInputSource[];
811
823
  AvailableActionInputTypes: WarpActionInputType[];
@@ -1494,4 +1506,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
1494
1506
  */
1495
1507
  declare function resolvePath(obj: unknown, path: string): unknown;
1496
1508
 
1497
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1509
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.d.ts CHANGED
@@ -10,6 +10,18 @@ type WarpI18nText = {
10
10
  [language: string]: string;
11
11
  };
12
12
 
13
+ type WarpBrandSiteRoute = {
14
+ path: string;
15
+ warp: string;
16
+ label: WarpI18nText;
17
+ nav?: boolean;
18
+ };
19
+ type WarpBrandSiteConfig = {
20
+ enabled: boolean;
21
+ auth?: boolean;
22
+ indexPath: string;
23
+ routes: WarpBrandSiteRoute[];
24
+ };
13
25
  type WarpBrand = {
14
26
  protocol: string;
15
27
  name: WarpText;
@@ -805,7 +817,7 @@ declare const WarpProtocolVersions: {
805
817
  declare const WarpConfig: {
806
818
  LatestWarpSchemaUrl: string;
807
819
  LatestBrandSchemaUrl: string;
808
- DefaultClientUrl: (env: WarpChainEnv) => "https://usewarp.to" | "https://testnet.usewarp.to" | "https://devnet.usewarp.to";
820
+ DefaultClientUrl: (env: WarpChainEnv) => "https://joai.ai" | "https://devnet.joai.ai" | "https://testnet.joai.ai";
809
821
  SuperClientUrls: string[];
810
822
  AvailableActionInputSources: WarpActionInputSource[];
811
823
  AvailableActionInputTypes: WarpActionInputType[];
@@ -1494,4 +1506,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
1494
1506
  */
1495
1507
  declare function resolvePath(obj: unknown, path: string): unknown;
1496
1508
 
1497
- export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1509
+ export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Qe=Object.create;var At=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var tr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Ze.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return r};var J=(r,t,e)=>(e=r!=null?Qe(Ye(r)):{},ge(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),er=r=>ge(At({},"__esModule",{value:!0}),r);var An={};tr(An,{BrowserCryptoProvider:()=>wt,CLOUD_WALLET_PROVIDERS:()=>dr,CacheTtl:()=>ie,EvmWalletChainNames:()=>cr,MultiversxWalletChainNames:()=>ur,NodeCryptoProvider:()=>It,WARP_LANGUAGES:()=>br,WarpAssets:()=>S,WarpBrandBuilder:()=>te,WarpBuilder:()=>ee,WarpCache:()=>ft,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>we,WarpChainName:()=>Ae,WarpChainResolver:()=>rt,WarpClient:()=>pe,WarpCompositeResolver:()=>nt,WarpConfig:()=>k,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>_,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>vt,WarpLogger:()=>C,WarpPlatformName:()=>Ft,WarpPlatforms:()=>Vt,WarpProtocolVersions:()=>M,WarpSerializer:()=>I,WarpTypeRegistry:()=>le,WarpValidator:()=>ut,address:()=>an,applyOutputToMessages:()=>Et,asset:()=>Zt,biguint:()=>rn,bool:()=>nn,buildGeneratedFallbackWarpIdentifier:()=>Ve,buildGeneratedSourceWarpIdentifier:()=>zr,buildInputsContext:()=>ct,buildMappedOutput:()=>G,buildNestedPayload:()=>Ee,bytesToBase64:()=>xr,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Kr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>Rt,createAuthMessage:()=>Tt,createCryptoProvider:()=>Cr,createDefaultWalletProvider:()=>Qr,createHttpAuthHeaders:()=>Dr,createSignableMessage:()=>$e,createWarpI18nText:()=>Er,createWarpIdentifier:()=>bt,doesWarpRequireWallet:()=>Sr,evaluateOutputCommon:()=>Qt,evaluateWhenCondition:()=>K,extractCollectOutput:()=>Z,extractIdentifierInfoFromUrl:()=>Y,extractPromptOutput:()=>Kt,extractQueryStringFromIdentifier:()=>zt,extractQueryStringFromUrl:()=>qt,extractResolvedInputValues:()=>F,extractWarpSecrets:()=>wr,findWarpAdapterForChain:()=>y,getChainDisplayName:()=>fr,getChainLogo:()=>hr,getCryptoProvider:()=>Dt,getGeneratedSourceWarpName:()=>Oe,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>Yt,getNextInfo:()=>pt,getNextInfoForStatus:()=>lt,getProviderConfig:()=>Ur,getRandomBytes:()=>kt,getRandomHex:()=>Mt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>rr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>mr,getWarpChainAssetLogoUrl:()=>yr,getWarpChainInfoLogoUrl:()=>Wr,getWarpIdentifierWithQuery:()=>$r,getWarpInfoFromIdentifier:()=>L,getWarpInputAction:()=>B,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>ar,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>ir,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>nr,hasInputPrefix:()=>Or,hex:()=>sn,initializeWalletCache:()=>Jr,isEqualWarpIdentifier:()=>Tr,isGeneratedSourcePrivateIdentifier:()=>_r,isPlatformValue:()=>Be,isWarpActionAutoExecute:()=>St,isWarpI18nText:()=>Pr,isWarpWalletReadOnly:()=>sr,matchesTrigger:()=>vn,mergeNestedPayload:()=>Jt,normalizeAndValidateMnemonic:()=>lr,normalizeMnemonic:()=>ve,option:()=>on,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>Mr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>Br,removeWarpWalletFromConfig:()=>pr,replacePlaceholders:()=>V,replacePlaceholdersInWhenExpression:()=>Q,resolveInputs:()=>xn,resolveNextString:()=>_t,resolvePath:()=>ce,resolvePlatformValue:()=>Xt,resolveWarpText:()=>st,safeWindow:()=>Ht,setCryptoProvider:()=>vr,setWarpWalletInConfig:()=>or,shiftBigintBy:()=>at,splitInput:()=>Pt,stampGeneratedWarpMeta:()=>Gr,string:()=>Xr,struct:()=>ln,testCryptoAvailability:()=>Ar,toInputPayloadValue:()=>Te,toPreviewText:()=>jt,tuple:()=>pn,uint16:()=>Zr,uint32:()=>tn,uint64:()=>en,uint8:()=>Yr,validateMnemonicLength:()=>xe,validateSignedMessage:()=>kr,vector:()=>cn,withAdapterFallback:()=>gr});module.exports=er(An);var rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var rr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,nr=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,ir=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,ar=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},sr=r=>typeof r=="string",or=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},pr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},xe=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},lr=(r,t=24)=>{let e=ve(r);return xe(e,t),e};var Ae=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(Ae||{}),Ft=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ft||{}),Vt=Object.values(Ft),cr=["ethereum","base","arbitrum","polygon","somnia","tempo"],ur=["multiversx","claws"],dr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Ht=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},k={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var gr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ce={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},fr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),we={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},hr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Ut=(r,t)=>r[t]??r.default??Object.values(r)[0],mr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ut(r.logo,e)},yr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)},Wr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)};var wt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},It=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},j=null;function Dt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new wt,j;if(typeof process<"u"&&process.versions?.node)return j=new It,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function vr(r){j=r}async function kt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).getRandomBytes(r)}function Ie(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function xr(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await kt(r/2,t);return Ie(e)}async function Ar(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await kt(16),r.randomBytes=!0}catch{}return r}function Cr(){return Dt()}var wr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var y=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},it=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],Ir=["state","mount","unmount","loop"],B=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Ir.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},St=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,at=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},jt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Q=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Sr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},K=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var br={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},st=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Pr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Er=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Tr=(r,t)=>!r||!t?!1:X(r)===X(t),bt=(r,t,e)=>{let n=X(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},L=(r,t)=>{let e=t||u.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=X(n),a=i.split("?")[0],s=Se(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:u.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===u.IdentifierType.Alias||l===u.IdentifierType.Hash){let c=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:c,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===u.IdentifierType.Alias||p===u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==u.IdentifierType.Alias&&p!==u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,c=Rr(l,p)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:p,type:c,identifier:o,identifierBase:l}}}return{chain:e,type:u.IdentifierType.Alias,identifier:i,identifierBase:a}},Y=(r,t)=>{let e=new URL(r),i=e.searchParams.get(u.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return L(a,t)},Rr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Nr=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=Nr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},qt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},zt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Br=(r,t)=>{let e=L(r,t);return(e?e.identifierBase:X(r)).trim()},$r=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Or=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};var be=J(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Y(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||k.DefaultClientUrl(this.config.env),a=y(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return k.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=L(t,this.config.defaultChain);if(!e)return null;let n=y(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=y(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new be.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Pe="https://",_t=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,pt=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=_t(a,"success");if(!s)return null;if(s.startsWith(Pe))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let W=V(p,{...e.vars,...i});return[{identifier:W,url:ot(t,W,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let W=V(l,{...e.vars,...i}),x=W?`${p}?${W}`:p;return[{identifier:x,url:ot(t,x,r)}]}let c=o[0];if(!c)return[];let d=c.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(W=>W.includes(`{{${g}[]`)).map(W=>{let x=W.match(/\[\](\.[^}]+)?}}/),w=x&&x[1]||"";return{placeholder:W,field:w?w.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(W=>{let x=l;for(let{regex:$,field:A}of h){let R=A?Lr(W,A):W;if(R==null)return null;x=x.replace($,R)}if(x.includes("{{")||x.includes("}}"))return null;let w=x?`${p}?${x}`:p;return{identifier:w,url:ot(t,w,r)}}).filter(W=>W!==null)},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=_t(p,s);if(!l)return null;if(l.startsWith(Pe))return[{identifier:null,url:l}];let[o,c]=l.split("?");if(!c){let f=V(o,{...e.vars,...i});return[{identifier:f,url:ot(t,f,r)}]}let d=V(c,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:ot(t,g,r)}]},ot=(r,t,e)=>{let[n,i]=t.split("?"),a=L(n,e.defaultChain)||{chain:u.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=y(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,c)=>l.searchParams.set(c,o)),l.toString().replace(/\/\?/,"?")},Lr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var z=class z{static debug(...t){z.isTestEnv||console.debug(...t)}static info(...t){z.isTestEnv||console.info(...t)}static warn(...t){z.isTestEnv||console.warn(...t)}static error(...t){z.isTestEnv||console.error(...t)}};z.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=z;function Ee(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Jt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Jt(e[n],t[n]):e[n]=t[n]}),e}function Te(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function F(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Te(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ee(n.input.position,i,a);e=Jt(e,s)}else e[i]=a}),e}function ct(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ne(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:c}=Re(r,e,p);return{values:{string:l,native:o,mapped:G(n,i)},output:await Qt(r,c,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Fr(p,r,n,i,a),p=await Vr(r,p,e,i,a,s.transform?.runner||null),p},Fr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(g=>g.as===o||g.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Vr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Hr(e),inputs:ct(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Hr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Re(r,e,s),c=await Qt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:G(n,i)},output:c}},Ne=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Be=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Vt.some(t=>t in r),Xt=(r,t)=>{if(!Be(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Ur=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function $e(r,t,e,n=5){let i=await Mt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Tt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return $e(r,i,e,5)}function Rt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Dr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Tt(r,e,n),p=await t(i);return Rt(r,p,a,s)}function kr(r){let t=new Date(r).getTime();return Date.now()<t}function Mr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Oe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",jr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Le=(r,t=24)=>{let e=jr(r);return e?e.slice(0,t):"action"},Fe=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},qr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},zr=(r,t,e)=>{let n=Le((e||t||"").trim()||"action"),i=`${r.type}|${qr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Fe(i);return`private_src_${n}_${a}`},Ve=r=>{let t=Oe(r),e=Le(t),n=Fe(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Gr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ve(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},_r=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Jr(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function Qr(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=B(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Kr=async(r,t,e,n)=>{try{let i=y(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Nt=require("mppx/client");async function Yt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return C.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Nt.Mppx.create({methods:[(0,Nt.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(u.ArgParamsSeparator),c=l.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),p=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(p)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=Ue[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,g]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="chain"||n==="nft")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Xr=r=>new I().nativeToString(m.String,r),Yr=r=>new I().nativeToString(m.Uint8,r),Zr=r=>new I().nativeToString(m.Uint16,r),tn=r=>new I().nativeToString(m.Uint32,r),en=r=>new I().nativeToString(m.Uint64,r),rn=r=>new I().nativeToString(m.Biguint,r),nn=r=>new I().nativeToString(m.Bool,r),an=r=>new I().nativeToString(m.Address,r),Zt=r=>new I().nativeToString(m.Asset,r),sn=r=>new I().nativeToString(m.Hex,r),on=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},pn=(...r)=>new I().nativeToString(m.Tuple,r),ln=r=>new I().nativeToString(m.Struct,r),cn=r=>new I().nativeToString(m.Vector,r);var De=J(require("ajv"),1);var te=class{constructor(t){this.pendingBrand={protocol:it("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||k.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ke=J(require("ajv"),1);var ut=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=B(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||k.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ke.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ee=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return jt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new ut(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
1
+ "use strict";var Qe=Object.create;var At=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var tr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Ze.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return r};var J=(r,t,e)=>(e=r!=null?Qe(Ye(r)):{},ge(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),er=r=>ge(At({},"__esModule",{value:!0}),r);var An={};tr(An,{BrowserCryptoProvider:()=>wt,CLOUD_WALLET_PROVIDERS:()=>dr,CacheTtl:()=>ie,EvmWalletChainNames:()=>cr,MultiversxWalletChainNames:()=>ur,NodeCryptoProvider:()=>It,WARP_LANGUAGES:()=>br,WarpAssets:()=>S,WarpBrandBuilder:()=>te,WarpBuilder:()=>ee,WarpCache:()=>ft,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>we,WarpChainName:()=>Ae,WarpChainResolver:()=>rt,WarpClient:()=>pe,WarpCompositeResolver:()=>nt,WarpConfig:()=>k,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>_,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>vt,WarpLogger:()=>C,WarpPlatformName:()=>Ft,WarpPlatforms:()=>Vt,WarpProtocolVersions:()=>M,WarpSerializer:()=>I,WarpTypeRegistry:()=>le,WarpValidator:()=>ut,address:()=>an,applyOutputToMessages:()=>Et,asset:()=>Zt,biguint:()=>rn,bool:()=>nn,buildGeneratedFallbackWarpIdentifier:()=>Ve,buildGeneratedSourceWarpIdentifier:()=>zr,buildInputsContext:()=>ct,buildMappedOutput:()=>G,buildNestedPayload:()=>Ee,bytesToBase64:()=>xr,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Kr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>Rt,createAuthMessage:()=>Tt,createCryptoProvider:()=>Cr,createDefaultWalletProvider:()=>Qr,createHttpAuthHeaders:()=>Dr,createSignableMessage:()=>$e,createWarpI18nText:()=>Er,createWarpIdentifier:()=>bt,doesWarpRequireWallet:()=>Sr,evaluateOutputCommon:()=>Qt,evaluateWhenCondition:()=>K,extractCollectOutput:()=>Z,extractIdentifierInfoFromUrl:()=>Y,extractPromptOutput:()=>Kt,extractQueryStringFromIdentifier:()=>zt,extractQueryStringFromUrl:()=>qt,extractResolvedInputValues:()=>F,extractWarpSecrets:()=>wr,findWarpAdapterForChain:()=>y,getChainDisplayName:()=>fr,getChainLogo:()=>hr,getCryptoProvider:()=>Dt,getGeneratedSourceWarpName:()=>Oe,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>Yt,getNextInfo:()=>pt,getNextInfoForStatus:()=>lt,getProviderConfig:()=>Ur,getRandomBytes:()=>kt,getRandomHex:()=>Mt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>rr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>mr,getWarpChainAssetLogoUrl:()=>yr,getWarpChainInfoLogoUrl:()=>Wr,getWarpIdentifierWithQuery:()=>$r,getWarpInfoFromIdentifier:()=>L,getWarpInputAction:()=>B,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>ar,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>ir,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>nr,hasInputPrefix:()=>Or,hex:()=>sn,initializeWalletCache:()=>Jr,isEqualWarpIdentifier:()=>Tr,isGeneratedSourcePrivateIdentifier:()=>_r,isPlatformValue:()=>Be,isWarpActionAutoExecute:()=>St,isWarpI18nText:()=>Pr,isWarpWalletReadOnly:()=>sr,matchesTrigger:()=>vn,mergeNestedPayload:()=>Jt,normalizeAndValidateMnemonic:()=>lr,normalizeMnemonic:()=>ve,option:()=>on,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>Mr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>Br,removeWarpWalletFromConfig:()=>pr,replacePlaceholders:()=>V,replacePlaceholdersInWhenExpression:()=>Q,resolveInputs:()=>xn,resolveNextString:()=>_t,resolvePath:()=>ce,resolvePlatformValue:()=>Xt,resolveWarpText:()=>st,safeWindow:()=>Ht,setCryptoProvider:()=>vr,setWarpWalletInConfig:()=>or,shiftBigintBy:()=>at,splitInput:()=>Pt,stampGeneratedWarpMeta:()=>Gr,string:()=>Xr,struct:()=>ln,testCryptoAvailability:()=>Ar,toInputPayloadValue:()=>Te,toPreviewText:()=>jt,tuple:()=>pn,uint16:()=>Zr,uint32:()=>tn,uint64:()=>en,uint8:()=>Yr,validateMnemonicLength:()=>xe,validateSignedMessage:()=>kr,vector:()=>cn,withAdapterFallback:()=>gr});module.exports=er(An);var rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var rr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,nr=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,ir=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,ar=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},sr=r=>typeof r=="string",or=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},pr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},xe=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},lr=(r,t=24)=>{let e=ve(r);return xe(e,t),e};var Ae=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(Ae||{}),Ft=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ft||{}),Vt=Object.values(Ft),cr=["ethereum","base","arbitrum","polygon","somnia","tempo"],ur=["multiversx","claws"],dr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Ht=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},k={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var gr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ce={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},fr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),we={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},hr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Ut=(r,t)=>r[t]??r.default??Object.values(r)[0],mr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ut(r.logo,e)},yr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)},Wr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)};var wt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},It=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},j=null;function Dt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new wt,j;if(typeof process<"u"&&process.versions?.node)return j=new It,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function vr(r){j=r}async function kt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).getRandomBytes(r)}function Ie(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function xr(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await kt(r/2,t);return Ie(e)}async function Ar(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await kt(16),r.randomBytes=!0}catch{}return r}function Cr(){return Dt()}var wr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var y=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},it=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],Ir=["state","mount","unmount","loop"],B=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Ir.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},St=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,at=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},jt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Q=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Sr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},K=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var br={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},st=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Pr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Er=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Tr=(r,t)=>!r||!t?!1:X(r)===X(t),bt=(r,t,e)=>{let n=X(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},L=(r,t)=>{let e=t||u.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=X(n),a=i.split("?")[0],s=Se(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:u.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===u.IdentifierType.Alias||l===u.IdentifierType.Hash){let c=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:c,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===u.IdentifierType.Alias||p===u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==u.IdentifierType.Alias&&p!==u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,c=Rr(l,p)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:p,type:c,identifier:o,identifierBase:l}}}return{chain:e,type:u.IdentifierType.Alias,identifier:i,identifierBase:a}},Y=(r,t)=>{let e=new URL(r),i=e.searchParams.get(u.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return L(a,t)},Rr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Nr=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=Nr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},qt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},zt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Br=(r,t)=>{let e=L(r,t);return(e?e.identifierBase:X(r)).trim()},$r=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Or=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};var be=J(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Y(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||k.DefaultClientUrl(this.config.env),a=y(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return k.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=L(t,this.config.defaultChain);if(!e)return null;let n=y(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=y(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new be.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Pe="https://",_t=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,pt=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=_t(a,"success");if(!s)return null;if(s.startsWith(Pe))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let W=V(p,{...e.vars,...i});return[{identifier:W,url:ot(t,W,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let W=V(l,{...e.vars,...i}),x=W?`${p}?${W}`:p;return[{identifier:x,url:ot(t,x,r)}]}let c=o[0];if(!c)return[];let d=c.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(W=>W.includes(`{{${g}[]`)).map(W=>{let x=W.match(/\[\](\.[^}]+)?}}/),w=x&&x[1]||"";return{placeholder:W,field:w?w.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(W=>{let x=l;for(let{regex:$,field:A}of h){let R=A?Lr(W,A):W;if(R==null)return null;x=x.replace($,R)}if(x.includes("{{")||x.includes("}}"))return null;let w=x?`${p}?${x}`:p;return{identifier:w,url:ot(t,w,r)}}).filter(W=>W!==null)},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=T(e,n)?.next||e.next||null,l=_t(p,s);if(!l)return null;if(l.startsWith(Pe))return[{identifier:null,url:l}];let[o,c]=l.split("?");if(!c){let f=V(o,{...e.vars,...i});return[{identifier:f,url:ot(t,f,r)}]}let d=V(c,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:ot(t,g,r)}]},ot=(r,t,e)=>{let[n,i]=t.split("?"),a=L(n,e.defaultChain)||{chain:u.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=y(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,c)=>l.searchParams.set(c,o)),l.toString().replace(/\/\?/,"?")},Lr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var z=class z{static debug(...t){z.isTestEnv||console.debug(...t)}static info(...t){z.isTestEnv||console.info(...t)}static warn(...t){z.isTestEnv||console.warn(...t)}static error(...t){z.isTestEnv||console.error(...t)}};z.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=z;function Ee(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Jt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Jt(e[n],t[n]):e[n]=t[n]}),e}function Te(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function F(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Te(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ee(n.input.position,i,a);e=Jt(e,s)}else e[i]=a}),e}function ct(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ne(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:c}=Re(r,e,p);return{values:{string:l,native:o,mapped:G(n,i)},output:await Qt(r,c,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Fr(p,r,n,i,a),p=await Vr(r,p,e,i,a,s.transform?.runner||null),p},Fr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(g=>g.as===o||g.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Vr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Hr(e),inputs:ct(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Hr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Re(r,e,s),c=await Qt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:G(n,i)},output:c}},Ne=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Be=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Vt.some(t=>t in r),Xt=(r,t)=>{if(!Be(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Ur=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function $e(r,t,e,n=5){let i=await Mt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Tt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return $e(r,i,e,5)}function Rt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Dr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Tt(r,e,n),p=await t(i);return Rt(r,p,a,s)}function kr(r){let t=new Date(r).getTime();return Date.now()<t}function Mr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Oe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",jr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Le=(r,t=24)=>{let e=jr(r);return e?e.slice(0,t):"action"},Fe=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},qr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},zr=(r,t,e)=>{let n=Le((e||t||"").trim()||"action"),i=`${r.type}|${qr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Fe(i);return`private_src_${n}_${a}`},Ve=r=>{let t=Oe(r),e=Le(t),n=Fe(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Gr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ve(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},_r=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Jr(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function Qr(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=B(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Kr=async(r,t,e,n)=>{try{let i=y(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Nt=require("mppx/client");async function Yt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return C.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Nt.Mppx.create({methods:[(0,Nt.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(u.ArgParamsSeparator),c=l.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),p=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(p)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=Ue[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,g]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="chain"||n==="nft")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Xr=r=>new I().nativeToString(m.String,r),Yr=r=>new I().nativeToString(m.Uint8,r),Zr=r=>new I().nativeToString(m.Uint16,r),tn=r=>new I().nativeToString(m.Uint32,r),en=r=>new I().nativeToString(m.Uint64,r),rn=r=>new I().nativeToString(m.Biguint,r),nn=r=>new I().nativeToString(m.Bool,r),an=r=>new I().nativeToString(m.Address,r),Zt=r=>new I().nativeToString(m.Asset,r),sn=r=>new I().nativeToString(m.Hex,r),on=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},pn=(...r)=>new I().nativeToString(m.Tuple,r),ln=r=>new I().nativeToString(m.Struct,r),cn=r=>new I().nativeToString(m.Vector,r);var De=J(require("ajv"),1);var te=class{constructor(t){this.pendingBrand={protocol:it("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||k.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ke=J(require("ajv"),1);var ut=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=B(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||k.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ke.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ee=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return jt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new ut(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
2
  `))}};var E=require("fs"),et=require("path");var re="$bigint:",Bt=(r,t)=>typeof t=="bigint"?re+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var $t=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,E.existsSync)(this.cacheDir)||(0,E.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,E.existsSync)(e))return null;let n=(0,E.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,E.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,E.writeFileSync)(a,JSON.stringify(i,Bt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,E.existsSync)(e)&&(0,E.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,E.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,E.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,E.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var dt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,tt);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,Bt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var gt=H;var Me=require("fs"),ne=require("path");var Ot=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Me.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ie={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},ft=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new dt(t,e):e?.type==="memory"?new gt(t,e):e?.type==="static"?new Ot(t,e):e?.type==="filesystem"?new $t(t,e):typeof window<"u"&&window.localStorage?new dt(t,e):new gt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var mt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},oe=r=>{try{return JSON.parse(r)}catch{return null}},un=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Tt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Rt(n,d,o,c)).forEach(([g,f])=>s.set(g,f))}let p=se(e.resolvedInputs,mt.Headers,i);if(p){let l=oe(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},dn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,mt.Queries,i);if(s){let p=oe(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},gn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,mt.Payload,n);if(a&&oe(a)!==null)return a;let{[mt.Payload]:s,[mt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},je=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ae.Get,o=await un(r,t,e,n,a,p),c=dn(r,t,e,l,a),d=gn(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var N=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${fn(i)}\\}\\}`,"g"),s)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return V(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=y(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},fn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var hn=["collect","compute","mcp","state","mount","unmount"],_=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new I,this.cache=new ft(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return F(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ht.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=y(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,i),c=T(o,e),{action:d,index:g}=B(o),f=[],h=[];if(g===e-1){let b=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,b,l,i.queries),h=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),h=await this.getModifiedInputs(f));let v=h.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,W=this.getDestinationFromAction(c),x=v?this.serializer.stringToNative(v)[1]:W;if(x&&(x=l.applyInputs(x,h,this.serializer)),!x&&!hn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let w=this.getPreparedArgs(c,h);w=w.map(b=>l.applyInputs(b,h,this.serializer));let $=h.find(b=>b.input.position==="value")?.value||null,A="value"in c?c.value:null,R=$?.split(u.ArgParamsSeparator)[1]||A||"0",U=l.applyInputs(R,h,this.serializer),O=BigInt(U),D=h.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),qe=[...("transfers"in c?c.transfers:[])||[],...D||[]].map(b=>{let Lt=l.applyInputs(b,h,this.serializer),Je=Lt.startsWith(`asset${u.ArgParamsSeparator}`)?Lt:`asset${u.ArgParamsSeparator}${Lt}`;return this.serializer.stringToNative(Je)[1]}),ze=h.find(b=>b.input.position==="data")?.value,Ge="data"in c?c.data||"":null,ue=ze||Ge||null,_e=ue?l.applyInputs(ue,h,this.serializer):null,de={adapter:p,warp:o,chain:s,action:e,destination:x,args:w,value:O,transfers:qe,data:_e,resolvedInputs:h};return await this.cache.set(ht.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return y(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(u.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let W=P(this.config,t);return W?this.serializer.nativeToString("address",W):null}if(c.source==="hidden"){if(c.default===void 0)return null;let W=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,W)}if(l[d])return l[d];let g=c.as||c.name,f=a?.[g],h=this.url.searchParams.get(g),v=f||h;return v?this.serializer.nativeToString(c.type,String(v)):null};return s.map((c,d)=>{let g=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:g||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=y(a.name,this.adapters),p=new N(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=at(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=at(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ct(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Pt(e),a=y(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=at(p,o.decimals);return Zt({...o,amount:c})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return y(s,this.adapters).chainInfo}};var yt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.handlers=n,this.factory=new _(t,e)}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},{index:g}=B(t);for(let f=1;f<=t.actions.length;f++){let h=T(t,f);if(!St(h))continue;let v=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:W,chain:x,immediateExecution:w,executable:$}=await this.executeAction(t,f,e,v);if(W&&i.push(W),x&&(a=x),w&&s.push(w),w?.output){let{_DATA:A,...R}=w.output;Object.assign(d,R)}w?.values?.mapped&&Object.assign(d,w.values.mapped),$&&f===g+1&&$.resolvedInputs&&(p=F($.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Ht.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=Q(a.when,o);if(!K(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=y(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=y(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!St(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),g=mn(c,d.output);return d.next=lt(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=G(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=G(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,y(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:c,body:d}=await je(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:c,body:d});try{let g={method:o,headers:c,body:d},h=await(await Yt(this.adapters))(l,g);C.debug("Collect response status",{status:h.status});let v=await h.json();C.debug("Collect response content",{content:v});let{values:W,output:x}=await Z(t.warp,v,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",W,x,v)}catch(g){C.error("WarpActionExecutor: Error executing collect",g);let f=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let f=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let p=this.factory.getSerializer(),l=new N(this.config,y(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let v=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=v}),C.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:g});try{let f=new s(new URL(c),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let v={};t.resolvedInputs.forEach(({input:A,value:R})=>{if(R&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let U=A.position.replace("payload:",""),[O,D]=p.stringToNative(R);if(O==="string")v[U]=String(D);else if(O==="bool")v[U]=!!D;else if(O==="uint8"||O==="uint16"||O==="uint32"||O==="uint64"||O==="uint128"||O==="uint256"||O==="biguint"){let xt=Number(D);v[U]=(Number.isInteger(xt),xt)}else v[U]=D}}),e&&Object.assign(v,e);let W=await h.callTool({name:d,arguments:v});await h.close();let x;if(W.content&&W.content.length>0){let A=W.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=W;let{values:w,output:$}=await Z(t.warp,x,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",w,$,W)}catch(f){C.error("WarpExecutor: Error executing MCP",f);let h=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=lt(this.config,this.adapters,t.warp,t.action,a,n),l=F(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Et(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let g={...n.envs,...i},f=Q(s.when,g);try{if(!K(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),C.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=Q(e.when,l);if(!K(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let g of o)l[g]!==void 0&&l[g]!==null&&(c[`state.${g}`]=l[g]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,g]of Object.entries(e.data))if(typeof g=="string"){let f=g.replace(/\{\{([^}]+)\}\}/g,(h,v)=>{let W=o[v.trim()];return W!=null?String(W):g});c[d]=yn(f)}else c[d]=g;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=y(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,a),c=T(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),R=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(R)}else{let{action:A}=B(o),R=this.factory.getStringTypedInputs(A,i),U=await this.factory.getResolvedInputs(s.name,A,R,l,a.queries);d=await this.factory.getModifiedInputs(U)}let g=Xt(c.prompt,this.config.platform),f=l.applyInputs(g,d,this.factory.getSerializer()),h=F(d),v=P(this.config,s.name),W=this.factory.getSerializer(),{values:x,output:w}=await Kt(o,f,n,d,W,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f);A&&(w.MESSAGE=A)}let $=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:v,txHash:null,tx:null,next:pt(this.config,this.adapters,o,n,w),values:x,output:w,messages:Et(o,{...x.mapped,...w},this.config),destination:$,resolvedInputs:h}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:lt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=y(p.name,this.adapters),o=new N(this.config,l,this.adapters),c;if(a)c=a;else{let h=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(h)}let d=o.buildInputBag(c,this.factory.getSerializer()),g={...i.envs??{},...d},f=Q(e.when,g);return K(f)}},mn=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},yn=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Wt=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Y(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?Y(t,this.config.defaultChain):L(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?qt(t):zt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let v=`${i.chain}:${s}`;h=await this.resolver.getByAlias(v,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=y(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let v=await h.registry.getInfoByHash(s,e);l=v.registryInfo,o=v.brand}else if(a==="alias"){let v=await h.registry.getInfoByAlias(s,e);l=v.registryInfo,o=v.brand,v.registryInfo&&(p=await h.builder().createFromTransactionHash(v.registryInfo.hash,e))}}if(p&&p.meta&&(Wn(p,i.chain,l,i.identifier),p.meta.query=c?Gt(c):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new N(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Wn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?bt(null,"alias",e.alias):bt(t,"hash",e?.hash??n))};var pe=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new rt(e));return new nt(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new yt(this.config,this.chains,t)}async detectWarp(t,e){return new vt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await y(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return y(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=L(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return y(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return y(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return y(t,this.chains).explorer}getOutput(t){return y(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??B(e).index+1,p=await y(t,this.chains).output.getActionExecution(e,a,n);return p.next=pt(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=y(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return y(t,this.chains).dataLoader}getWallet(t){return y(t,this.chains).wallet}get factory(){return new _(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return y(t,this.chains).builder()}createAbiBuilder(t){return y(t,this.chains).abiBuilder()}createBrandBuilder(t){return y(t,this.chains).brandBuilder()}createSerializer(t){return y(t,this.chains).serializer}resolveText(t){return st(t,this.config)}};var le=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function vn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function xn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpInputAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var it=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var at=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var vr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Se=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Se(r.user?.wallets?.[t]||null),be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ee=r=>r?typeof r=="string"?r:r.externalId||null:null,xr=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,Ar=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Cr=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},wr=r=>typeof r=="string",Ir=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Sr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Re=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ne=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},br=(r,t=24)=>{let e=Re(r);return Ne(e,t),e};var Be=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(Be||{}),Dt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Dt||{}),kt=Object.values(Dt),Tr=["ethereum","base","arbitrum","polygon","somnia","tempo"],Rr=["multiversx","claws"],Nr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Mt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${j.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${j.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Lr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var st="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",b={baseUrl:st,chainLogo:r=>`${st}/chains/logos/${r}`,tokenLogo:r=>`${st}/tokens/logos/${r}`,walletLogo:r=>`${st}/wallets/logos/${r}`},$e={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Vr=r=>$e[r]??r.charAt(0).toUpperCase()+r.slice(1),Oe={ethereum:{light:b.chainLogo("ethereum-white.svg"),dark:b.chainLogo("ethereum-black.svg")},base:{light:b.chainLogo("base-white.svg"),dark:b.chainLogo("base-black.svg")},arbitrum:b.chainLogo("arbitrum.svg"),polygon:b.chainLogo("polygon.svg"),somnia:b.chainLogo("somnia.png"),tempo:{light:b.chainLogo("tempo-white.svg"),dark:b.chainLogo("tempo-black.svg")},multiversx:b.chainLogo("multiversx.svg"),claws:b.chainLogo("claws.png"),sui:b.chainLogo("sui.svg"),solana:b.chainLogo("solana.svg"),near:{light:b.chainLogo("near-white.svg"),dark:b.chainLogo("near-black.svg")},fastset:{light:b.chainLogo("fastset-white.svg"),dark:b.chainLogo("fastset-black.svg")}},Hr=(r,t="dark")=>{let e=Oe[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var wt=(r,t)=>r[t]??r.default??Object.values(r)[0],Dr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:wt(r.logo,e)},kr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)},Mr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)};var It=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},St=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},k=null;function jt(){if(k)return k;if(typeof window<"u"&&window.crypto)return k=new It,k;if(typeof process<"u"&&process.versions?.node)return k=new St,k;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function qr(r){k=r}async function qt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||jt()).getRandomBytes(r)}function Le(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function zr(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function zt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await qt(r/2,t);return Le(e)}async function Gr(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await qt(16),r.randomBytes=!0}catch{}return r}function _r(){return jt()}var Kr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},ot=r=>{if(r==="warp")return`warp:${j.Warp}`;if(r==="brand")return`brand:${j.Brand}`;if(r==="abi")return`abi:${j.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Fe=["state","mount","unmount","loop"],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Fe.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},bt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,pt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Gt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},F=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),J=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),en=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Q=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var nn={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},lt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},an=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,sn=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,cn=(r,t)=>!r||!t?!1:K(r)===K(t),Pt=(r,t,e)=>{let n=K(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||u.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=K(n),a=i.split("?")[0],s=_t(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:u.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===u.IdentifierType.Alias||l===u.IdentifierType.Hash){let c=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:c,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===u.IdentifierType.Alias||p===u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==u.IdentifierType.Alias&&p!==u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,c=Ve(l,p)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:p,type:c,identifier:o,identifierBase:l}}}return{chain:e,type:u.IdentifierType.Alias,identifier:i,identifierBase:a}},X=(r,t)=>{let e=new URL(r),i=e.searchParams.get(u.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},Ve=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,He=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},_t=r=>{let t=He(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=_t(a);return[i,...s]},Jt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Qt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Kt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},un=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},dn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Et=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},hn=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Et(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=lt(a,e);return[i,F(s,t)]});return Object.fromEntries(n)};import Ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ue({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Xt="https://",Yt=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,ct=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Yt(a,"success");if(!s)return null;if(s.startsWith(Xt))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let y=F(p,{...e.vars,...i});return[{identifier:y,url:Y(t,y,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let y=F(l,{...e.vars,...i}),x=y?`${p}?${y}`:p;return[{identifier:x,url:Y(t,x,r)}]}let c=o[0];if(!c)return[];let d=c.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(y=>y.includes(`{{${g}[]`)).map(y=>{let x=y.match(/\[\](\.[^}]+)?}}/),C=x&&x[1]||"";return{placeholder:y,field:C?C.slice(1):"",regex:new RegExp(y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(y=>{let x=l;for(let{regex:N,field:A}of h){let T=A?De(y,A):y;if(T==null)return null;x=x.replace(N,T)}if(x.includes("{{")||x.includes("}}"))return null;let C=x?`${p}?${x}`:p;return{identifier:C,url:Y(t,C,r)}}).filter(y=>y!==null)},ut=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=Yt(p,s);if(!l)return null;if(l.startsWith(Xt))return[{identifier:null,url:l}];let[o,c]=l.split("?");if(!c){let f=F(o,{...e.vars,...i});return[{identifier:f,url:Y(t,f,r)}]}let d=F(c,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:Y(t,g,r)}]},Y=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:u.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,c)=>l.searchParams.set(c,o)),l.toString().replace(/\/\?/,"?")},De=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var M=class M{static debug(...t){M.isTestEnv||console.debug(...t)}static info(...t){M.isTestEnv||console.info(...t)}static warn(...t){M.isTestEnv||console.warn(...t)}static error(...t){M.isTestEnv||console.error(...t)}};M.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=M;function ke(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Zt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Zt(e[n],t[n]):e[n]=t[n]}),e}function Me(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function L(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function z(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Me(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=ke(n.input.position,i,a);e=Zt(e,s)}else e[i]=a}),e}function dt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var te=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ge(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:c}=te(r,e,p);return{values:{string:l,native:o,mapped:z(n,i)},output:await ee(r,c,t,e,n,i,a)}},ee=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=je(p,r,n,i,a),p=await qe(r,p,e,i,a,s.transform?.runner||null),p},je=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(g=>g.as===o||g.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},qe=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:ze(e),inputs:dt(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){w.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},ze=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},re=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=te(r,e,s),c=await ee(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:z(n,i)},output:c}},Ge=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var _e=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:kt.some(t=>t in r),ne=(r,t)=>{if(!_e(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var qn=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function Je(r,t,e,n=5){let i=await zt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Je(r,i,e,5)}function Nt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Jn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),p=await t(i);return Nt(r,p,a,s)}function Qn(r){let t=new Date(r).getTime();return Date.now()<t}function Kn(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Qe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Ke=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ie=(r,t=24)=>{let e=Ke(r);return e?e.slice(0,t):"action"},ae=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},Xe=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},Yn=(r,t,e)=>{let n=ie((e||t||"").trim()||"action"),i=`${r.type}|${Xe(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=ae(i);return`private_src_${n}_${a}`},Ye=r=>{let t=Qe(r),e=ie(t),n=ae(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Zn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ye(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ti=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ri(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function ii(r,t,e){return null}var Ze=(r,t)=>{let e=null;try{e=$(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},oi=async(r,t,e,n)=>{try{let i=W(e,n),a=Ze(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as tr,tempo as er}from"mppx/client";async function se(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return w.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),tr.create({methods:[er({account:e})],polyfill:!1}).fetch}return fetch}var oe={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=oe[t]??t,t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(u.ArgParamsSeparator),c=l.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),p=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(p)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=oe[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,g]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="chain"||n==="nft")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var mi=r=>new I().nativeToString(m.String,r),yi=r=>new I().nativeToString(m.Uint8,r),Wi=r=>new I().nativeToString(m.Uint16,r),vi=r=>new I().nativeToString(m.Uint32,r),xi=r=>new I().nativeToString(m.Uint64,r),Ai=r=>new I().nativeToString(m.Biguint,r),Ci=r=>new I().nativeToString(m.Bool,r),wi=r=>new I().nativeToString(m.Address,r),pe=r=>new I().nativeToString(m.Asset,r),Ii=r=>new I().nativeToString(m.Hex,r),Si=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},bi=(...r)=>new I().nativeToString(m.Tuple,r),Pi=r=>new I().nativeToString(m.Struct,r),Ei=r=>new I().nativeToString(m.Vector,r);import rr from"ajv";var le=class{constructor(t){this.pendingBrand={protocol:ot("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new rr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import nr from"ajv";var gt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=$(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new nr({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ce=class{constructor(t){this.config=t;this.pendingWarp={protocol:ot("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Gt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new gt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
1
+ var it=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var at=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var vr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Se=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Se(r.user?.wallets?.[t]||null),be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ee=r=>r?typeof r=="string"?r:r.externalId||null:null,xr=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,Ar=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Cr=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},wr=r=>typeof r=="string",Ir=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Sr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Re=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ne=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},br=(r,t=24)=>{let e=Re(r);return Ne(e,t),e};var Be=(g=>(g.Multiversx="multiversx",g.Claws="claws",g.Sui="sui",g.Ethereum="ethereum",g.Base="base",g.Arbitrum="arbitrum",g.Polygon="polygon",g.Somnia="somnia",g.Tempo="tempo",g.Fastset="fastset",g.Solana="solana",g.Near="near",g))(Be||{}),Dt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Dt||{}),kt=Object.values(Dt),Tr=["ethereum","base","arbitrum","polygon","somnia","tempo"],Rr=["multiversx","claws"],Nr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Mt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${j.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${j.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Lr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var st="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",b={baseUrl:st,chainLogo:r=>`${st}/chains/logos/${r}`,tokenLogo:r=>`${st}/tokens/logos/${r}`,walletLogo:r=>`${st}/wallets/logos/${r}`},$e={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Vr=r=>$e[r]??r.charAt(0).toUpperCase()+r.slice(1),Oe={ethereum:{light:b.chainLogo("ethereum-white.svg"),dark:b.chainLogo("ethereum-black.svg")},base:{light:b.chainLogo("base-white.svg"),dark:b.chainLogo("base-black.svg")},arbitrum:b.chainLogo("arbitrum.svg"),polygon:b.chainLogo("polygon.svg"),somnia:b.chainLogo("somnia.png"),tempo:{light:b.chainLogo("tempo-white.svg"),dark:b.chainLogo("tempo-black.svg")},multiversx:b.chainLogo("multiversx.svg"),claws:b.chainLogo("claws.png"),sui:b.chainLogo("sui.svg"),solana:b.chainLogo("solana.svg"),near:{light:b.chainLogo("near-white.svg"),dark:b.chainLogo("near-black.svg")},fastset:{light:b.chainLogo("fastset-white.svg"),dark:b.chainLogo("fastset-black.svg")}},Hr=(r,t="dark")=>{let e=Oe[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var wt=(r,t)=>r[t]??r.default??Object.values(r)[0],Dr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:wt(r.logo,e)},kr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)},Mr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)};var It=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},St=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},k=null;function jt(){if(k)return k;if(typeof window<"u"&&window.crypto)return k=new It,k;if(typeof process<"u"&&process.versions?.node)return k=new St,k;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function qr(r){k=r}async function qt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||jt()).getRandomBytes(r)}function Le(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function zr(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function zt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await qt(r/2,t);return Le(e)}async function Gr(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await qt(16),r.randomBytes=!0}catch{}return r}function _r(){return jt()}var Kr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},ot=r=>{if(r==="warp")return`warp:${j.Warp}`;if(r==="brand")return`brand:${j.Brand}`;if(r==="abi")return`abi:${j.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Fe=["state","mount","unmount","loop"],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Fe.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},bt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,pt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Gt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},F=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),J=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),en=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Q=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var nn={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},lt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},an=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,sn=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,cn=(r,t)=>!r||!t?!1:K(r)===K(t),Pt=(r,t,e)=>{let n=K(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},O=(r,t)=>{let e=t||u.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=K(n),a=i.split("?")[0],s=_t(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:u.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[p,l,o]=s;if(l===u.IdentifierType.Alias||l===u.IdentifierType.Hash){let c=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:c,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===u.IdentifierType.Alias||p===u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==u.IdentifierType.Alias&&p!==u.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,c=Ve(l,p)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:p,type:c,identifier:o,identifierBase:l}}}return{chain:e,type:u.IdentifierType.Alias,identifier:i,identifierBase:a}},X=(r,t)=>{let e=new URL(r),i=e.searchParams.get(u.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return O(a,t)},Ve=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,He=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},_t=r=>{let t=He(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=_t(a);return[i,...s]},Jt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Qt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Kt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},un=(r,t)=>{let e=O(r,t);return(e?e.identifierBase:K(r)).trim()},dn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var Et=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},hn=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Et(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=lt(a,e);return[i,F(s,t)]});return Object.fromEntries(n)};import Ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=O(t,this.config.defaultChain);if(!e)return null;let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ue({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Xt="https://",Yt=(r,t)=>r?typeof r=="string"?t==="success"?r:null:r[t]||null:null,ct=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Yt(a,"success");if(!s)return null;if(s.startsWith(Xt))return[{identifier:null,url:s}];let[p,l]=s.split("?");if(!l){let y=F(p,{...e.vars,...i});return[{identifier:y,url:Y(t,y,r)}]}let o=l.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let y=F(l,{...e.vars,...i}),x=y?`${p}?${y}`:p;return[{identifier:x,url:Y(t,x,r)}]}let c=o[0];if(!c)return[];let d=c.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||i[g]===void 0)return[];let f=Array.isArray(i[g])?i[g]:[i[g]];if(f.length===0)return[];let h=o.filter(y=>y.includes(`{{${g}[]`)).map(y=>{let x=y.match(/\[\](\.[^}]+)?}}/),C=x&&x[1]||"";return{placeholder:y,field:C?C.slice(1):"",regex:new RegExp(y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(y=>{let x=l;for(let{regex:N,field:A}of h){let T=A?De(y,A):y;if(T==null)return null;x=x.replace(N,T)}if(x.includes("{{")||x.includes("}}"))return null;let C=x?`${p}?${x}`:p;return{identifier:C,url:Y(t,C,r)}}).filter(y=>y!==null)},ut=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=Yt(p,s);if(!l)return null;if(l.startsWith(Xt))return[{identifier:null,url:l}];let[o,c]=l.split("?");if(!c){let f=F(o,{...e.vars,...i});return[{identifier:f,url:Y(t,f,r)}]}let d=F(c,{...e.vars,...i}),g=d?`${o}?${d}`:o;return[{identifier:g,url:Y(t,g,r)}]},Y=(r,t,e)=>{let[n,i]=t.split("?"),a=O(n,e.defaultChain)||{chain:u.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,c)=>l.searchParams.set(c,o)),l.toString().replace(/\/\?/,"?")},De=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var M=class M{static debug(...t){M.isTestEnv||console.debug(...t)}static info(...t){M.isTestEnv||console.info(...t)}static warn(...t){M.isTestEnv||console.warn(...t)}static error(...t){M.isTestEnv||console.error(...t)}};M.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=M;function ke(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Zt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Zt(e[n],t[n]):e[n]=t[n]}),e}function Me(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function L(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function z(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Me(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=ke(n.input.position,i,a);e=Zt(e,s)}else e[i]=a}),e}function dt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var te=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ge(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,g)=>g.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:c}=te(r,e,p);return{values:{string:l,native:o,mapped:z(n,i)},output:await ee(r,c,t,e,n,i,a)}},ee=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=je(p,r,n,i,a),p=await qe(r,p,e,i,a,s.transform?.runner||null),p},je=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(g=>g.as===o||g.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},qe=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:ze(e),inputs:dt(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){w.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},ze=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},re=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=te(r,e,s),c=await ee(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:z(n,i)},output:c}},Ge=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var _e=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:kt.some(t=>t in r),ne=(r,t)=>{if(!_e(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var qn=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function Je(r,t,e,n=5){let i=await zt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Je(r,i,e,5)}function Nt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Jn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),p=await t(i);return Nt(r,p,a,s)}function Qn(r){let t=new Date(r).getTime();return Date.now()<t}function Kn(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var Qe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Ke=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ie=(r,t=24)=>{let e=Ke(r);return e?e.slice(0,t):"action"},ae=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},Xe=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},Yn=(r,t,e)=>{let n=ie((e||t||"").trim()||"action"),i=`${r.type}|${Xe(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=ae(i);return`private_src_${n}_${a}`},Ye=r=>{let t=Qe(r),e=ie(t),n=ae(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Zn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ye(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ti=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ri(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function ii(r,t,e){return null}var Ze=(r,t)=>{let e=null;try{e=$(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},oi=async(r,t,e,n)=>{try{let i=W(e,n),a=Ze(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as tr,tempo as er}from"mppx/client";async function se(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return w.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),tr.create({methods:[er({account:e})],polyfill:!1}).fetch}return fetch}var oe={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=oe[t]??t,t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(u.ArgParamsSeparator),c=l.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),p=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(p)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=oe[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,g]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${g}`)[1]}}),[n,p]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="chain"||n==="nft")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var mi=r=>new I().nativeToString(m.String,r),yi=r=>new I().nativeToString(m.Uint8,r),Wi=r=>new I().nativeToString(m.Uint16,r),vi=r=>new I().nativeToString(m.Uint32,r),xi=r=>new I().nativeToString(m.Uint64,r),Ai=r=>new I().nativeToString(m.Biguint,r),Ci=r=>new I().nativeToString(m.Bool,r),wi=r=>new I().nativeToString(m.Address,r),pe=r=>new I().nativeToString(m.Asset,r),Ii=r=>new I().nativeToString(m.Hex,r),Si=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},bi=(...r)=>new I().nativeToString(m.Tuple,r),Pi=r=>new I().nativeToString(m.Struct,r),Ei=r=>new I().nativeToString(m.Vector,r);import rr from"ajv";var le=class{constructor(t){this.pendingBrand={protocol:ot("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new rr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import nr from"ajv";var gt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=$(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new nr({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ce=class{constructor(t){this.config=t;this.pendingWarp={protocol:ot("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Gt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new gt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
2
  `))}};import{existsSync as $t,mkdirSync as ir,readdirSync as ue,readFileSync as ar,unlinkSync as Ot,writeFileSync as sr}from"fs";import{join as de,resolve as ge}from"path";var Bt="$bigint:",ft=(r,t)=>typeof t=="bigint"?Bt+t.toString():t,G=(r,t)=>typeof t=="string"&&t.startsWith(Bt)?BigInt(t.slice(Bt.length)):t;var ht=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ge(n):ge(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){$t(this.cacheDir)||ir(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return de(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!$t(e))return null;let n=ar(e,"utf-8"),i=JSON.parse(n,G);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Ot(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);sr(a,JSON.stringify(i,ft),"utf-8")}async delete(t){try{let e=this.getFilePath(t);$t(e)&&Ot(e)}catch{}}async keys(t){try{let e=ue(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{ue(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Ot(de(this.cacheDir,e))})}catch{}}};var tt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,G);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,ft))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var V=class V{constructor(t,e){}async get(t){let e=V.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(V.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;V.cache.set(t,{value:e,expiresAt:i})}async delete(t){V.cache.delete(t)}async keys(t){let e=Array.from(V.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){V.cache.clear()}};V.cache=new Map;var et=V;import{readFileSync as or}from"fs";import{resolve as fe}from"path";var mt=class{constructor(t,e){let n=e?.path?fe(e.path):fe(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=or(t,"utf-8");return new Map(Object.entries(JSON.parse(e,G)))}catch(e){return w.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var he={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},yt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new tt(t,e):e?.type==="memory"?new et(t,e):e?.type==="static"?new mt(t,e):e?.type==="filesystem"?new ht(t,e):typeof window<"u"&&window.localStorage?new tt(t,e):new et(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var rt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Lt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ft=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Vt=r=>{try{return JSON.parse(r)}catch{return null}},pr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Rt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Nt(n,d,o,c)).forEach(([g,f])=>s.set(g,f))}let p=Ft(e.resolvedInputs,rt.Headers,i);if(p){let l=Vt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},lr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Lt.Get){let s=Ft(e.resolvedInputs,rt.Queries,i);if(s){let p=Vt(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},cr=(r,t,e,n,i)=>{if(r===Lt.Get)return;let a=Ft(t.resolvedInputs,rt.Payload,n);if(a&&Vt(a)!==null)return a;let{[rt.Payload]:s,[rt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},me=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Lt.Get,o=await pr(r,t,e,n,a,p),c=lr(r,t,e,l,a),d=cr(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${ur(i)}\\}\\}`,"g"),s)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),g={...this.config.vars,...e.envs}?.[o];g!=null&&a(s,g)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return F(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},ur=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var dr=["collect","compute","mcp","state","mount","unmount"],_=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new I,this.cache=new yt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return L(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),c=E(o,e),{action:d,index:g}=$(o),f=[],h=[];if(g===e-1){let S=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,S,l,i.queries),h=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),h=await this.getModifiedInputs(f));let v=h.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,y=this.getDestinationFromAction(c),x=v?this.serializer.stringToNative(v)[1]:y;if(x&&(x=l.applyInputs(x,h,this.serializer)),!x&&!dr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let C=this.getPreparedArgs(c,h);C=C.map(S=>l.applyInputs(S,h,this.serializer));let N=h.find(S=>S.input.position==="value")?.value||null,A="value"in c?c.value:null,T=N?.split(u.ArgParamsSeparator)[1]||A||"0",H=l.applyInputs(T,h,this.serializer),B=BigInt(H),U=h.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),xe=[...("transfers"in c?c.transfers:[])||[],...U||[]].map(S=>{let Ct=l.applyInputs(S,h,this.serializer),Ie=Ct.startsWith(`asset${u.ArgParamsSeparator}`)?Ct:`asset${u.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Ie)[1]}),Ae=h.find(S=>S.input.position==="data")?.value,Ce="data"in c?c.data||"":null,Ht=Ae||Ce||null,we=Ht?l.applyInputs(Ht,h,this.serializer):null,Ut={adapter:p,warp:o,chain:s,action:e,destination:x,args:C,value:B,transfers:xe,data:we,resolvedInputs:h};return await this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Ut.resolvedInputs,he.OneWeek),Ut}async getChainInfoForWarp(t,e){if(t.chain)return W(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(u.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let y=P(this.config,t);return y?this.serializer.nativeToString("address",y):null}if(c.source==="hidden"){if(c.default===void 0)return null;let y=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,y)}if(l[d])return l[d];let g=c.as||c.name,f=a?.[g],h=this.url.searchParams.get(g),v=f||h;return v?this.serializer.nativeToString(c.type,String(v)):null};return s.map((c,d)=>{let g=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:g||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),p=new R(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=pt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=pt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=dt(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Et(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=pt(p,o.decimals);return pe({...o,amount:c})}else return e}catch(n){throw w.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.handlers=n,this.factory=new _(t,e)}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},{index:g}=$(t);for(let f=1;f<=t.actions.length;f++){let h=E(t,f);if(!bt(h))continue;let v=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:y,chain:x,immediateExecution:C,executable:N}=await this.executeAction(t,f,e,v);if(y&&i.push(y),x&&(a=x),C&&s.push(C),C?.output){let{_DATA:A,...T}=C.output;Object.assign(d,T)}C?.values?.mapped&&Object.assign(d,C.values.mapped),N&&f===g+1&&N.resolvedInputs&&(p=L(N.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Mt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=J(a.when,o);if(!Q(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!bt(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),g=gr(c,d.output);return d.next=ut(this.config,this.adapters,t,o,g,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=z(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:l}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=z(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:c,body:d}=await me(s,e,t,n,i,p,a,async g=>await this.callHandler(()=>this.handlers?.onSignRequest?.(g)));w.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:c,body:d});try{let g={method:o,headers:c,body:d},h=await(await se(this.adapters))(l,g);w.debug("Collect response status",{status:h.status});let v=await h.json();w.debug("Collect response content",{content:v});let{values:y,output:x}=await Z(t.warp,v,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),h.ok?"success":"error",y,x,v)}catch(g){w.error("WarpActionExecutor: Error executing collect",g);let f=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let f=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let h=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}let p=this.factory.getSerializer(),l=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),g={};o.headers&&Object.entries(o.headers).forEach(([f,h])=>{let v=l.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());g[f]=v}),w.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:g});try{let f=new s(new URL(c),{requestInit:{headers:g}}),h=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await h.connect(f);let v={};t.resolvedInputs.forEach(({input:A,value:T})=>{if(T&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let H=A.position.replace("payload:",""),[B,U]=p.stringToNative(T);if(B==="string")v[H]=String(U);else if(B==="bool")v[H]=!!U;else if(B==="uint8"||B==="uint16"||B==="uint32"||B==="uint64"||B==="uint128"||B==="uint256"||B==="biguint"){let nt=Number(U);v[H]=(Number.isInteger(nt),nt)}else v[H]=U}}),e&&Object.assign(v,e);let y=await h.callTool({name:d,arguments:v});await h.close();let x;if(y.content&&y.content.length>0){let A=y.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=y;let{values:C,output:N}=await Z(t.warp,x,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",C,N,y)}catch(f){w.error("WarpExecutor: Error executing MCP",f);let h=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}buildCollectResult(t,e,n,i,a,s){let p=ut(this.config,this.adapters,t.warp,t.action,a,n),l=L(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Tt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let g={...n.envs,...i},f=J(s.when,g);try{if(!Q(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),w.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=J(e.when,l);if(!Q(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let g of o)l[g]!==void 0&&l[g]!==null&&(c[`state.${g}`]=l[g]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,g]of Object.entries(e.data))if(typeof g=="string"){let f=g.replace(/\{\{([^}]+)\}\}/g,(h,v)=>{let y=o[v.trim()];return y!=null?String(y):g});c[d]=fr(f)}else c[d]=g;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),T=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(T)}else{let{action:A}=$(o),T=this.factory.getStringTypedInputs(A,i),H=await this.factory.getResolvedInputs(s.name,A,T,l,a.queries);d=await this.factory.getModifiedInputs(H)}let g=ne(c.prompt,this.config.platform),f=l.applyInputs(g,d,this.factory.getSerializer()),h=L(d),v=P(this.config,s.name),y=this.factory.getSerializer(),{values:x,output:C}=await re(o,f,n,d,y,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f);A&&(C.MESSAGE=A)}let N=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:v,txHash:null,tx:null,next:ct(this.config,this.adapters,o,n,C),values:x,output:C,messages:Tt(o,{...x.mapped,...C},this.config),destination:N,resolvedInputs:h}}catch(s){return w.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:ut(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new R(this.config,l,this.adapters),c;if(a)c=a;else{let h=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(h)}let d=o.buildInputBag(c,this.factory.getSerializer()),g={...i.envs??{},...d},f=J(e.when,g);return Q(f)}},gr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},fr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var xt=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw w.error("WarpIndex: Error searching for warps: ",i),i}}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?X(t,this.config.defaultChain):O(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Jt(t):Qt(i.identifier);if(this.resolver){let h=null;if(a==="hash")h=await this.resolver.getByHash(s,e);else if(a==="alias"){let v=`${i.chain}:${s}`;h=await this.resolver.getByAlias(v,e)||await this.resolver.getByAlias(s,e)}h&&(p=h.warp,l=h.registryInfo,o=h.brand)}else{let h=W(i.chain,this.adapters);if(a==="hash"){p=await h.builder().createFromTransactionHash(s,e);let v=await h.registry.getInfoByHash(s,e);l=v.registryInfo,o=v.brand}else if(a==="alias"){let v=await h.registry.getInfoByAlias(s,e);l=v.registryInfo,o=v.brand,v.registryInfo&&(p=await h.builder().createFromTransactionHash(v.registryInfo.hash,e))}}if(p&&p.meta&&(hr(p,i.chain,l,i.identifier),p.meta.query=c?Kt(c):null),!p)return n;let d=p.chain||i.chain,g=this.adapters.find(h=>h.chainInfo.name.toLowerCase()===d.toLowerCase()),f=g?await new R(this.config,g,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return w.error("Error detecting warp link",a),n}}},hr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Pt(null,"alias",e.alias):Pt(t,"hash",e?.hash??n))};var ye=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new it(e));return new at(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new vt(this.config,this.chains,t)}async detectWarp(t,e){return new At(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await h.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:g}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async h=>{await l.evaluateOutput(p,h)},resolvedInputs:g}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=O(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??$(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=ct(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new _(this.config,this.chains)}get index(){return new xt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return lt(t,this.config)}};var We=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function ns(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ve(t,n)!==i)return!1;return!0}function is(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ve(t,i):i;return e}function ve(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{It as BrowserCryptoProvider,Nr as CLOUD_WALLET_PROVIDERS,he as CacheTtl,Tr as EvmWalletChainNames,Rr as MultiversxWalletChainNames,St as NodeCryptoProvider,nn as WARP_LANGUAGES,b as WarpAssets,le as WarpBrandBuilder,ce as WarpBuilder,yt as WarpCache,Wt as WarpCacheKey,$e as WarpChainDisplayNames,Oe as WarpChainLogos,Be as WarpChainName,it as WarpChainResolver,ye as WarpClient,at as WarpCompositeResolver,D as WarpConfig,u as WarpConstants,vt as WarpExecutor,_ as WarpFactory,xt as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,At as WarpLinkDetecter,w as WarpLogger,Dt as WarpPlatformName,kt as WarpPlatforms,j as WarpProtocolVersions,I as WarpSerializer,We as WarpTypeRegistry,gt as WarpValidator,wi as address,Tt as applyOutputToMessages,pe as asset,Ai as biguint,Ci as bool,Ye as buildGeneratedFallbackWarpIdentifier,Yn as buildGeneratedSourceWarpIdentifier,dt as buildInputsContext,z as buildMappedOutput,ke as buildNestedPayload,zr as bytesToBase64,Le as bytesToHex,oi as checkWarpAssetBalance,K as cleanWarpIdentifier,Nt as createAuthHeaders,Rt as createAuthMessage,_r as createCryptoProvider,ii as createDefaultWalletProvider,Jn as createHttpAuthHeaders,Je as createSignableMessage,sn as createWarpI18nText,Pt as createWarpIdentifier,en as doesWarpRequireWallet,ee as evaluateOutputCommon,Q as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,re as extractPromptOutput,Qt as extractQueryStringFromIdentifier,Jt as extractQueryStringFromUrl,L as extractResolvedInputValues,Kr as extractWarpSecrets,W as findWarpAdapterForChain,Vr as getChainDisplayName,Hr as getChainLogo,jt as getCryptoProvider,Qe as getGeneratedSourceWarpName,ot as getLatestProtocolIdentifier,se as getMppFetch,ct as getNextInfo,ut as getNextInfoForStatus,qn as getProviderConfig,qt as getRandomBytes,zt as getRandomHex,Ze as getRequiredAssetIds,vr as getWalletFromConfigOrFail,E as getWarpActionByIndex,Dr as getWarpBrandLogoUrl,kr as getWarpChainAssetLogoUrl,Mr as getWarpChainInfoLogoUrl,dn as getWarpIdentifierWithQuery,O as getWarpInfoFromIdentifier,$ as getWarpInputAction,Se as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ee as getWarpWalletExternalId,Te as getWarpWalletExternalIdFromConfig,Cr as getWarpWalletExternalIdFromConfigOrFail,Pe as getWarpWalletMnemonic,Ar as getWarpWalletMnemonicFromConfig,be as getWarpWalletPrivateKey,xr as getWarpWalletPrivateKeyFromConfig,hn as hasInputPrefix,Ii as hex,ri as initializeWalletCache,cn as isEqualWarpIdentifier,ti as isGeneratedSourcePrivateIdentifier,_e as isPlatformValue,bt as isWarpActionAutoExecute,an as isWarpI18nText,wr as isWarpWalletReadOnly,ns as matchesTrigger,Zt as mergeNestedPayload,br as normalizeAndValidateMnemonic,Re as normalizeMnemonic,Si as option,Ge as parseOutputOutIndex,Kn as parseSignedMessage,Kt as parseWarpQueryStringToObject,un as removeWarpChainPrefix,Sr as removeWarpWalletFromConfig,F as replacePlaceholders,J as replacePlaceholdersInWhenExpression,is as resolveInputs,Yt as resolveNextString,ve as resolvePath,ne as resolvePlatformValue,lt as resolveWarpText,Mt as safeWindow,qr as setCryptoProvider,Ir as setWarpWalletInConfig,pt as shiftBigintBy,Et as splitInput,Zn as stampGeneratedWarpMeta,mi as string,Pi as struct,Gr as testCryptoAvailability,Me as toInputPayloadValue,Gt as toPreviewText,bi as tuple,Wi as uint16,vi as uint32,xi as uint64,yi as uint8,Ne as validateMnemonicLength,Qn as validateSignedMessage,Ei as vector,Lr as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "4.16.0",
3
+ "version": "4.16.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",