@joai/warps 3.4.1 → 3.5.0

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
@@ -182,6 +182,7 @@ type WarpProviderConfig = {
182
182
  };
183
183
  type WarpClientConfig = {
184
184
  env: WarpChainEnv;
185
+ platform?: WarpPlatformName;
185
186
  clientUrl?: string;
186
187
  currentUrl?: string;
187
188
  vars?: Record<string, string | number>;
@@ -352,6 +353,12 @@ declare enum WarpChainName {
352
353
  Solana = "solana",
353
354
  Near = "near"
354
355
  }
356
+ declare enum WarpPlatformName {
357
+ Macos = "macos",
358
+ Linux = "linux",
359
+ Windows = "windows"
360
+ }
361
+ declare const WarpPlatforms: WarpPlatformName[];
355
362
  declare const EvmWalletChainNames: WarpChainName[];
356
363
  declare const CLOUD_WALLET_PROVIDERS: WarpWalletProvider[];
357
364
  declare const WarpConstants: {
@@ -433,6 +440,7 @@ type WarpAlert = {
433
440
  };
434
441
  type WarpAlerts = Record<WarpAlertName, WarpAlert>;
435
442
 
443
+ type WarpPlatformValue<T> = T | Partial<Record<WarpPlatformName, T>>;
436
444
  type WarpExplorerName = string;
437
445
  type WarpChainInfoLogoThemed = Record<WarpTheme, string>;
438
446
  type WarpChainInfoLogo = string | WarpChainInfoLogoThemed;
@@ -575,7 +583,7 @@ type WarpPromptAction = {
575
583
  type: WarpActionType;
576
584
  label: WarpText;
577
585
  description?: WarpText | null;
578
- prompt: string;
586
+ prompt: WarpPlatformValue<string>;
579
587
  inputs?: WarpActionInput[];
580
588
  primary?: boolean;
581
589
  auto?: boolean;
@@ -818,6 +826,9 @@ declare const extractPromptOutput: (warp: Warp, promptValue: string, actionIndex
818
826
  }>;
819
827
  declare const parseOutputOutIndex: (outputPath: string) => number | null;
820
828
 
829
+ declare const isPlatformValue: <T>(value: WarpPlatformValue<T>) => value is Partial<Record<WarpPlatformName, T>>;
830
+ declare const resolvePlatformValue: <T>(value: WarpPlatformValue<T>, platform?: WarpPlatformName) => T;
831
+
821
832
  /**
822
833
  * Builds a nested payload object from a position string and field value.
823
834
  * Position strings should be in format: "payload:path.to.nested.location"
@@ -1265,4 +1276,4 @@ declare class WarpValidator {
1265
1276
  private validateSchema;
1266
1277
  }
1267
1278
 
1268
- 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, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, 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, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, 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 WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1279
+ 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, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, 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, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, 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 WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, 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
@@ -182,6 +182,7 @@ type WarpProviderConfig = {
182
182
  };
183
183
  type WarpClientConfig = {
184
184
  env: WarpChainEnv;
185
+ platform?: WarpPlatformName;
185
186
  clientUrl?: string;
186
187
  currentUrl?: string;
187
188
  vars?: Record<string, string | number>;
@@ -352,6 +353,12 @@ declare enum WarpChainName {
352
353
  Solana = "solana",
353
354
  Near = "near"
354
355
  }
356
+ declare enum WarpPlatformName {
357
+ Macos = "macos",
358
+ Linux = "linux",
359
+ Windows = "windows"
360
+ }
361
+ declare const WarpPlatforms: WarpPlatformName[];
355
362
  declare const EvmWalletChainNames: WarpChainName[];
356
363
  declare const CLOUD_WALLET_PROVIDERS: WarpWalletProvider[];
357
364
  declare const WarpConstants: {
@@ -433,6 +440,7 @@ type WarpAlert = {
433
440
  };
434
441
  type WarpAlerts = Record<WarpAlertName, WarpAlert>;
435
442
 
443
+ type WarpPlatformValue<T> = T | Partial<Record<WarpPlatformName, T>>;
436
444
  type WarpExplorerName = string;
437
445
  type WarpChainInfoLogoThemed = Record<WarpTheme, string>;
438
446
  type WarpChainInfoLogo = string | WarpChainInfoLogoThemed;
@@ -575,7 +583,7 @@ type WarpPromptAction = {
575
583
  type: WarpActionType;
576
584
  label: WarpText;
577
585
  description?: WarpText | null;
578
- prompt: string;
586
+ prompt: WarpPlatformValue<string>;
579
587
  inputs?: WarpActionInput[];
580
588
  primary?: boolean;
581
589
  auto?: boolean;
@@ -818,6 +826,9 @@ declare const extractPromptOutput: (warp: Warp, promptValue: string, actionIndex
818
826
  }>;
819
827
  declare const parseOutputOutIndex: (outputPath: string) => number | null;
820
828
 
829
+ declare const isPlatformValue: <T>(value: WarpPlatformValue<T>) => value is Partial<Record<WarpPlatformName, T>>;
830
+ declare const resolvePlatformValue: <T>(value: WarpPlatformValue<T>, platform?: WarpPlatformName) => T;
831
+
821
832
  /**
822
833
  * Builds a nested payload object from a position string and field value.
823
834
  * Position strings should be in format: "payload:path.to.nested.location"
@@ -1265,4 +1276,4 @@ declare class WarpValidator {
1265
1276
  private validateSchema;
1266
1277
  }
1267
1278
 
1268
- 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, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, 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, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, 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 WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1279
+ 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, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, 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, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, 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 WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, 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 Ve=Object.create;var ft=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ue=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var Le=(r,t)=>{for(var e in t)ft(r,e,{get:t[e],enumerable:!0})},ne=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fe(t))!De.call(r,i)&&i!==e&&ft(r,i,{get:()=>t[i],enumerable:!(n=He(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?Ve(Ue(r)):{},ne(t||!r||!r.__esModule?ft(e,"default",{value:r,enumerable:!0}):e,r)),je=r=>ne(ft({},"__esModule",{value:!0}),r);var Kr={};Le(Kr,{BrowserCryptoProvider:()=>gt,CLOUD_WALLET_PROVIDERS:()=>Ke,CacheTtl:()=>Qt,EvmWalletChainNames:()=>Qe,NodeCryptoProvider:()=>ht,WARP_LANGUAGES:()=>or,WarpBrandBuilder:()=>kt,WarpBuilder:()=>Gt,WarpCache:()=>pt,WarpCacheKey:()=>St,WarpChainName:()=>ue,WarpClient:()=>Yt,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>lt,WarpFactory:()=>G,WarpIndex:()=>ut,WarpInputTypes:()=>m,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>dt,WarpLogger:()=>C,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>te,WarpValidator:()=>at,address:()=>Lr,applyOutputToMessages:()=>vt,asset:()=>zt,biguint:()=>Ur,bool:()=>Dr,buildGeneratedFallbackWarpIdentifier:()=>we,buildGeneratedSourceWarpIdentifier:()=>Pr,buildInputsContext:()=>nt,buildMappedOutput:()=>K,buildNestedPayload:()=>he,bytesToBase64:()=>nr,bytesToHex:()=>de,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>Ct,createAuthMessage:()=>At,createCryptoProvider:()=>ar,createDefaultWalletProvider:()=>Rr,createHttpAuthHeaders:()=>Cr,createSignableMessage:()=>ve,createWarpI18nText:()=>cr,createWarpIdentifier:()=>yt,evaluateOutputCommon:()=>Dt,evaluateWhenCondition:()=>$t,extractCollectOutput:()=>it,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>Lt,extractQueryStringFromIdentifier:()=>Vt,extractQueryStringFromUrl:()=>Ot,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>sr,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Tt,getEventNameFromWarp:()=>Ze,getGeneratedSourceWarpName:()=>Ae,getLatestProtocolIdentifier:()=>tt,getNextInfo:()=>z,getProviderConfig:()=>Ar,getRandomBytes:()=>Et,getRandomHex:()=>Rt,getWalletFromConfigOrFail:()=>Me,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>Ye,getWarpChainAssetLogoUrl:()=>tr,getWarpChainInfoLogoUrl:()=>er,getWarpIdentifierWithQuery:()=>gr,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>ie,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>oe,getWarpWalletExternalIdFromConfig:()=>pe,getWarpWalletExternalIdFromConfigOrFail:()=>ke,getWarpWalletMnemonic:()=>se,getWarpWalletMnemonicFromConfig:()=>ze,getWarpWalletPrivateKey:()=>ae,getWarpWalletPrivateKeyFromConfig:()=>qe,handleX402Payment:()=>qt,hasInputPrefix:()=>hr,hex:()=>jr,initializeWalletCache:()=>Er,isEqualWarpIdentifier:()=>lr,isGeneratedSourcePrivateIdentifier:()=>Tr,isWarpActionAutoExecute:()=>mt,isWarpI18nText:()=>pr,isWarpWalletReadOnly:()=>Ge,mergeNestedPayload:()=>Ut,normalizeAndValidateMnemonic:()=>Je,normalizeMnemonic:()=>ce,option:()=>Mr,parseOutputOutIndex:()=>We,parseSignedMessage:()=>wr,parseWarpQueryStringToObject:()=>Ht,removeWarpChainPrefix:()=>fr,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Bt,resolveWarpText:()=>rt,safeWindow:()=>bt,setCryptoProvider:()=>rr,setWarpWalletInConfig:()=>_e,shiftBigintBy:()=>et,splitInput:()=>Wt,stampGeneratedWarpMeta:()=>br,string:()=>$r,struct:()=>zr,testCryptoAvailability:()=>ir,toInputPayloadValue:()=>me,toPreviewText:()=>Nt,tuple:()=>qr,uint16:()=>Vr,uint32:()=>Hr,uint64:()=>Fr,uint8:()=>Or,validateMnemonicLength:()=>le,validateSignedMessage:()=>xr,vector:()=>kr,withAdapterFallback:()=>Xe});module.exports=je(Kr);var Me=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ie=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>ie(r.user?.wallets?.[t]||null),ae=r=>r?typeof r=="string"?r:r.privateKey||null:null,se=r=>r?typeof r=="string"?r:r.mnemonic||null:null,oe=r=>r?typeof r=="string"?r:r.externalId||null:null,qe=(r,t)=>ae(r.user?.wallets?.[t]||null)?.trim()||null,ze=(r,t)=>se(r.user?.wallets?.[t]||null)?.trim()||null,pe=(r,t)=>oe(r.user?.wallets?.[t]||null)?.trim()||null,ke=(r,t)=>{let e=pe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ge=r=>typeof r=="string",_e=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ce=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},le=(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`)},Je=(r,t=24)=>{let e=ce(r);return le(e,t),e};var ue=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(ue||{}),Qe=["ethereum","base","arbitrum","polygon","somnia"],Ke=["coinbase","privy","gaupa"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},bt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 Xe=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ze=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Ye=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},tr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},er=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var gt=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}},ht=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"}`)}}},M=null;function Tt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new gt,M;if(typeof process<"u"&&process.versions?.node)return M=new ht,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function rr(r){M=r}async function Et(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Tt()).getRandomBytes(r)}function de(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 nr(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 Rt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Et(r/2,t);return de(e)}async function ir(){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 Et(16),r.randomBytes=!0}catch{}return r}function ar(){return Tt()}var sr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},mt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},et=(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)},Nt=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Bt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),$t=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 or={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"},rt=(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,cr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,lr=(r,t)=>!r||!t?!1:J(r)===J(t),yt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=fe(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=ur(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},ur=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,dr=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},fe=r=>{let t=dr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=fe(a);return[i,...s]},Ot=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Vt=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},Ht=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},fr=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()},gr=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 Wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},hr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=Wt(r)[0];return t.has(e)};var vt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var ge=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new ge.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 mr="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(mr))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=D(s,{...e.vars,...i});return[{identifier:f,url:Ft(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=D(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:Ft(t,v,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=p;for(let{regex:T,field:V}of g){let x=V?yr(f,V):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:Ft(t,A,r)}}).filter(f=>f!==null)},Ft=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},yr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var k=class k{static debug(...t){k.isTestEnv||console.debug(...t)}static info(...t){k.isTestEnv||console.info(...t)}static warn(...t){k.isTestEnv||console.warn(...t)}static error(...t){k.isTestEnv||console.error(...t)}};k.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=k;function he(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ut(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]=Ut(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(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(l.Position.Payload)){let s=he(n.input.position,i,a);e=Ut(e,s)}else e[i]=a}),e}function nt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let c=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[c]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${c}.token`]=d,i[`${c}.identifier`]=d,i[`${c}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var ye=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=We(p);if(c!==null&&c!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},it=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:o,output:u}=ye(r,e,p);return{values:{string:c,native:o,mapped:K(n,i)},output:await Dt(r,u,t,e,n,i,a)}},Dt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Wr(p,r,n,i,a),p=await vr(r,p,e,i,a,s.transform?.runner||null),p},Wr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.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(l.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(l.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 c={...s,out:e,inputs:nt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,c),c[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,c[o]=null}return s},Lt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=ye(r,e,s),u=await Dt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:K(n,i)},output:u}},We=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 Ar=(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 ve(r,t,e,n=5){let i=await Rt(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 At(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return ve(r,i,e,5)}function Ct(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Cr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await At(r,e,n),p=await t(i);return Ct(r,p,a,s)}function xr(r){let t=new Date(r).getTime();return Date.now()<t}function wr(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 Ae=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Ir=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Ce=(r,t=24)=>{let e=Ir(r);return e?e.slice(0,t):"action"},xe=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)},Sr=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()}},Pr=(r,t,e)=>{let n=Ce((e||t||"").trim()||"action"),i=`${r.type}|${Sr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=xe(i);return`private_src_${n}_${a}`},we=r=>{let t=Ae(r),e=Ce(t),n=xe(t.trim().toLowerCase());return`private_gen_${e}_${n}`},br=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||we(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Tr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Er(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 Rr(r,t,e){return null}var jt=require("@x402/core/client"),Mt=require("@x402/core/http");async function qt(r,t,e,n,i){let a=await Nr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Nr=async(r,t)=>{let e=await Br(r),i=new Mt.x402HTTPClient(new jt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new jt.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Mt.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Br=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[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(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 $r=r=>new w().nativeToString(m.String,r),Or=r=>new w().nativeToString(m.Uint8,r),Vr=r=>new w().nativeToString(m.Uint16,r),Hr=r=>new w().nativeToString(m.Uint32,r),Fr=r=>new w().nativeToString(m.Uint64,r),Ur=r=>new w().nativeToString(m.Biguint,r),Dr=r=>new w().nativeToString(m.Bool,r),Lr=r=>new w().nativeToString(m.Address,r),zt=r=>new w().nativeToString(m.Asset,r),jr=r=>new w().nativeToString(m.Hex,r),Mr=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},qr=(...r)=>new w().nativeToString(m.Tuple,r),zr=r=>new w().nativeToString(m.Struct,r),kr=r=>new w().nativeToString(m.Vector,r);var Ie=_(require("ajv"),1);var kt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Ie.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Se=_(require("ajv"),1);var at=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(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}}validatePrimaryAction(t){try{let{action:e}=R(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Se.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 Gt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Nt(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 at(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var S=require("fs"),Z=require("path");var _t="$bigint:",xt=(r,t)=>typeof t=="bigint"?_t+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(_t)?BigInt(t.slice(_t.length)):t;var wt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,Z.resolve)(n):(0,Z.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,xt),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var st=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,xt))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{constructor(t,e){}get(t){let e=L.cache.get(t);return e?Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;L.cache.set(t,{value:e,expiresAt:i})}forget(t){L.cache.delete(t)}clear(){L.cache.clear()}};L.cache=new Map;var ot=L;var Pe=require("fs"),Jt=require("path");var It=class{constructor(t,e){let n=e?.path?(0,Jt.resolve)(e.path):(0,Jt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Pe.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Qt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},St={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}`},pt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new st(t,e):e?.type==="memory"?new ot(t,e):e?.type==="static"?new It(t,e):e?.type==="filesystem"?new wt(t,e):typeof window<"u"&&window.localStorage?new st(t,e):new ot(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var ct={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Kt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Xt=(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)},Zt=r=>{try{return JSON.parse(r)}catch{return null}},Gr=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:c,nonce:o,expiresAt:u}=await At(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(Ct(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=Xt(e.resolvedInputs,ct.Headers,i);if(p){let c=Zt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},_r=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Kt.Get){let s=Xt(e.resolvedInputs,ct.Queries,i);if(s){let p=Zt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Jr=(r,t,e,n,i)=>{if(r===Kt.Get)return;let a=Xt(t.resolvedInputs,ct.Payload,n);if(a&&Zt(a)!==null)return a;let{[ct.Payload]:s,[ct.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},be=async(r,t,e,n,i,a,s,p)=>{let c=t.method||Kt.Get,o=await Gr(r,t,e,n,a,p),u=_r(r,t,e,c,a),d=Jr(c,e,i,a,s);return{url:u,method:c,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);return await this.applyGlobals(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=I(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===l.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(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=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 w,this.cache=new pt(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(St.WarpExecutable(t,e||"",n))||[];return $(i)}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),c=new N(this.config,p,this.adapters),o=await c.apply(t,i),u=E(o,e),{action:d,index:h}=R(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let T=A.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,V=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:V;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let O=this.getPreparedArgs(u,A);O=O.map(P=>c.applyInputs(P,A,this.serializer,f));let H=A.find(P=>P.input.position==="value")?.value||null,b="value"in u?u.value:null,F=H?.split(l.ArgParamsSeparator)[1]||b||"0",Y=c.applyInputs(F,A,this.serializer,f),Te=BigInt(Y),Ee=A.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Re=[...("transfers"in u?u.transfers:[])||[],...Ee||[]].map(P=>{let Pt=c.applyInputs(P,A,this.serializer,f),Oe=Pt.startsWith(`asset${l.ArgParamsSeparator}`)?Pt:`asset${l.ArgParamsSeparator}${Pt}`;return this.serializer.stringToNative(Oe)[1]}),Ne=A.find(P=>P.input.position==="data")?.value,Be="data"in u?u.data||"":null,ee=Ne||Be||null,$e=ee?c.applyInputs(ee,A,this.serializer,f):null,re={adapter:p,warp:o,chain:s,action:e,destination:x,args:O,value:Te,transfers:Re,data:$e,resolvedInputs:A};return this.cache.set(St.WarpExecutable(this.config.env,o.meta?.hash||"",e),re.resolvedInputs,Qt.OneWeek),re}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===l.Source.UserWallet){let v=I(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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 c=et(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=et(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=nt(t,this.serializer,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Wt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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 u=et(p,o.decimals);return zt({...o,amount:u})}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,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 lt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=R(t);for(let g=1;g<=t.actions.length;g++){let y=E(t,g);if(!mt(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:T}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),T&&g===h+1&&T.resolvedInputs&&(p=$(T.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return{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):bt.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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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(!mt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:I(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c.tx);return u.next=z(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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=I(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:c}=await it(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await be(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let g=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await qt(g,c,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await it(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=$(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=I(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=$(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=$(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:y}}let p=this.factory.getSerializer(),c=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:O})=>{if(O&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[b,F]=p.stringToNative(O);if(b==="string")f[H]=String(F);else if(b==="bool")f[H]=!!F;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let Y=Number(F);f[H]=(Number.isInteger(Y),Y)}else f[H]=F}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:V}=await it(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,V,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let p=z(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:vt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),c=new N(this.config,p,this.adapters),o=await c.apply(t,a),u=E(o,n),{action:d}=R(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let H=this.factory.getStringTypedInputs(e,i),b=await this.factory.getResolvedInputs(s.name,e,H,c,a.queries);f=await this.factory.getModifiedInputs(b)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),T=I(this.config,s.name),V=this.factory.getSerializer(),{values:x,output:O}=await Lt(o,v,n,f,V,this.config);return{status:"success",warp:o,action:n,user:T,txHash:null,tx:null,next:z(this.config,this.adapters,o,n,O),values:x,output:O,messages:vt(o,O,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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),c=W(p.name,this.adapters),o=new N(this.config,c,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Bt(e.when,f);return $t(v)}};var ut=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 dt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Ot(t):Vt(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Qr(p,u.chainInfo.name,c,i.identifier),p.meta.query=d?Ht(d):null),!p)return n;let h=p.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new N(this.config,g,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Qr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?yt(t,"alias",e.alias):yt(t,"hash",e?.hash??n))};var Yt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new lt(this.config,this.chains,t)}async detectWarp(t,e){return new dt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=B(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(!I(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??R(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=z(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 G(this.config,this.chains)}get index(){return new ut(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 rt(t,this.config)}};var te=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()]))}};0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
1
+ "use strict";var De=Object.create;var ft=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,qe=Object.prototype.hasOwnProperty;var ze=(r,t)=>{for(var e in t)ft(r,e,{get:t[e],enumerable:!0})},se=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of je(t))!qe.call(r,i)&&i!==e&&ft(r,i,{get:()=>t[i],enumerable:!(n=Le(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?De(Me(r)):{},se(t||!r||!r.__esModule?ft(e,"default",{value:r,enumerable:!0}):e,r)),ke=r=>se(ft({},"__esModule",{value:!0}),r);var en={};ze(en,{BrowserCryptoProvider:()=>gt,CLOUD_WALLET_PROVIDERS:()=>tr,CacheTtl:()=>Zt,EvmWalletChainNames:()=>Ye,NodeCryptoProvider:()=>ht,WARP_LANGUAGES:()=>ur,WarpBrandBuilder:()=>Jt,WarpBuilder:()=>Qt,WarpCache:()=>pt,WarpCacheKey:()=>St,WarpChainName:()=>ge,WarpClient:()=>re,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>lt,WarpFactory:()=>G,WarpIndex:()=>ut,WarpInputTypes:()=>m,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>dt,WarpLogger:()=>C,WarpPlatformName:()=>Tt,WarpPlatforms:()=>bt,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>ne,WarpValidator:()=>at,address:()=>kr,applyOutputToMessages:()=>vt,asset:()=>_t,biguint:()=>qr,bool:()=>zr,buildGeneratedFallbackWarpIdentifier:()=>Te,buildGeneratedSourceWarpIdentifier:()=>Nr,buildInputsContext:()=>nt,buildMappedOutput:()=>K,buildNestedPayload:()=>We,bytesToBase64:()=>or,bytesToHex:()=>he,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>Ct,createAuthMessage:()=>At,createCryptoProvider:()=>cr,createDefaultWalletProvider:()=>Or,createHttpAuthHeaders:()=>Pr,createSignableMessage:()=>we,createWarpI18nText:()=>fr,createWarpIdentifier:()=>yt,evaluateOutputCommon:()=>jt,evaluateWhenCondition:()=>Ot,extractCollectOutput:()=>it,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>Mt,extractQueryStringFromIdentifier:()=>Ft,extractQueryStringFromUrl:()=>Ht,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>lr,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Rt,getEventNameFromWarp:()=>rr,getGeneratedSourceWarpName:()=>Ie,getLatestProtocolIdentifier:()=>tt,getNextInfo:()=>z,getProviderConfig:()=>Sr,getRandomBytes:()=>Nt,getRandomHex:()=>Bt,getWalletFromConfigOrFail:()=>Ge,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>nr,getWarpChainAssetLogoUrl:()=>ir,getWarpChainInfoLogoUrl:()=>ar,getWarpIdentifierWithQuery:()=>Wr,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>oe,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>le,getWarpWalletExternalIdFromConfig:()=>ue,getWarpWalletExternalIdFromConfigOrFail:()=>Qe,getWarpWalletMnemonic:()=>ce,getWarpWalletMnemonicFromConfig:()=>Je,getWarpWalletPrivateKey:()=>pe,getWarpWalletPrivateKeyFromConfig:()=>_e,handleX402Payment:()=>Gt,hasInputPrefix:()=>vr,hex:()=>Gr,initializeWalletCache:()=>Vr,isEqualWarpIdentifier:()=>gr,isGeneratedSourcePrivateIdentifier:()=>$r,isPlatformValue:()=>xe,isWarpActionAutoExecute:()=>mt,isWarpI18nText:()=>dr,isWarpWalletReadOnly:()=>Ke,mergeNestedPayload:()=>Lt,normalizeAndValidateMnemonic:()=>Ze,normalizeMnemonic:()=>de,option:()=>_r,parseOutputOutIndex:()=>Ce,parseSignedMessage:()=>br,parseWarpQueryStringToObject:()=>Ut,removeWarpChainPrefix:()=>yr,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Vt,resolvePlatformValue:()=>qt,resolveWarpText:()=>rt,safeWindow:()=>Et,setCryptoProvider:()=>sr,setWarpWalletInConfig:()=>Xe,shiftBigintBy:()=>et,splitInput:()=>Wt,stampGeneratedWarpMeta:()=>Br,string:()=>Ur,struct:()=>Qr,testCryptoAvailability:()=>pr,toInputPayloadValue:()=>ve,toPreviewText:()=>$t,tuple:()=>Jr,uint16:()=>Lr,uint32:()=>jr,uint64:()=>Mr,uint8:()=>Dr,validateMnemonicLength:()=>fe,validateSignedMessage:()=>Tr,vector:()=>Kr,withAdapterFallback:()=>er});module.exports=ke(en);var Ge=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},oe=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>oe(r.user?.wallets?.[t]||null),pe=r=>r?typeof r=="string"?r:r.privateKey||null:null,ce=r=>r?typeof r=="string"?r:r.mnemonic||null:null,le=r=>r?typeof r=="string"?r:r.externalId||null:null,_e=(r,t)=>pe(r.user?.wallets?.[t]||null)?.trim()||null,Je=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,ue=(r,t)=>le(r.user?.wallets?.[t]||null)?.trim()||null,Qe=(r,t)=>{let e=ue(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ke=r=>typeof r=="string",Xe=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},de=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},fe=(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`)},Ze=(r,t=24)=>{let e=de(r);return fe(e,t),e};var ge=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(ge||{}),Tt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Tt||{}),bt=Object.values(Tt),Ye=["ethereum","base","arbitrum","polygon","somnia"],tr=["coinbase","privy","gaupa"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},Et=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 er=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var rr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var nr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},ir=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},ar=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var gt=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}},ht=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"}`)}}},M=null;function Rt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new gt,M;if(typeof process<"u"&&process.versions?.node)return M=new ht,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function sr(r){M=r}async function Nt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Rt()).getRandomBytes(r)}function he(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 or(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 Bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Nt(r/2,t);return he(e)}async function pr(){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 Nt(16),r.randomBytes=!0}catch{}return r}function cr(){return Rt()}var lr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},mt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},et=(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)},$t=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Vt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ot=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 ur={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"},rt=(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""},dr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,fr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,gr=(r,t)=>!r||!t?!1:J(r)===J(t),yt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=me(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=hr(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},hr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,mr=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},me=r=>{let t=mr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=me(a);return[i,...s]},Ht=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ft=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},Ut=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},yr=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()},Wr=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 Wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},vr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=Wt(r)[0];return t.has(e)};var vt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var ye=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new ye.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 Ar="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ar))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=D(s,{...e.vars,...i});return[{identifier:f,url:Dt(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=D(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:Dt(t,v,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=p;for(let{regex:b,field:H}of g){let x=H?Cr(f,H):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:Dt(t,A,r)}}).filter(f=>f!==null)},Dt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Cr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var k=class k{static debug(...t){k.isTestEnv||console.debug(...t)}static info(...t){k.isTestEnv||console.info(...t)}static warn(...t){k.isTestEnv||console.warn(...t)}static error(...t){k.isTestEnv||console.error(...t)}};k.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=k;function We(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Lt(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]=Lt(e[n],t[n]):e[n]=t[n]}),e}function ve(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=ve(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=We(n.input.position,i,a);e=Lt(e,s)}else e[i]=a}),e}function nt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let c=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[c]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${c}.token`]=d,i[`${c}.identifier`]=d,i[`${c}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Ae=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=Ce(p);if(c!==null&&c!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},it=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:o,output:u}=Ae(r,e,p);return{values:{string:c,native:o,mapped:K(n,i)},output:await jt(r,u,t,e,n,i,a)}},jt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=xr(p,r,n,i,a),p=await wr(r,p,e,i,a,s.transform?.runner||null),p},xr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},wr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(l.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 c={...s,out:Ir(e),inputs:nt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,c),c[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,c[o]=null}return s},Ir=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},Mt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=Ae(r,e,s),u=await jt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:K(n,i)},output:u}},Ce=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 xe=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:bt.some(t=>t in r),qt=(r,t)=>{if(!xe(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 Sr=(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 we(r,t,e,n=5){let i=await Bt(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 At(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return we(r,i,e,5)}function Ct(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Pr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await At(r,e,n),p=await t(i);return Ct(r,p,a,s)}function Tr(r){let t=new Date(r).getTime();return Date.now()<t}function br(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 Ie=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Er=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Se=(r,t=24)=>{let e=Er(r);return e?e.slice(0,t):"action"},Pe=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)},Rr=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()}},Nr=(r,t,e)=>{let n=Se((e||t||"").trim()||"action"),i=`${r.type}|${Rr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Pe(i);return`private_src_${n}_${a}`},Te=r=>{let t=Ie(r),e=Se(t),n=Pe(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Br=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Te(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 Vr(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 Or(r,t,e){return null}var zt=require("@x402/core/client"),kt=require("@x402/core/http");async function Gt(r,t,e,n,i){let a=await Hr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Hr=async(r,t)=>{let e=await Fr(r),i=new kt.x402HTTPClient(new zt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new zt.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new kt.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Fr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[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(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 Ur=r=>new w().nativeToString(m.String,r),Dr=r=>new w().nativeToString(m.Uint8,r),Lr=r=>new w().nativeToString(m.Uint16,r),jr=r=>new w().nativeToString(m.Uint32,r),Mr=r=>new w().nativeToString(m.Uint64,r),qr=r=>new w().nativeToString(m.Biguint,r),zr=r=>new w().nativeToString(m.Bool,r),kr=r=>new w().nativeToString(m.Address,r),_t=r=>new w().nativeToString(m.Asset,r),Gr=r=>new w().nativeToString(m.Hex,r),_r=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Jr=(...r)=>new w().nativeToString(m.Tuple,r),Qr=r=>new w().nativeToString(m.Struct,r),Kr=r=>new w().nativeToString(m.Vector,r);var be=_(require("ajv"),1);var Jt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new be.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Ee=_(require("ajv"),1);var at=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(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}}validatePrimaryAction(t){try{let{action:e}=R(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ee.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 Qt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 $t(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 at(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var S=require("fs"),Z=require("path");var Kt="$bigint:",xt=(r,t)=>typeof t=="bigint"?Kt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Kt)?BigInt(t.slice(Kt.length)):t;var wt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,Z.resolve)(n):(0,Z.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,xt),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var st=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,xt))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{constructor(t,e){}get(t){let e=L.cache.get(t);return e?Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;L.cache.set(t,{value:e,expiresAt:i})}forget(t){L.cache.delete(t)}clear(){L.cache.clear()}};L.cache=new Map;var ot=L;var Re=require("fs"),Xt=require("path");var It=class{constructor(t,e){let n=e?.path?(0,Xt.resolve)(e.path):(0,Xt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Re.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Zt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},St={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}`},pt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new st(t,e):e?.type==="memory"?new ot(t,e):e?.type==="static"?new It(t,e):e?.type==="filesystem"?new wt(t,e):typeof window<"u"&&window.localStorage?new st(t,e):new ot(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var ct={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Yt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},te=(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)},ee=r=>{try{return JSON.parse(r)}catch{return null}},Xr=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:c,nonce:o,expiresAt:u}=await At(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(Ct(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=te(e.resolvedInputs,ct.Headers,i);if(p){let c=ee(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Zr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Yt.Get){let s=te(e.resolvedInputs,ct.Queries,i);if(s){let p=ee(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Yr=(r,t,e,n,i)=>{if(r===Yt.Get)return;let a=te(t.resolvedInputs,ct.Payload,n);if(a&&ee(a)!==null)return a;let{[ct.Payload]:s,[ct.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},Ne=async(r,t,e,n,i,a,s,p)=>{let c=t.method||Yt.Get,o=await Xr(r,t,e,n,a,p),u=Zr(r,t,e,c,a),d=Yr(c,e,i,a,s);return{url:u,method:c,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);return await this.applyGlobals(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=I(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===l.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(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=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 w,this.cache=new pt(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(St.WarpExecutable(t,e||"",n))||[];return $(i)}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),c=new N(this.config,p,this.adapters),o=await c.apply(t,i),u=E(o,e),{action:d,index:h}=R(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let b=A.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,H=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:H;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let F=this.getPreparedArgs(u,A);F=F.map(P=>c.applyInputs(P,A,this.serializer,f));let V=A.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,O=V?.split(l.ArgParamsSeparator)[1]||T||"0",Y=c.applyInputs(O,A,this.serializer,f),Be=BigInt(Y),$e=A.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Ve=[...("transfers"in u?u.transfers:[])||[],...$e||[]].map(P=>{let Pt=c.applyInputs(P,A,this.serializer,f),Ue=Pt.startsWith(`asset${l.ArgParamsSeparator}`)?Pt:`asset${l.ArgParamsSeparator}${Pt}`;return this.serializer.stringToNative(Ue)[1]}),Oe=A.find(P=>P.input.position==="data")?.value,He="data"in u?u.data||"":null,ie=Oe||He||null,Fe=ie?c.applyInputs(ie,A,this.serializer,f):null,ae={adapter:p,warp:o,chain:s,action:e,destination:x,args:F,value:Be,transfers:Ve,data:Fe,resolvedInputs:A};return this.cache.set(St.WarpExecutable(this.config.env,o.meta?.hash||"",e),ae.resolvedInputs,Zt.OneWeek),ae}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===l.Source.UserWallet){let v=I(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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 c=et(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=et(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=nt(t,this.serializer,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Wt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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 u=et(p,o.decimals);return _t({...o,amount:u})}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,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 lt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=R(t);for(let g=1;g<=t.actions.length;g++){let y=E(t,g);if(!mt(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:b}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),b&&g===h+1&&b.resolvedInputs&&(p=$(b.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return{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):Et.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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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(!mt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:I(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c.tx);return u.next=z(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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=I(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:c}=await it(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await Ne(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let g=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Gt(g,c,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await it(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=$(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=I(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=$(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=$(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:y}}let p=this.factory.getSerializer(),c=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:F})=>{if(F&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[T,O]=p.stringToNative(F);if(T==="string")f[V]=String(O);else if(T==="bool")f[V]=!!O;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let Y=Number(O);f[V]=(Number.isInteger(Y),Y)}else f[V]=O}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:H}=await it(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,H,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let p=z(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:vt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),c=new N(this.config,p,this.adapters),o=await c.apply(t,a),u=E(o,n),{action:d}=R(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let T=this.factory.getStringTypedInputs(e,i),O=await this.factory.getResolvedInputs(s.name,e,T,c,a.queries);f=await this.factory.getModifiedInputs(O)}let v=qt(u.prompt,this.config.platform),A=c.applyInputs(v,f,this.factory.getSerializer(),y),b=$(f),H=I(this.config,s.name),x=this.factory.getSerializer(),{values:F,output:V}=await Mt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:H,txHash:null,tx:null,next:z(this.config,this.adapters,o,n,V),values:F,output:V,messages:vt(o,V,this.config),destination:null,resolvedInputs:b}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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),c=W(p.name,this.adapters),o=new N(this.config,c,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Vt(e.when,f);return Ot(v)}};var ut=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 dt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Ht(t):Ft(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(tn(p,u.chainInfo.name,c,i.identifier),p.meta.query=d?Ut(d):null),!p)return n;let h=p.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new N(this.config,g,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},tn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?yt(t,"alias",e.alias):yt(t,"hash",e?.hash??n))};var re=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new lt(this.config,this.chains,t)}async detectWarp(t,e){return new dt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=B(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(!I(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??R(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=z(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 G(this.config,this.chains)}get index(){return new ut(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 rt(t,this.config)}};var ne=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()]))}};0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,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,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,replacePlaceholders,replacePlaceholdersInWhenExpression,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 tr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},he=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>he(r.user?.wallets?.[t]||null),me=r=>r?typeof r=="string"?r:r.privateKey||null:null,ye=r=>r?typeof r=="string"?r:r.mnemonic||null:null,We=r=>r?typeof r=="string"?r:r.externalId||null:null,er=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,rr=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,ve=(r,t)=>We(r.user?.wallets?.[t]||null)?.trim()||null,nr=(r,t)=>{let e=ve(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},ir=r=>typeof r=="string",ar=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Ae=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ce=(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`)},sr=(r,t=24)=>{let e=Ae(r);return Ce(e,t),e};var xe=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(xe||{}),cr=["ethereum","base","arbitrum","polygon","somnia"],lr=["coinbase","privy","gaupa"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},Bt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 yr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var vr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Ar=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Cr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var gt=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}},ht=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"}`)}}},D=null;function $t(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new gt,D;if(typeof process<"u"&&process.versions?.node)return D=new ht,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function wr(r){D=r}async function Ot(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||$t()).getRandomBytes(r)}function we(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 Ir(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 Vt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ot(r/2,t);return we(e)}async function Sr(){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 Ot(16),r.randomBytes=!0}catch{}return r}function Pr(){return $t()}var Er=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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],E=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},mt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},et=(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)},Ht=(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},L=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Ft=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ut=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 $r={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"},rt=(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""},Or=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Vr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Dr=(r,t)=>!r||!t?!1:J(r)===J(t),yt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=Dt(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=Ie(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},Ie=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Se=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Dt=r=>{let t=Se(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Dt(a);return[i,...s]},Lt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},jt=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},Mt=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},Lr=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()},jr=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 Wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},zr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=Wt(r)[0];return t.has(e)};var vt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Pe from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new Pe({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 be="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(be))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:At(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:At(t,v,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=p;for(let{regex:b,field:O}of g){let x=O?Te(f,O):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:At(t,A,r)}}).filter(f=>f!==null)},At=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Te=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var j=class j{static debug(...t){j.isTestEnv||console.debug(...t)}static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;function Ee(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function qt(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]=qt(e[n],t[n]):e[n]=t[n]}),e}function Re(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Re(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=Ee(n.input.position,i,a);e=qt(e,s)}else e[i]=a}),e}function nt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let c=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[c]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${c}.token`]=d,i[`${c}.identifier`]=d,i[`${c}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var zt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=$e(p);if(c!==null&&c!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},it=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:o,output:u}=zt(r,e,p);return{values:{string:c,native:o,mapped:K(n,i)},output:await kt(r,u,t,e,n,i,a)}},kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Ne(p,r,n,i,a),p=await Be(r,p,e,i,a,s.transform?.runner||null),p},Ne=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Be=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(l.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 c={...s,out:e,inputs:nt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,c),c[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,c[o]=null}return s},Gt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=zt(r,e,s),u=await kt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:K(n,i)},output:u}},$e=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 yn=(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 Oe(r,t,e,n=5){let i=await Vt(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 Ct(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Oe(r,i,e,5)}function xt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Cn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Ct(r,e,n),p=await t(i);return xt(r,p,a,s)}function xn(r){let t=new Date(r).getTime();return Date.now()<t}function wn(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 Ve=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",He=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),_t=(r,t=24)=>{let e=He(r);return e?e.slice(0,t):"action"},Jt=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)},Fe=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()}},Sn=(r,t,e)=>{let n=_t((e||t||"").trim()||"action"),i=`${r.type}|${Fe(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Jt(i);return`private_src_${n}_${a}`},Ue=r=>{let t=Ve(r),e=_t(t),n=Jt(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Pn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ue(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},bn=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function En(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 Nn(r,t,e){return null}import{x402Client as Qt}from"@x402/core/client";import{x402HTTPClient as Kt}from"@x402/core/http";async function Xt(r,t,e,n,i){let a=await De(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var De=async(r,t)=>{let e=await Le(r),i=new Kt(new Qt).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Qt,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Kt(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Le=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[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(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 jn=r=>new w().nativeToString(m.String,r),Mn=r=>new w().nativeToString(m.Uint8,r),qn=r=>new w().nativeToString(m.Uint16,r),zn=r=>new w().nativeToString(m.Uint32,r),kn=r=>new w().nativeToString(m.Uint64,r),Gn=r=>new w().nativeToString(m.Biguint,r),_n=r=>new w().nativeToString(m.Bool,r),Jn=r=>new w().nativeToString(m.Address,r),Zt=r=>new w().nativeToString(m.Asset,r),Qn=r=>new w().nativeToString(m.Hex,r),Kn=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Xn=(...r)=>new w().nativeToString(m.Tuple,r),Zn=r=>new w().nativeToString(m.Struct,r),Yn=r=>new w().nativeToString(m.Vector,r);import je from"ajv";var Yt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new je,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Me from"ajv";var at=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(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}}validatePrimaryAction(t){try{let{action:e}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Me({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 te=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Ht(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 at(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as It,mkdirSync as qe,readdirSync as ze,readFileSync as ke,unlinkSync as St,writeFileSync as Ge}from"fs";import{join as ee,resolve as re}from"path";var wt="$bigint:",st=(r,t)=>typeof t=="bigint"?wt+t.toString():t,k=(r,t)=>typeof t=="string"&&t.startsWith(wt)?BigInt(t.slice(wt.length)):t;var ot=class{constructor(t,e){let n=e?.path;this.cacheDir=n?re(n):re(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){It(this.cacheDir)||qe(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ee(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!It(e))return null;let n=ke(e,"utf-8"),i=JSON.parse(n,k);return Date.now()>i.expiresAt?(St(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);Ge(a,JSON.stringify(i,st),"utf-8")}forget(t){try{let e=this.getFilePath(t);It(e)&&St(e)}catch{}}clear(){try{ze(this.cacheDir).forEach(e=>{e.endsWith(".json")&&St(ee(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,k);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,st))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var Z=F;import{readFileSync as _e}from"fs";import{resolve as ne}from"path";var pt=class{constructor(t,e){let n=e?.path?ne(e.path):ne(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=_e(t,"utf-8");return new Map(Object.entries(JSON.parse(e,k)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}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},Pt={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}`},ct=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new pt(t,e):e?.type==="filesystem"?new ot(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},bt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Tt=(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)},Et=r=>{try{return JSON.parse(r)}catch{return null}},Je=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:c,nonce:o,expiresAt:u}=await Ct(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(xt(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=Tt(e.resolvedInputs,Y.Headers,i);if(p){let c=Et(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Qe=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===bt.Get){let s=Tt(e.resolvedInputs,Y.Queries,i);if(s){let p=Et(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Ke=(r,t,e,n,i)=>{if(r===bt.Get)return;let a=Tt(t.resolvedInputs,Y.Payload,n);if(a&&Et(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},ae=async(r,t,e,n,i,a,s,p)=>{let c=t.method||bt.Get,o=await Je(r,t,e,n,a,p),u=Qe(r,t,e,c,a),d=Ke(c,e,i,a,s);return{url:u,method:c,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);return await this.applyGlobals(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=S(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===l.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(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return L(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=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 w,this.cache=new ct(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(Pt.WarpExecutable(t,e||"",n))||[];return $(i)}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=W(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,i),u=T(o,e),{action:d,index:h}=E(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let b=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:O;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,A);N=N.map(I=>c.applyInputs(I,A,this.serializer,f));let V=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,H=V?.split(l.ArgParamsSeparator)[1]||P||"0",_=c.applyInputs(H,A,this.serializer,f),pe=BigInt(_),ce=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),le=[...("transfers"in u?u.transfers:[])||[],...ce||[]].map(I=>{let ft=c.applyInputs(I,A,this.serializer,f),ge=ft.startsWith(`asset${l.ArgParamsSeparator}`)?ft:`asset${l.ArgParamsSeparator}${ft}`;return this.serializer.stringToNative(ge)[1]}),ue=A.find(I=>I.input.position==="data")?.value,de="data"in u?u.data||"":null,Rt=ue||de||null,fe=Rt?c.applyInputs(Rt,A,this.serializer,f):null,Nt={adapter:p,warp:o,chain:s,action:e,destination:x,args:N,value:pe,transfers:le,data:fe,resolvedInputs:A};return this.cache.set(Pt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Nt.resolvedInputs,ie.OneWeek),Nt}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===l.Source.UserWallet){let v=S(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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 c=et(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=et(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=nt(t,this.serializer,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Wt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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 u=et(p,o.decimals);return Zt({...o,amount:u})}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,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 lt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=E(t);for(let g=1;g<=t.actions.length;g++){let y=T(t,g);if(!mt(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:b}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),b&&g===h+1&&b.resolvedInputs&&(p=$(b.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return{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):Bt.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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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(!mt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c.tx);return u.next=z(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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=S(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:c}=await it(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}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:c,method:o,headers:u,body:d}=await ae(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let g=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Xt(g,c,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await it(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=$(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let g=$(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=$(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:y}}let p=this.factory.getSerializer(),c=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[P,H]=p.stringToNative(N);if(P==="string")f[V]=String(H);else if(P==="bool")f[V]=!!H;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let _=Number(H);f[V]=(Number.isInteger(_),_)}else f[V]=H}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:O}=await it(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,O,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let p=z(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:vt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,a),u=T(o,n),{action:d}=E(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let V=this.factory.getStringTypedInputs(e,i),P=await this.factory.getResolvedInputs(s.name,e,V,c,a.queries);f=await this.factory.getModifiedInputs(P)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),b=S(this.config,s.name),O=this.factory.getSerializer(),{values:x,output:N}=await Gt(o,v,n,f,O,this.config);return{status:"success",warp:o,action:n,user:b,txHash:null,tx:null,next:z(this.config,this.adapters,o,n,N),values:x,output:N,messages:vt(o,N,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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),c=W(p.name,this.adapters),o=new R(this.config,c,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Ft(e.when,f);return Ut(v)}};var ut=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 dt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Lt(t):jt(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Xe(p,u.chainInfo.name,c,i.identifier),p.meta.query=d?Mt(d):null),!p)return n;let h=p.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new R(this.config,g,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Xe=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?yt(t,"alias",e.alias):yt(t,"hash",e?.hash??n))};var se=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new lt(this.config,this.chains,t)}async detectWarp(t,e){return new dt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=B(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(!S(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(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=z(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 G(this.config,this.chains)}get index(){return new ut(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 rt(t,this.config)}};var oe=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()]))}};export{gt as BrowserCryptoProvider,lr as CLOUD_WALLET_PROVIDERS,ie as CacheTtl,cr as EvmWalletChainNames,ht as NodeCryptoProvider,$r as WARP_LANGUAGES,Yt as WarpBrandBuilder,te as WarpBuilder,ct as WarpCache,Pt as WarpCacheKey,xe as WarpChainName,se as WarpClient,U as WarpConfig,l as WarpConstants,lt as WarpExecutor,G as WarpFactory,ut as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,dt as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,oe as WarpTypeRegistry,at as WarpValidator,Jn as address,vt as applyOutputToMessages,Zt as asset,Gn as biguint,_n as bool,Ue as buildGeneratedFallbackWarpIdentifier,Sn as buildGeneratedSourceWarpIdentifier,nt as buildInputsContext,K as buildMappedOutput,Ee as buildNestedPayload,Ir as bytesToBase64,we as bytesToHex,J as cleanWarpIdentifier,xt as createAuthHeaders,Ct as createAuthMessage,Pr as createCryptoProvider,Nn as createDefaultWalletProvider,Cn as createHttpAuthHeaders,Oe as createSignableMessage,Vr as createWarpI18nText,yt as createWarpIdentifier,kt as evaluateOutputCommon,Ut as evaluateWhenCondition,it as extractCollectOutput,Q as extractIdentifierInfoFromUrl,Gt as extractPromptOutput,jt as extractQueryStringFromIdentifier,Lt as extractQueryStringFromUrl,$ as extractResolvedInputValues,Er as extractWarpSecrets,W as findWarpAdapterForChain,$t as getCryptoProvider,yr as getEventNameFromWarp,Ve as getGeneratedSourceWarpName,tt as getLatestProtocolIdentifier,z as getNextInfo,yn as getProviderConfig,Ot as getRandomBytes,Vt as getRandomHex,tr as getWalletFromConfigOrFail,T as getWarpActionByIndex,vr as getWarpBrandLogoUrl,Ar as getWarpChainAssetLogoUrl,Cr as getWarpChainInfoLogoUrl,jr as getWarpIdentifierWithQuery,B as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,he as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,We as getWarpWalletExternalId,ve as getWarpWalletExternalIdFromConfig,nr as getWarpWalletExternalIdFromConfigOrFail,ye as getWarpWalletMnemonic,rr as getWarpWalletMnemonicFromConfig,me as getWarpWalletPrivateKey,er as getWarpWalletPrivateKeyFromConfig,Xt as handleX402Payment,zr as hasInputPrefix,Qn as hex,En as initializeWalletCache,Dr as isEqualWarpIdentifier,bn as isGeneratedSourcePrivateIdentifier,mt as isWarpActionAutoExecute,Or as isWarpI18nText,ir as isWarpWalletReadOnly,qt as mergeNestedPayload,sr as normalizeAndValidateMnemonic,Ae as normalizeMnemonic,Kn as option,$e as parseOutputOutIndex,wn as parseSignedMessage,Mt as parseWarpQueryStringToObject,Lr as removeWarpChainPrefix,L as replacePlaceholders,Ft as replacePlaceholdersInWhenExpression,rt as resolveWarpText,Bt as safeWindow,wr as setCryptoProvider,ar as setWarpWalletInConfig,et as shiftBigintBy,Wt as splitInput,Pn as stampGeneratedWarpMeta,jn as string,Zn as struct,Sr as testCryptoAvailability,Re as toInputPayloadValue,Ht as toPreviewText,Xn as tuple,qn as uint16,zn as uint32,kn as uint64,Mn as uint8,Ce as validateMnemonicLength,xn as validateSignedMessage,Yn as vector,gr as withAdapterFallback};
1
+ var ar=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},We=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>We(r.user?.wallets?.[t]||null),ve=r=>r?typeof r=="string"?r:r.privateKey||null:null,Ae=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ce=r=>r?typeof r=="string"?r:r.externalId||null:null,sr=(r,t)=>ve(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>Ae(r.user?.wallets?.[t]||null)?.trim()||null,xe=(r,t)=>Ce(r.user?.wallets?.[t]||null)?.trim()||null,pr=(r,t)=>{let e=xe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},cr=r=>typeof r=="string",lr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},we=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ie=(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`)},ur=(r,t=24)=>{let e=we(r);return Ie(e,t),e};var Se=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(Se||{}),Bt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Bt||{}),$t=Object.values(Bt),gr=["ethereum","base","arbitrum","polygon","somnia"],hr=["coinbase","privy","gaupa"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},Vt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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",l.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 vr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var xr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Ir=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Sr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Pr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var gt=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}},ht=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"}`)}}},D=null;function Ot(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new gt,D;if(typeof process<"u"&&process.versions?.node)return D=new ht,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function br(r){D=r}async function Ht(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Ot()).getRandomBytes(r)}function Pe(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 Er(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 Ft(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ht(r/2,t);return Pe(e)}async function Rr(){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 Ht(16),r.randomBytes=!0}catch{}return r}function Nr(){return Ot()}var Vr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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}`)},b=(r,t)=>r?.actions[t-1],E=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},mt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},et=(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)},Ut=(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},L=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Dt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Lt=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 Ur={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"},rt=(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""},Dr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Lr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,zr=(r,t)=>!r||!t?!1:J(r)===J(t),yt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},$=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=jt(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.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,c,o]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:c,identifier:u,identifierBase:o}}}if(s.length===2){let[p,c]=s;if(p===l.IdentifierType.Alias||p===l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:p,identifier:o,identifierBase:c}}}if(s.length===2){let[p,c]=s;if(p!==l.IdentifierType.Alias&&p!==l.IdentifierType.Hash){let o=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=Te(c,p)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return $(a,t)},Te=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,be=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},jt=r=>{let t=be(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=jt(a);return[i,...s]},Mt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.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},zt=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},kr=(r,t)=>{let e=$(r,t);return(e?e.identifierBase:J(r)).trim()},Gr=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 Wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Qr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=Wt(r)[0];return t.has(e)};var vt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Ee from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=$(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 c=W(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new Ee({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 Re="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Re))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:At(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:At(t,v,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=p;for(let{regex:T,field:O}of g){let x=O?Ne(f,O):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:At(t,A,r)}}).filter(f=>f!==null)},At=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n,e.defaultChain)||{chain:l.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 c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Ne=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var j=class j{static debug(...t){j.isTestEnv||console.debug(...t)}static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;function Be(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function kt(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]=kt(e[n],t[n]):e[n]=t[n]}),e}function $e(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 V(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=$e(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=Be(n.input.position,i,a);e=kt(e,s)}else e[i]=a}),e}function nt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let c=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[c]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${c}.token`]=d,i[`${c}.identifier`]=d,i[`${c}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Gt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(l.Transform.Prefix))continue;let c=Fe(p);if(c!==null&&c!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},it=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:o,output:u}=Gt(r,e,p);return{values:{string:c,native:o,mapped:K(n,i)},output:await _t(r,u,t,e,n,i,a)}},_t=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Ve(p,r,n,i,a),p=await Oe(r,p,e,i,a,s.transform?.runner||null),p},Ve=(r,t,e,n,i)=>{let a={...r},s=b(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Oe=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(l.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 c={...s,out:He(e),inputs:nt(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,c),c[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,c[o]=null}return s},He=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},Jt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:c,output:o}=Gt(r,e,s),u=await _t(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:c,mapped:K(n,i)},output:u}},Fe=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 Ue=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:$t.some(t=>t in r),Qt=(r,t)=>{if(!Ue(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 Sn=(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 De(r,t,e,n=5){let i=await Ft(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 Ct(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return De(r,i,e,5)}function xt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function En(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Ct(r,e,n),p=await t(i);return xt(r,p,a,s)}function Rn(r){let t=new Date(r).getTime();return Date.now()<t}function Nn(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 Le=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",je=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Kt=(r,t=24)=>{let e=je(r);return e?e.slice(0,t):"action"},Xt=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)},Me=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()}},$n=(r,t,e)=>{let n=Kt((e||t||"").trim()||"action"),i=`${r.type}|${Me(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Xt(i);return`private_src_${n}_${a}`},qe=r=>{let t=Le(r),e=Kt(t),n=Xt(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Vn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||qe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},On=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Fn(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 Dn(r,t,e){return null}import{x402Client as Zt}from"@x402/core/client";import{x402HTTPClient as Yt}from"@x402/core/http";async function te(r,t,e,n,i){let a=await ze(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var ze=async(r,t)=>{let e=await ke(r),i=new Yt(new Zt).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Zt,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Yt(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},ke=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[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(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[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(l.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,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 Qn=r=>new w().nativeToString(m.String,r),Kn=r=>new w().nativeToString(m.Uint8,r),Xn=r=>new w().nativeToString(m.Uint16,r),Zn=r=>new w().nativeToString(m.Uint32,r),Yn=r=>new w().nativeToString(m.Uint64,r),ti=r=>new w().nativeToString(m.Biguint,r),ei=r=>new w().nativeToString(m.Bool,r),ri=r=>new w().nativeToString(m.Address,r),ee=r=>new w().nativeToString(m.Asset,r),ni=r=>new w().nativeToString(m.Hex,r),ii=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},ai=(...r)=>new w().nativeToString(m.Tuple,r),si=r=>new w().nativeToString(m.Struct,r),oi=r=>new w().nativeToString(m.Vector,r);import Ge from"ajv";var re=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Ge,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import _e from"ajv";var at=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(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}}validatePrimaryAction(t){try{let{action:e}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new _e({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 ne=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Ut(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 at(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};import{existsSync as It,mkdirSync as Je,readdirSync as Qe,readFileSync as Ke,unlinkSync as St,writeFileSync as Xe}from"fs";import{join as ie,resolve as ae}from"path";var wt="$bigint:",st=(r,t)=>typeof t=="bigint"?wt+t.toString():t,k=(r,t)=>typeof t=="string"&&t.startsWith(wt)?BigInt(t.slice(wt.length)):t;var ot=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ae(n):ae(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){It(this.cacheDir)||Je(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ie(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!It(e))return null;let n=Ke(e,"utf-8"),i=JSON.parse(n,k);return Date.now()>i.expiresAt?(St(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);Xe(a,JSON.stringify(i,st),"utf-8")}forget(t){try{let e=this.getFilePath(t);It(e)&&St(e)}catch{}}clear(){try{Qe(this.cacheDir).forEach(e=>{e.endsWith(".json")&&St(ie(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,k);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,st))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var Z=F;import{readFileSync as Ze}from"fs";import{resolve as se}from"path";var pt=class{constructor(t,e){let n=e?.path?se(e.path):se(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=Ze(t,"utf-8");return new Map(Object.entries(JSON.parse(e,k)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var oe={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Pt={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}`},ct=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new pt(t,e):e?.type==="filesystem"?new ot(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Tt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},bt=(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)},Et=r=>{try{return JSON.parse(r)}catch{return null}},Ye=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:c,nonce:o,expiresAt:u}=await Ct(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(xt(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=bt(e.resolvedInputs,Y.Headers,i);if(p){let c=Et(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},tr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Tt.Get){let s=bt(e.resolvedInputs,Y.Queries,i);if(s){let p=Et(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},er=(r,t,e,n,i)=>{if(r===Tt.Get)return;let a=bt(t.resolvedInputs,Y.Payload,n);if(a&&Et(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},pe=async(r,t,e,n,i,a,s,p)=>{let c=t.method||Tt.Get,o=await Ye(r,t,e,n,a,p),u=tr(r,t,e,c,a),d=er(c,e,i,a,s);return{url:u,method:c,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);return await this.applyGlobals(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=S(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(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===l.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(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return L(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.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 c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=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 w,this.cache=new ct(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(Pt.WarpExecutable(t,e||"",n))||[];return V(i)}async createExecutable(t,e,n,i={}){let a=b(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,i),u=b(o,e),{action:d,index:h}=E(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let T=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:O;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let H=this.getPreparedArgs(u,A);H=H.map(I=>c.applyInputs(I,A,this.serializer,f));let N=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,B=N?.split(l.ArgParamsSeparator)[1]||P||"0",_=c.applyInputs(B,A,this.serializer,f),ue=BigInt(_),de=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),fe=[...("transfers"in u?u.transfers:[])||[],...de||[]].map(I=>{let ft=c.applyInputs(I,A,this.serializer,f),ye=ft.startsWith(`asset${l.ArgParamsSeparator}`)?ft:`asset${l.ArgParamsSeparator}${ft}`;return this.serializer.stringToNative(ye)[1]}),ge=A.find(I=>I.input.position==="data")?.value,he="data"in u?u.data||"":null,Rt=ge||he||null,me=Rt?c.applyInputs(Rt,A,this.serializer,f):null,Nt={adapter:p,warp:o,chain:s,action:e,destination:x,args:H,value:ue,transfers:fe,data:me,resolvedInputs:A};return this.cache.set(Pt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Nt.resolvedInputs,oe.OneWeek),Nt}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(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===l.Source.UserWallet){let v=S(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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 c=et(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=et(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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=nt(t,this.serializer,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Wt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)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 u=et(p,o.decimals);return ee({...o,amount:u})}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,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,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(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 lt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=E(t);for(let g=1;g<=t.actions.length;g++){let y=b(t,g);if(!mt(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:T}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),T&&g===h+1&&T.resolvedInputs&&(p=V(T.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=b(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):Vt.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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,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 u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,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(!mt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c.tx);return u.next=z(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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=S(this.config,t.chain.name),i=b(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:c}=await it(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}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:c,method:o,headers:u,body:d}=await pe(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let g=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await te(g,c,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await it(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=V(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let g=V(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let y=V(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:y}}let p=this.factory.getSerializer(),c=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:H})=>{if(H&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let N=x.position.replace("payload:",""),[P,B]=p.stringToNative(H);if(P==="string")f[N]=String(B);else if(P==="bool")f[N]=!!B;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let _=Number(B);f[N]=(Number.isInteger(_),_)}else f[N]=B}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:O}=await it(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,O,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=V(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:y}}}buildCollectResult(t,e,n,i,a,s){let p=z(this.config,this.adapters,t.warp,t.action,a),c=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:vt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,a),u=b(o,n),{action:d}=E(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let P=this.factory.getStringTypedInputs(e,i),B=await this.factory.getResolvedInputs(s.name,e,P,c,a.queries);f=await this.factory.getModifiedInputs(B)}let v=Qt(u.prompt,this.config.platform),A=c.applyInputs(v,f,this.factory.getSerializer(),y),T=V(f),O=S(this.config,s.name),x=this.factory.getSerializer(),{values:H,output:N}=await Jt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:O,txHash:null,tx:null,next:z(this.config,this.adapters,o,n,N),values:H,output:N,messages:vt(o,N,this.config),destination:null,resolvedInputs:T}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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),c=W(p.name,this.adapters),o=new R(this.config,c,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Dt(e.when,f);return Lt(v)}};var ut=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 dt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(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,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):$(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Mt(t):qt(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(rr(p,u.chainInfo.name,c,i.identifier),p.meta.query=d?zt(d):null),!p)return n;let h=p.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new R(this.config,g,this.adapters).apply(p);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},rr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?yt(t,"alias",e.alias):yt(t,"hash",e?.hash??n))};var ce=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new lt(this.config,this.chains,t)}async detectWarp(t,e){return new dt(this.config,this.chains).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 y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(p,y)},resolvedInputs:h}}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=$(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(!S(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(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=z(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 G(this.config,this.chains)}get index(){return new ut(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 rt(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()]))}};export{gt as BrowserCryptoProvider,hr as CLOUD_WALLET_PROVIDERS,oe as CacheTtl,gr as EvmWalletChainNames,ht as NodeCryptoProvider,Ur as WARP_LANGUAGES,re as WarpBrandBuilder,ne as WarpBuilder,ct as WarpCache,Pt as WarpCacheKey,Se as WarpChainName,ce as WarpClient,U as WarpConfig,l as WarpConstants,lt as WarpExecutor,G as WarpFactory,ut as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,dt as WarpLinkDetecter,C as WarpLogger,Bt as WarpPlatformName,$t as WarpPlatforms,M as WarpProtocolVersions,w as WarpSerializer,le as WarpTypeRegistry,at as WarpValidator,ri as address,vt as applyOutputToMessages,ee as asset,ti as biguint,ei as bool,qe as buildGeneratedFallbackWarpIdentifier,$n as buildGeneratedSourceWarpIdentifier,nt as buildInputsContext,K as buildMappedOutput,Be as buildNestedPayload,Er as bytesToBase64,Pe as bytesToHex,J as cleanWarpIdentifier,xt as createAuthHeaders,Ct as createAuthMessage,Nr as createCryptoProvider,Dn as createDefaultWalletProvider,En as createHttpAuthHeaders,De as createSignableMessage,Lr as createWarpI18nText,yt as createWarpIdentifier,_t as evaluateOutputCommon,Lt as evaluateWhenCondition,it as extractCollectOutput,Q as extractIdentifierInfoFromUrl,Jt as extractPromptOutput,qt as extractQueryStringFromIdentifier,Mt as extractQueryStringFromUrl,V as extractResolvedInputValues,Vr as extractWarpSecrets,W as findWarpAdapterForChain,Ot as getCryptoProvider,xr as getEventNameFromWarp,Le as getGeneratedSourceWarpName,tt as getLatestProtocolIdentifier,z as getNextInfo,Sn as getProviderConfig,Ht as getRandomBytes,Ft as getRandomHex,ar as getWalletFromConfigOrFail,b as getWarpActionByIndex,Ir as getWarpBrandLogoUrl,Sr as getWarpChainAssetLogoUrl,Pr as getWarpChainInfoLogoUrl,Gr as getWarpIdentifierWithQuery,$ as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,We as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,Ce as getWarpWalletExternalId,xe as getWarpWalletExternalIdFromConfig,pr as getWarpWalletExternalIdFromConfigOrFail,Ae as getWarpWalletMnemonic,or as getWarpWalletMnemonicFromConfig,ve as getWarpWalletPrivateKey,sr as getWarpWalletPrivateKeyFromConfig,te as handleX402Payment,Qr as hasInputPrefix,ni as hex,Fn as initializeWalletCache,zr as isEqualWarpIdentifier,On as isGeneratedSourcePrivateIdentifier,Ue as isPlatformValue,mt as isWarpActionAutoExecute,Dr as isWarpI18nText,cr as isWarpWalletReadOnly,kt as mergeNestedPayload,ur as normalizeAndValidateMnemonic,we as normalizeMnemonic,ii as option,Fe as parseOutputOutIndex,Nn as parseSignedMessage,zt as parseWarpQueryStringToObject,kr as removeWarpChainPrefix,L as replacePlaceholders,Dt as replacePlaceholdersInWhenExpression,Qt as resolvePlatformValue,rt as resolveWarpText,Vt as safeWindow,br as setCryptoProvider,lr as setWarpWalletInConfig,et as shiftBigintBy,Wt as splitInput,Vn as stampGeneratedWarpMeta,Qn as string,si as struct,Rr as testCryptoAvailability,$e as toInputPayloadValue,Ut as toPreviewText,ai as tuple,Xn as uint16,Zn as uint32,Yn as uint64,Kn as uint8,Ie as validateMnemonicLength,Rn as validateSignedMessage,oi as vector,vr as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "3.4.1",
3
+ "version": "3.5.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",