@joai/warps 4.31.1 → 4.32.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 +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -458,6 +458,9 @@ declare const WarpConstants: {
|
|
|
458
458
|
ArgCompositeSeparator: string;
|
|
459
459
|
ArgListSeparator: string;
|
|
460
460
|
ArgStructSeparator: string;
|
|
461
|
+
Append: {
|
|
462
|
+
Prefix: string;
|
|
463
|
+
};
|
|
461
464
|
Transform: {
|
|
462
465
|
Prefix: string;
|
|
463
466
|
};
|
|
@@ -628,6 +631,7 @@ type WarpInlineAction = {
|
|
|
628
631
|
auto?: boolean;
|
|
629
632
|
silent?: boolean;
|
|
630
633
|
when?: string;
|
|
634
|
+
output?: Record<string, string>;
|
|
631
635
|
};
|
|
632
636
|
type WarpTransferAction = {
|
|
633
637
|
type: WarpActionType;
|
|
@@ -1002,6 +1006,7 @@ declare const extractPromptOutput: (warp: Warp, promptValue: string, actionIndex
|
|
|
1002
1006
|
};
|
|
1003
1007
|
output: WarpExecutionOutput;
|
|
1004
1008
|
}>;
|
|
1009
|
+
declare const extractInlineOutput: (action: WarpInlineAction, result: WarpActionExecutionResult, envs: Record<string, any> | undefined) => WarpExecutionOutput;
|
|
1005
1010
|
declare const parseOutputOutIndex: (outputPath: string) => number | null;
|
|
1006
1011
|
|
|
1007
1012
|
declare const isPlatformValue: <T>(value: WarpPlatformValue<T>) => value is Partial<Record<WarpPlatformName, T>>;
|
|
@@ -1548,4 +1553,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
|
|
|
1548
1553
|
*/
|
|
1549
1554
|
declare function resolvePath(obj: unknown, path: string): unknown;
|
|
1550
1555
|
|
|
1551
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierInfo, type WarpIdentifierType, WarpIndex, type WarpInlineAction, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpNextEntry, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, type WarpSection, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolveNextStrings, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1556
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierInfo, type WarpIdentifierType, WarpIndex, type WarpInlineAction, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpNextEntry, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, type WarpSection, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractInlineOutput, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolveNextStrings, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.d.ts
CHANGED
|
@@ -458,6 +458,9 @@ declare const WarpConstants: {
|
|
|
458
458
|
ArgCompositeSeparator: string;
|
|
459
459
|
ArgListSeparator: string;
|
|
460
460
|
ArgStructSeparator: string;
|
|
461
|
+
Append: {
|
|
462
|
+
Prefix: string;
|
|
463
|
+
};
|
|
461
464
|
Transform: {
|
|
462
465
|
Prefix: string;
|
|
463
466
|
};
|
|
@@ -628,6 +631,7 @@ type WarpInlineAction = {
|
|
|
628
631
|
auto?: boolean;
|
|
629
632
|
silent?: boolean;
|
|
630
633
|
when?: string;
|
|
634
|
+
output?: Record<string, string>;
|
|
631
635
|
};
|
|
632
636
|
type WarpTransferAction = {
|
|
633
637
|
type: WarpActionType;
|
|
@@ -1002,6 +1006,7 @@ declare const extractPromptOutput: (warp: Warp, promptValue: string, actionIndex
|
|
|
1002
1006
|
};
|
|
1003
1007
|
output: WarpExecutionOutput;
|
|
1004
1008
|
}>;
|
|
1009
|
+
declare const extractInlineOutput: (action: WarpInlineAction, result: WarpActionExecutionResult, envs: Record<string, any> | undefined) => WarpExecutionOutput;
|
|
1005
1010
|
declare const parseOutputOutIndex: (outputPath: string) => number | null;
|
|
1006
1011
|
|
|
1007
1012
|
declare const isPlatformValue: <T>(value: WarpPlatformValue<T>) => value is Partial<Record<WarpPlatformName, T>>;
|
|
@@ -1548,4 +1553,4 @@ declare function resolveInputs(trigger: WebhookTrigger, payload: unknown): Recor
|
|
|
1548
1553
|
*/
|
|
1549
1554
|
declare function resolvePath(obj: unknown, path: string): unknown;
|
|
1550
1555
|
|
|
1551
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierInfo, type WarpIdentifierType, WarpIndex, type WarpInlineAction, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpNextEntry, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, type WarpSection, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolveNextStrings, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1556
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type ContractDeployParams, type ContractFlags, type ContractUpgradeParams, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, MultiversxWalletChainNames, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, WarpAssets, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandSiteConfig, type WarpBrandSiteRoute, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheAdapter, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetNftMetadata, type WarpChainAssetType, type WarpChainAssetValue, WarpChainDisplayNames, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainLogos, WarpChainName, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, type WarpComputeAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierInfo, type WarpIdentifierType, WarpIndex, type WarpInlineAction, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpLoopAction, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpMountAction, type WarpNativeValue, type WarpNextConfig, type WarpNextEntry, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, type WarpSection, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractInlineOutput, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getChainDisplayName, getChainLogo, getCryptoProvider, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getMppFetch, getNextInfo, getNextInfoForStatus, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpInputAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, matchesTrigger, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveInputs, resolveNextString, resolveNextStrings, resolvePath, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Xe=Object.create;var At=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var rr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},fe=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ye(t))!er.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ze(t,i))||n.enumerable});return r};var K=(r,t,e)=>(e=r!=null?Xe(tr(r)):{},fe(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),nr=r=>fe(At({},"__esModule",{value:!0}),r);var Nn={};rr(Nn,{BrowserCryptoProvider:()=>bt,CLOUD_WALLET_PROVIDERS:()=>gr,CacheTtl:()=>ie,EvmWalletChainNames:()=>dr,MultiversxWalletChainNames:()=>fr,NodeCryptoProvider:()=>wt,WARP_LANGUAGES:()=>Tr,WarpAssets:()=>I,WarpBrandBuilder:()=>ee,WarpBuilder:()=>ut,WarpCache:()=>gt,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>be,WarpChainName:()=>Ae,WarpChainResolver:()=>rt,WarpClient:()=>pe,WarpCompositeResolver:()=>nt,WarpConfig:()=>D,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>Q,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>$,WarpLinkBuilder:()=>G,WarpLinkDetecter:()=>xt,WarpLogger:()=>b,WarpPlatformName:()=>Vt,WarpPlatforms:()=>Ht,WarpProtocolVersions:()=>q,WarpSerializer:()=>w,WarpTypeRegistry:()=>le,WarpValidator:()=>ct,address:()=>un,applyOutputToMessages:()=>Tt,asset:()=>te,biguint:()=>ln,bool:()=>cn,buildGeneratedFallbackWarpIdentifier:()=>Ve,buildGeneratedSourceWarpIdentifier:()=>Xr,buildInputsContext:()=>lt,buildMappedOutput:()=>J,buildNestedPayload:()=>Te,bytesToBase64:()=>Cr,bytesToHex:()=>we,checkWarpAssetBalance:()=>rn,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>$t,createAuthMessage:()=>Rt,createCryptoProvider:()=>wr,createDefaultWalletProvider:()=>en,createHttpAuthHeaders:()=>Gr,createSignableMessage:()=>Oe,createWarpI18nText:()=>Rr,createWarpIdentifier:()=>Pt,doesWarpRequireWallet:()=>Sr,evaluateOutputCommon:()=>Kt,evaluateWhenCondition:()=>k,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractPromptOutput:()=>Xt,extractQueryStringFromIdentifier:()=>Gt,extractQueryStringFromUrl:()=>zt,extractResolvedInputValues:()=>j,extractWarpSecrets:()=>Ir,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>mr,getChainLogo:()=>yr,getCryptoProvider:()=>Dt,getGeneratedSourceWarpName:()=>Be,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>Yt,getNextInfo:()=>ot,getNextInfoForStatus:()=>pt,getProviderConfig:()=>zr,getRandomBytes:()=>Mt,getRandomHex:()=>kt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>ir,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>Wr,getWarpChainAssetLogoUrl:()=>xr,getWarpChainInfoLogoUrl:()=>vr,getWarpIdentifierWithQuery:()=>jr,getWarpInfoFromIdentifier:()=>V,getWarpInputAction:()=>N,getWarpWalletAddress:()=>ge,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>or,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>sr,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>ar,hasInputPrefix:()=>Lr,hex:()=>dn,initializeWalletCache:()=>tn,isEqualWarpIdentifier:()=>$r,isGeneratedSourcePrivateIdentifier:()=>Yr,isPlatformValue:()=>Ne,isWarpActionAutoExecute:()=>It,isWarpI18nText:()=>Er,isWarpWalletReadOnly:()=>pr,matchesTrigger:()=>Rn,mergeNestedPayload:()=>Qt,normalizeAndValidateMnemonic:()=>ur,normalizeMnemonic:()=>xe,option:()=>fn,parseOutputOutIndex:()=>$e,parseSignedMessage:()=>Jr,parseWarpQueryStringToObject:()=>_t,removeWarpChainPrefix:()=>Br,removeWarpWalletFromConfig:()=>cr,replacePlaceholders:()=>B,replacePlaceholdersInWhenExpression:()=>M,resolveInputs:()=>$n,resolveNextString:()=>Ur,resolveNextStrings:()=>Et,resolvePath:()=>ce,resolvePlatformValue:()=>Zt,resolveWarpText:()=>st,safeWindow:()=>Ft,setCryptoProvider:()=>Ar,setWarpWalletInConfig:()=>lr,shiftBigintBy:()=>at,splitInput:()=>St,stampGeneratedWarpMeta:()=>Zr,string:()=>nn,struct:()=>hn,testCryptoAvailability:()=>br,toInputPayloadValue:()=>Ee,toPreviewText:()=>qt,tuple:()=>gn,uint16:()=>sn,uint32:()=>on,uint64:()=>pn,uint8:()=>an,validateMnemonicLength:()=>ve,validateSignedMessage:()=>_r,vector:()=>mn,withAdapterFallback:()=>hr});module.exports=nr(Nn);var rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ge=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>ge(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,ar=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,sr=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},pr=r=>typeof r=="string",lr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},cr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},xe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ve=(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=xe(r);return ve(e,t),e};var Ae=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(Ae||{}),Vt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Vt||{}),Ht=Object.values(Vt),dr=["ethereum","base","arbitrum","polygon","somnia","tempo"],fr=["multiversx","claws"],gr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:"}},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",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},Ft=typeof window<"u"?window:{open:()=>{}};var q={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${q.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${q.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","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 hr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ce={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},mr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),be={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},yr=(r,t="dark")=>{let e=be[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Ut=(r,t)=>r[t]??r.default??Object.values(r)[0],Wr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ut(r.logo,e)},xr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)},vr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)};var bt=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}},wt=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"}`)}}},z=null;function Dt(){if(z)return z;if(typeof window<"u"&&window.crypto)return z=new bt,z;if(typeof process<"u"&&process.versions?.node)return z=new wt,z;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(r){z=r}async function Mt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).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 Cr(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 kt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Mt(r/2,t);return we(e)}async function br(){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 Mt(16),r.randomBytes=!0}catch{}return r}function wr(){return Dt()}var Ir=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},it=r=>{if(r==="warp")return`warp:${q.Warp}`;if(r==="brand")return`brand:${q.Brand}`;if(r==="abi")return`abi:${q.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Pr=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Pr.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},It=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,at=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},B=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),M=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),Sr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},k=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var Tr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},st=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Er=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Rr=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,$r=(r,t)=>!r||!t?!1:X(r)===X(t),Pt=(r,t,e)=>{let n=X(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},V=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=Ie(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=Nr(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},Z=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return V(i)},Nr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Or=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ie=r=>{let t=Or(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Ie(a);return[i,...s]},zt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Gt=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},_t=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Br=r=>{let t=V(r);return(t?t.identifierBase:X(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 St=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Lr=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=St(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,B(s,t)]});return Object.fromEntries(n)};var Pe=K(require("qr-code-styling"),1);var G=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=V(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return D.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Pe.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 Vr="https://",Hr=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=M(r.when,t);if(!k(e))return null}return r.identifier},Fr=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),Et=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(Fr(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=Hr(a,e);s!==null&&i.push(s)}return i.length>0?i:null},Ur=(r,t,e)=>Et(r,t,e)?.[0]??null,Se=(r,t,e,n,i)=>{if(n.startsWith(Vr))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=B(a,{...e.vars,...i});return[{identifier:f,url:Jt(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=B(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Jt(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:f,field:y?y.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:x,field:C}of h){let v=C?Dr(f,C):f;if(v==null)return null;g=g.replace(x,v)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Jt(t,y,r)}}).filter(f=>f!==null)},ot=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Et(a,"success",i);if(!s)return null;let p=s.flatMap(l=>Se(r,t,e,l,i));return p.length>0?p:null},pt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=Et(p,s,i);if(!l)return null;let o=l.flatMap(c=>Se(r,t,e,c,i));return o.length>0?o:null},Jt=(r,t,e)=>{let[n,i]=t.split("?"),a=new G(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},Dr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var _=class _{static debug(...t){_.isTestEnv||console.debug(...t)}static info(...t){_.isTestEnv||console.info(...t)}static warn(...t){_.isTestEnv||console.warn(...t)}static error(...t){_.isTestEnv||console.error(...t)}};_.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var b=_;function Te(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function 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 Ee(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 j(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function J(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Ee(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Te(n.input.position,i,a);e=Qt(e,s)}else e[i]=a}),e}function lt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=$e(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Y=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=Re(r,e,p),d=J(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await Kt(r,c,t,e,n,i,a)}},Kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Mr(p,r,n,i,a),p=await kr(r,p,e,i,a,s.transform?.runner||null),p},Mr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},kr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:qr(e),inputs:lt(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){b.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},qr=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},Xt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Re(r,e,s),c=await Kt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:J(n,i)},output:c}},$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 Ne=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ht.some(t=>t in r),Zt=(r,t)=>{if(!Ne(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 zr=(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 kt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Oe(r,i,e,5)}function $t(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Gr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),p=await t(i);return $t(r,p,a,s)}function _r(r){let t=new Date(r).getTime();return Date.now()<t}function Jr(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 Be=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Qr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),je=(r,t=24)=>{let e=Qr(r);return e?e.slice(0,t):"action"},Le=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)},Kr=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()}},Xr=(r,t,e)=>{let n=je((e||t||"").trim()||"action"),i=`${r.type}|${Kr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Le(i);return`private_src_${n}_${a}`},Ve=r=>{let t=Be(r),e=je(t),n=Le(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Zr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ve(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Yr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function tn(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 en(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=N(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},rn=async(r,t,e,n)=>{try{let i=W(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Nt=require("mppx/client");async function Yt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return b.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Nt.Mppx.create({methods:[(0,Nt.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Fe=/^(.+)\[\]$/,Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,Fe.test(t))return t+u.ArgParamsSeparator+JSON.stringify(e);if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(m.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(m.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=Ue[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(Fe.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.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.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var nn=r=>new w().nativeToString(m.String,r),an=r=>new w().nativeToString(m.Uint8,r),sn=r=>new w().nativeToString(m.Uint16,r),on=r=>new w().nativeToString(m.Uint32,r),pn=r=>new w().nativeToString(m.Uint64,r),ln=r=>new w().nativeToString(m.Biguint,r),cn=r=>new w().nativeToString(m.Bool,r),un=r=>new w().nativeToString(m.Address,r),te=r=>new w().nativeToString(m.Asset,r),dn=r=>new w().nativeToString(m.Hex,r),fn=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},gn=(...r)=>new w().nativeToString(m.Tuple,r),hn=r=>new w().nativeToString(m.Struct,r),mn=r=>new w().nativeToString(m.Vector,r);var De=K(require("ajv"),1);var ee=class{constructor(t){this.pendingBrand={protocol:it("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ke=K(require("ajv"),1);var Me={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{type:"string"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string",description:"Variable name to store the LLM-generated response in. Defaults to MESSAGE if not set."},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var Wn=new Set(["POST","PUT","PATCH","DELETE"]),xn=/^[A-Z][A-Z0-9_]*$/,ct=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=N(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||xn.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!Wn.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():Me,n=new ke.default({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ut=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return qt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var T=require("fs"),et=require("path");var re="$bigint:",Ot=(r,t)=>typeof t=="bigint"?re+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var Bt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,T.existsSync)(this.cacheDir)||(0,T.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,T.existsSync)(e))return null;let n=(0,T.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,T.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,T.writeFileSync)(a,JSON.stringify(i,Ot),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,T.existsSync)(e)&&(0,T.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,T.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,T.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,T.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var dt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,tt);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ot))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var ft=H;var qe=require("fs"),ne=require("path");var jt=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,qe.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return b.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ie={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},gt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new dt(t,e):e?.type==="memory"?new ft(t,e):e?.type==="static"?new jt(t,e):e?.type==="filesystem"?new Bt(t,e):typeof window<"u"&&window.localStorage?new dt(t,e):new ft(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var mt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},oe=r=>{try{return JSON.parse(r)}catch{return null}},vn=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Rt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries($t(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=se(e.resolvedInputs,mt.Headers,i);if(p){let l=oe(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},An=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,mt.Queries,i);if(s){let p=oe(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},Cn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,mt.Payload,n);if(a&&oe(a)!==null)return a;let{[mt.Payload]:s,[mt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},ze=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ae.Get,o=await vn(r,t,e,n,a,p),c=An(r,t,e,l,a),d=Cn(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var $=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${bn(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=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(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return B(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},bn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var wn=["collect","compute","mcp","state","mount","unmount"],In=new Set(Object.values(m)),Pn=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:In.has(r.slice(0,t))},Q=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 gt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return j(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ht.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),c=E(o,e),{action:d,index:h}=N(o),f=[],g=[];if(h===e-1){let P=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,P,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let y=g.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,x=this.getDestinationFromAction(c),C=y?this.serializer.stringToNative(y)[1]:x;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!wn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(c,g);v=v.map(P=>l.applyInputs(P,g,this.serializer));let R=g.find(P=>P.input.position==="value")?.value||null,A="value"in c?c.value:null,L=R?.split(u.ArgParamsSeparator)[1]||A||"0",F=l.applyInputs(L,g,this.serializer),O=BigInt(F),U=g.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Ge=[...("transfers"in c?c.transfers:[])||[],...U||[]].map(P=>{let Lt=l.applyInputs(P,g,this.serializer),Ke=Lt.startsWith(`asset${u.ArgParamsSeparator}`)?Lt:`asset${u.ArgParamsSeparator}${Lt}`;return this.serializer.stringToNative(Ke)[1]}),_e=g.find(P=>P.input.position==="data")?.value,Je="data"in c?c.data||"":null,ue=_e||Je||null,Qe=ue?l.applyInputs(ue,g,this.serializer):null,de={adapter:p,warp:o,chain:s,action:e,destination:C,args:v,value:O,transfers:Ge,data:Qe,resolvedInputs:g};return await this.cache.set(ht.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return 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||Pn(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let x=S(this.config,t);return x?this.serializer.nativeToString("address",x):null}if(c.source==="hidden"){if(c.default===void 0)return null;let x=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,x)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),y=f||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),p=new $(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=at(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=at(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=lt(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=St(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=at(p,o.decimals);return te({...o,amount:c})}else return e}catch(n){throw b.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var yt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this.handlers=n,this.factory=new Q(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let f=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(f){let g=await new $(this.config,f,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:h}=N(t);for(let f=1;f<=t.actions.length;f++){let g=E(t,f);if(!It(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:x,chain:C,immediateExecution:v,executable:R}=await this.executeAction(t,f,e,y);if(x&&i.push(x),C&&(a=C),v&&s.push(v),v?.output){let{_DATA:A,...L}=v.output;Object.assign(d,L)}v?.values?.mapped&&Object.assign(d,v.values.mapped),R&&f===h+1&&R.resolvedInputs&&(p=j(R.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Ft.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=M(a.when,o);if(!k(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[y,x]of Object.entries(c.meta?.query||{}))h[y]=x.replace(/\{\{(.+?)\}\}/g,(C,v)=>{let R=d[v.trim()];return R==null?"":typeof R=="object"?JSON.stringify(R):String(R)});c.meta={...c.meta,query:h};let{immediateExecutions:f}=await this.execute(c,[],i),g=f[0];return g?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),{tx:null,chain:null,immediateExecution:g,executable:null}):{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!It(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={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:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=Sn(c,d.output);return d.next=pt(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=S(this.config,t.chain.name),a=E(t.warp,t.action),s=this.factory.getSerializer(),p=J(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await Y(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=J(t.resolvedInputs,n),{values:a,output:s}=await Y(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new $(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await ze(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));s&&(o=B(o,s)),b.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},y=await(await Yt(this.adapters))(o,f);b.debug("Collect response status",{status:y.status});let x=await y.json();b.debug("Collect response content",{content:x});let{values:C,output:v}=await Y(t.warp,x,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),y.ok?"success":"error",C,v,x)}catch(f){b.error("WarpActionExecutor: Error executing collect",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs: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=E(t.warp,t.action);if(!i.destination){let f=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=j(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:g}}let p=this.factory.getSerializer(),l=new $(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let y=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=y}),b.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:L})=>{if(L&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let F=A.position.replace("payload:",""),[O,U]=p.stringToNative(L);if(O==="string")y[F]=String(U);else if(O==="bool")y[F]=!!U;else if(O==="uint8"||O==="uint16"||O==="uint32"||O==="uint64"||O==="uint128"||O==="uint256"||O==="biguint"){let vt=Number(U);y[F]=(Number.isInteger(vt),vt)}else y[F]=U}}),e&&Object.assign(y,e);let x=await g.callTool({name:d,arguments:y});await g.close();let C;if(x.content&&x.content.length>0){let A=x.content[0];if(A.type==="text")try{C=JSON.parse(A.text)}catch{C=A.text}else A.type,C=A}else C=x;let{values:v,output:R}=await Y(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",v,R,x)}catch(f){b.error("WarpExecutor: Error executing MCP",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=pt(this.config,this.adapters,t.warp,t.action,a,n),l=j(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:Tt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=M(s.when,h);try{if(!k(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),b.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=M(e.when,l);if(!k(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let x=o[y.trim()];return x!=null?String(x):h});c[d]=Tn(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),L=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(L)}else{let{action:A}=N(o),L=this.factory.getStringTypedInputs(A,i),F=await this.factory.getResolvedInputs(s.name,A,L,l,a.queries);d=await this.factory.getModifiedInputs(F)}let h=Zt(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=B(f,a.envs));let g=j(d),y=S(this.config,s.name),x=this.factory.getSerializer(),{values:C,output:v}=await Xt(o,f,n,d,x,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f,c.expect);A&&(v.MESSAGE=A,c.as&&(v[c.as]=A))}let R=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,v),values:C,output:v,messages:Tt(o,{...C.mapped,...v},this.config),destination:R,resolvedInputs:g}}catch(s){return b.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:pt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new $(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=M(e.when,h);return k(f)}},Sn=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},Tn=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Wt=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw b.error("WarpIndex: Error searching for warps: ",i),i}}};var xt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?Z(t):V(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?zt(t):Gt(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(En(p,i.chain,l,i.identifier),p.meta.query=c?_t(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new $(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return b.error("Error detecting warp link",a),n}}},En=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Pt(null,"alias",e.alias):Pt(t,"hash",e?.hash??n))};var pe=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new rt(e));return new nt(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new yt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new xt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},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=V(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");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??N(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=ot(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 Q(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new G(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ut(this.config)}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 st(t,this.config)}};var le=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function Rn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function $n(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpInputAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolveNextStrings,resolvePath,resolvePlatformValue,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 Ze=Object.create;var At=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var er=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var nr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tr(t))!rr.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ye(t,i))||n.enumerable});return r};var K=(r,t,e)=>(e=r!=null?Ze(er(r)):{},ge(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),ir=r=>ge(At({},"__esModule",{value:!0}),r);var jn={};nr(jn,{BrowserCryptoProvider:()=>bt,CLOUD_WALLET_PROVIDERS:()=>hr,CacheTtl:()=>ae,EvmWalletChainNames:()=>fr,MultiversxWalletChainNames:()=>gr,NodeCryptoProvider:()=>wt,WARP_LANGUAGES:()=>Er,WarpAssets:()=>I,WarpBrandBuilder:()=>re,WarpBuilder:()=>ut,WarpCache:()=>gt,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>be,WarpChainLogos:()=>we,WarpChainName:()=>Ce,WarpChainResolver:()=>rt,WarpClient:()=>le,WarpCompositeResolver:()=>nt,WarpConfig:()=>D,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>Q,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>$,WarpLinkBuilder:()=>_,WarpLinkDetecter:()=>xt,WarpLogger:()=>b,WarpPlatformName:()=>Vt,WarpPlatforms:()=>Ht,WarpProtocolVersions:()=>q,WarpSerializer:()=>w,WarpTypeRegistry:()=>ce,WarpValidator:()=>ct,address:()=>gn,applyOutputToMessages:()=>Tt,asset:()=>ee,biguint:()=>dn,bool:()=>fn,buildGeneratedFallbackWarpIdentifier:()=>He,buildGeneratedSourceWarpIdentifier:()=>Yr,buildInputsContext:()=>lt,buildMappedOutput:()=>J,buildNestedPayload:()=>Ee,bytesToBase64:()=>br,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>an,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>$t,createAuthMessage:()=>Rt,createCryptoProvider:()=>Ir,createDefaultWalletProvider:()=>nn,createHttpAuthHeaders:()=>Jr,createSignableMessage:()=>Be,createWarpI18nText:()=>$r,createWarpIdentifier:()=>Pt,doesWarpRequireWallet:()=>Tr,evaluateOutputCommon:()=>Kt,evaluateWhenCondition:()=>M,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractInlineOutput:()=>Zt,extractPromptOutput:()=>Xt,extractQueryStringFromIdentifier:()=>_t,extractQueryStringFromUrl:()=>zt,extractResolvedInputValues:()=>j,extractWarpSecrets:()=>Pr,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>yr,getChainLogo:()=>Wr,getCryptoProvider:()=>Dt,getGeneratedSourceWarpName:()=>je,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>te,getNextInfo:()=>ot,getNextInfoForStatus:()=>pt,getProviderConfig:()=>Gr,getRandomBytes:()=>kt,getRandomHex:()=>Mt,getRequiredAssetIds:()=>Fe,getWalletFromConfigOrFail:()=>ar,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>xr,getWarpChainAssetLogoUrl:()=>vr,getWarpChainInfoLogoUrl:()=>Ar,getWarpIdentifierWithQuery:()=>Lr,getWarpInfoFromIdentifier:()=>V,getWarpInputAction:()=>N,getWarpWalletAddress:()=>he,getWarpWalletAddressFromConfig:()=>S,getWarpWalletExternalId:()=>We,getWarpWalletExternalIdFromConfig:()=>xe,getWarpWalletExternalIdFromConfigOrFail:()=>pr,getWarpWalletMnemonic:()=>ye,getWarpWalletMnemonicFromConfig:()=>or,getWarpWalletPrivateKey:()=>me,getWarpWalletPrivateKeyFromConfig:()=>sr,hasInputPrefix:()=>Vr,hex:()=>hn,initializeWalletCache:()=>rn,isEqualWarpIdentifier:()=>Nr,isGeneratedSourcePrivateIdentifier:()=>en,isPlatformValue:()=>Oe,isWarpActionAutoExecute:()=>It,isWarpI18nText:()=>Rr,isWarpWalletReadOnly:()=>lr,matchesTrigger:()=>On,mergeNestedPayload:()=>Qt,normalizeAndValidateMnemonic:()=>dr,normalizeMnemonic:()=>ve,option:()=>mn,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>Kr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>jr,removeWarpWalletFromConfig:()=>ur,replacePlaceholders:()=>B,replacePlaceholdersInWhenExpression:()=>k,resolveInputs:()=>Bn,resolveNextString:()=>Dr,resolveNextStrings:()=>Et,resolvePath:()=>ue,resolvePlatformValue:()=>Yt,resolveWarpText:()=>st,safeWindow:()=>Ft,setCryptoProvider:()=>Cr,setWarpWalletInConfig:()=>cr,shiftBigintBy:()=>at,splitInput:()=>St,stampGeneratedWarpMeta:()=>tn,string:()=>on,struct:()=>Wn,testCryptoAvailability:()=>wr,toInputPayloadValue:()=>Re,toPreviewText:()=>qt,tuple:()=>yn,uint16:()=>ln,uint32:()=>cn,uint64:()=>un,uint8:()=>pn,validateMnemonicLength:()=>Ae,validateSignedMessage:()=>Qr,vector:()=>xn,withAdapterFallback:()=>mr});module.exports=ir(jn);var rt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var nt=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var ar=(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,sr=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,xe=(r,t)=>We(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},lr=r=>typeof r=="string",cr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ur=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ae=(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`)},dr=(r,t=24)=>{let e=ve(r);return Ae(e,t),e};var Ce=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(Ce||{}),Vt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Vt||{}),Ht=Object.values(Vt),fr=["ethereum","base","arbitrum","polygon","somnia","tempo"],gr=["multiversx","claws"],hr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:";",Append:{Prefix:"append:"},Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},Ft=typeof window<"u"?window:{open:()=>{}};var q={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${q.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${q.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","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 mr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",I={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},be={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},yr=r=>be[r]??r.charAt(0).toUpperCase()+r.slice(1),we={ethereum:{light:I.chainLogo("ethereum-white.svg"),dark:I.chainLogo("ethereum-black.svg")},base:{light:I.chainLogo("base-white.svg"),dark:I.chainLogo("base-black.svg")},arbitrum:I.chainLogo("arbitrum.svg"),polygon:I.chainLogo("polygon.svg"),somnia:I.chainLogo("somnia.png"),tempo:{light:I.chainLogo("tempo-white.svg"),dark:I.chainLogo("tempo-black.svg")},multiversx:I.chainLogo("multiversx.svg"),claws:I.chainLogo("claws.png"),sui:I.chainLogo("sui.svg"),solana:I.chainLogo("solana.svg"),near:{light:I.chainLogo("near-white.svg"),dark:I.chainLogo("near-black.svg")},fastset:{light:I.chainLogo("fastset-white.svg"),dark:I.chainLogo("fastset-black.svg")}},Wr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Ut=(r,t)=>r[t]??r.default??Object.values(r)[0],xr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Ut(r.logo,e)},vr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)},Ar=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Ut(r.logoUrl,e)};var bt=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}},wt=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"}`)}}},z=null;function Dt(){if(z)return z;if(typeof window<"u"&&window.crypto)return z=new bt,z;if(typeof process<"u"&&process.versions?.node)return z=new wt,z;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Cr(r){z=r}async function kt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Dt()).getRandomBytes(r)}function Ie(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function br(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await kt(r/2,t);return Ie(e)}async function wr(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await kt(16),r.randomBytes=!0}catch{}return r}function Ir(){return Dt()}var Pr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},it=r=>{if(r==="warp")return`warp:${q.Warp}`;if(r==="brand")return`brand:${q.Brand}`;if(r==="abi")return`abi:${q.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Sr=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Sr.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},It=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,at=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},B=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),k=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),Tr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},M=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 Er={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},st=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},Rr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,$r=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Nr=(r,t)=>!r||!t?!1:X(r)===X(t),Pt=(r,t,e)=>{let n=X(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},V=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=Pe(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=Or(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},Z=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return V(i)},Or=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Br=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Pe=r=>{let t=Br(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Pe(a);return[i,...s]},zt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},_t=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},jr=r=>{let t=V(r);return(t?t.identifierBase:X(r)).trim()},Lr=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 St=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Vr=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=St(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,B(s,t)]});return Object.fromEntries(n)};var Se=K(require("qr-code-styling"),1);var _=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=V(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return D.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Se.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 Hr="https://",Fr=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=k(r.when,t);if(!M(e))return null}return r.identifier},Ur=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),Et=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(Ur(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=Fr(a,e);s!==null&&i.push(s)}return i.length>0?i:null},Dr=(r,t,e)=>Et(r,t,e)?.[0]??null,Te=(r,t,e,n,i)=>{if(n.startsWith(Hr))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=B(a,{...e.vars,...i});return[{identifier:f,url:Jt(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=B(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Jt(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:f,field:y?y.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:x,field:C}of h){let v=C?kr(f,C):f;if(v==null)return null;g=g.replace(x,v)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Jt(t,y,r)}}).filter(f=>f!==null)},ot=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Et(a,"success",i);if(!s)return null;let p=s.flatMap(l=>Te(r,t,e,l,i));return p.length>0?p:null},pt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=Et(p,s,i);if(!l)return null;let o=l.flatMap(c=>Te(r,t,e,c,i));return o.length>0?o:null},Jt=(r,t,e)=>{let[n,i]=t.split("?"),a=new _(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},kr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var G=class G{static debug(...t){G.isTestEnv||console.debug(...t)}static info(...t){G.isTestEnv||console.info(...t)}static warn(...t){G.isTestEnv||console.warn(...t)}static error(...t){G.isTestEnv||console.error(...t)}};G.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var b=G;function Ee(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function 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 j(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function J(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;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(u.Position.Payload)){let s=Ee(n.input.position,i,a);e=Qt(e,s)}else e[i]=a}),e}function lt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var $e=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ne(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Y=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=$e(r,e,p),d=J(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await Kt(r,c,t,e,n,i,a)}},Kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Mr(p,r,n,i,a),p=await qr(r,p,e,i,a,s.transform?.runner||null),p},Mr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},qr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:zr(e),inputs:lt(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){b.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},zr=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},Xt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=$e(r,e,s),c=await Kt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:J(n,i)},output:c}},_r=(r,t)=>{let e=r.split(".");return e[0]!=="out"?r:e.length===1?t:e.slice(1).reduce((n,i)=>n&&n[i]!==void 0?n[i]:null,t)},Zt=(r,t,e)=>{if(!r.output)return t.output;let n={...t.output||{},...t.values?.mapped||{}},i={};for(let[a,s]of Object.entries(r.output)){let p=s.startsWith(u.Append.Prefix),l=p?s.slice(u.Append.Prefix.length):s,o=_r(l,n);if(p){let c=e?.[a],d=Array.isArray(c)?c:c!==void 0?[c]:[];i[a]=[...d,o]}else i[a]=o}return{...t.output,...i}},Ne=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var Oe=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ht.some(t=>t in r),Yt=(r,t)=>{if(!Oe(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 Gr=(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 Be(r,t,e,n=5){let i=await Mt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Be(r,i,e,5)}function $t(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Jr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),p=await t(i);return $t(r,p,a,s)}function Qr(r){let t=new Date(r).getTime();return Date.now()<t}function Kr(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 je=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Xr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Le=(r,t=24)=>{let e=Xr(r);return e?e.slice(0,t):"action"},Ve=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)},Zr=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()}},Yr=(r,t,e)=>{let n=Le((e||t||"").trim()||"action"),i=`${r.type}|${Zr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Ve(i);return`private_src_${n}_${a}`},He=r=>{let t=je(r),e=Le(t),n=Ve(t.trim().toLowerCase());return`private_gen_${e}_${n}`},tn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||He(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},en=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function rn(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}var Fe=(r,t)=>{let e=null;try{e=N(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},an=async(r,t,e,n)=>{try{let i=W(e,n),a=Fe(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Nt=require("mppx/client");async function te(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return b.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),Nt.Mppx.create({methods:[(0,Nt.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var sn=r=>{try{return JSON.parse(r)}catch{return null}},Ue=/^(.+)\[\]$/,De={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=De[t]??t,Ue.test(t)){let n=typeof e=="string"?sn(e):null;return t+u.ArgParamsSeparator+JSON.stringify(n??e)}if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(m.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(m.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=De[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(Ue.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.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.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var on=r=>new w().nativeToString(m.String,r),pn=r=>new w().nativeToString(m.Uint8,r),ln=r=>new w().nativeToString(m.Uint16,r),cn=r=>new w().nativeToString(m.Uint32,r),un=r=>new w().nativeToString(m.Uint64,r),dn=r=>new w().nativeToString(m.Biguint,r),fn=r=>new w().nativeToString(m.Bool,r),gn=r=>new w().nativeToString(m.Address,r),ee=r=>new w().nativeToString(m.Asset,r),hn=r=>new w().nativeToString(m.Hex,r),mn=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},yn=(...r)=>new w().nativeToString(m.Tuple,r),Wn=r=>new w().nativeToString(m.Struct,r),xn=r=>new w().nativeToString(m.Vector,r);var ke=K(require("ajv"),1);var re=class{constructor(t){this.pendingBrand={protocol:it("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new ke.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var qe=K(require("ajv"),1);var Me={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{type:"string"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},output:{additionalProperties:{type:"string"},type:"object"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var An=new Set(["POST","PUT","PATCH","DELETE"]),Cn=/^[A-Z][A-Z0-9_]*$/,ct=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=N(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||Cn.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!An.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():Me,n=new qe.default({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ut=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return qt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var T=require("fs"),et=require("path");var ne="$bigint:",Ot=(r,t)=>typeof t=="bigint"?ne+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(ne)?BigInt(t.slice(ne.length)):t;var Bt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,T.existsSync)(this.cacheDir)||(0,T.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,T.existsSync)(e))return null;let n=(0,T.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,T.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,T.writeFileSync)(a,JSON.stringify(i,Ot),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,T.existsSync)(e)&&(0,T.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,T.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,T.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,T.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var dt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,tt);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ot))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var ft=H;var ze=require("fs"),ie=require("path");var jt=class{constructor(t,e){let n=e?.path?(0,ie.resolve)(e.path):(0,ie.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,ze.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return b.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ae={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},ht={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},gt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new dt(t,e):e?.type==="memory"?new ft(t,e):e?.type==="static"?new jt(t,e):e?.type==="filesystem"?new Bt(t,e):typeof window<"u"&&window.localStorage?new dt(t,e):new ft(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var mt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},se={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},oe=(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)},pe=r=>{try{return JSON.parse(r)}catch{return null}},bn=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Rt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries($t(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=oe(e.resolvedInputs,mt.Headers,i);if(p){let l=pe(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},wn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===se.Get){let s=oe(e.resolvedInputs,mt.Queries,i);if(s){let p=pe(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},In=(r,t,e,n,i)=>{if(r===se.Get)return;let a=oe(t.resolvedInputs,mt.Payload,n);if(a&&pe(a)!==null)return a;let{[mt.Payload]:s,[mt.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},_e=async(r,t,e,n,i,a,s,p)=>{let l=t.method||se.Get,o=await bn(r,t,e,n,a,p),c=wn(r,t,e,l,a),d=In(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var $=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Pn(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=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(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return B(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},Pn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var Sn=["collect","compute","mcp","state","mount","unmount"],Tn=new Set(Object.values(m)),En=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:Tn.has(r.slice(0,t))},Q=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 gt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return j(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ht.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,i),c=E(o,e),{action:d,index:h}=N(o),f=[],g=[];if(h===e-1){let P=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,P,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let y=g.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,x=this.getDestinationFromAction(c),C=y?this.serializer.stringToNative(y)[1]:x;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!Sn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(c,g);v=v.map(P=>l.applyInputs(P,g,this.serializer));let R=g.find(P=>P.input.position==="value")?.value||null,A="value"in c?c.value:null,L=R?.split(u.ArgParamsSeparator)[1]||A||"0",F=l.applyInputs(L,g,this.serializer),O=BigInt(F),U=g.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Ge=[...("transfers"in c?c.transfers:[])||[],...U||[]].map(P=>{let Lt=l.applyInputs(P,g,this.serializer),Xe=Lt.startsWith(`asset${u.ArgParamsSeparator}`)?Lt:`asset${u.ArgParamsSeparator}${Lt}`;return this.serializer.stringToNative(Xe)[1]}),Je=g.find(P=>P.input.position==="data")?.value,Qe="data"in c?c.data||"":null,de=Je||Qe||null,Ke=de?l.applyInputs(de,g,this.serializer):null,fe={adapter:p,warp:o,chain:s,action:e,destination:C,args:v,value:O,transfers:Ge,data:Ke,resolvedInputs:g};return await this.cache.set(ht.WarpExecutable(this.config.env,o.meta?.hash||"",e),fe.resolvedInputs,ae.OneWeek),fe}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||En(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let x=S(this.config,t);return x?this.serializer.nativeToString("address",x):null}if(c.source==="hidden"){if(c.default===void 0)return null;let x=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,x)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),y=f||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),p=new $(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=at(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=at(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=lt(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=St(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=at(p,o.decimals);return ee({...o,amount:c})}else return e}catch(n){throw b.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var yt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this.handlers=n,this.factory=new Q(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let f=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(f){let g=await new $(this.config,f,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:h}=N(t);for(let f=1;f<=t.actions.length;f++){let g=E(t,f);if(!It(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:x,chain:C,immediateExecution:v,executable:R}=await this.executeAction(t,f,e,y);if(x&&i.push(x),C&&(a=C),v&&s.push(v),v?.output){let{_DATA:A,...L}=v.output;Object.assign(d,L)}v?.values?.mapped&&Object.assign(d,v.values.mapped),R&&f===h+1&&R.resolvedInputs&&(p=j(R.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Ft.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=k(a.when,o);if(!M(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[y,x]of Object.entries(c.meta?.query||{}))h[y]=x.replace(/\{\{(.+?)\}\}/g,(C,v)=>{let R=d[v.trim()];return R==null?"":typeof R=="object"?JSON.stringify(R):String(R)});c.meta={...c.meta,query:h};let{immediateExecutions:f}=await this.execute(c,[],i),g=f[0];if(g){if(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),o.output){let y=Zt(o,g,i.envs);return{tx:null,chain:null,immediateExecution:{...g,output:y},executable:null}}return{tx:null,chain:null,immediateExecution:g,executable:null}}return{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!It(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={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:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=Rn(c,d.output);return d.next=pt(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=S(this.config,t.chain.name),a=E(t.warp,t.action),s=this.factory.getSerializer(),p=J(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await Y(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=J(t.resolvedInputs,n),{values:a,output:s}=await Y(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new $(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await _e(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));s&&(o=B(o,s)),b.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},y=await(await te(this.adapters))(o,f);b.debug("Collect response status",{status:y.status});let x=await y.json();b.debug("Collect response content",{content:x});let{values:C,output:v}=await Y(t.warp,x,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),y.ok?"success":"error",C,v,x)}catch(f){b.error("WarpActionExecutor: Error executing collect",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs: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=E(t.warp,t.action);if(!i.destination){let f=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=j(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:g}}let p=this.factory.getSerializer(),l=new $(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let y=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=y}),b.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:L})=>{if(L&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let F=A.position.replace("payload:",""),[O,U]=p.stringToNative(L);if(O==="string")y[F]=String(U);else if(O==="bool")y[F]=!!U;else if(O==="uint8"||O==="uint16"||O==="uint32"||O==="uint64"||O==="uint128"||O==="uint256"||O==="biguint"){let vt=Number(U);y[F]=(Number.isInteger(vt),vt)}else y[F]=U}}),e&&Object.assign(y,e);let x=await g.callTool({name:d,arguments:y});await g.close();let C;if(x.content&&x.content.length>0){let A=x.content[0];if(A.type==="text")try{C=JSON.parse(A.text)}catch{C=A.text}else A.type,C=A}else C=x;let{values:v,output:R}=await Y(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",v,R,x)}catch(f){b.error("WarpExecutor: Error executing MCP",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=pt(this.config,this.adapters,t.warp,t.action,a,n),l=j(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:Tt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=k(s.when,h);try{if(!M(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),b.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=k(e.when,l);if(!M(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let x=o[y.trim()];return x!=null?String(x):h});c[d]=$n(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new $(this.config,p,this.adapters),o=await l.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),L=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(L)}else{let{action:A}=N(o),L=this.factory.getStringTypedInputs(A,i),F=await this.factory.getResolvedInputs(s.name,A,L,l,a.queries);d=await this.factory.getModifiedInputs(F)}let h=Yt(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=B(f,a.envs));let g=j(d),y=S(this.config,s.name),x=this.factory.getSerializer(),{values:C,output:v}=await Xt(o,f,n,d,x,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f,c.expect);A&&(v.MESSAGE=A,c.as&&(v[c.as]=A))}let R=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,v),values:C,output:v,messages:Tt(o,{...C.mapped,...v},this.config),destination:R,resolvedInputs:g}}catch(s){return b.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:pt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new $(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=k(e.when,h);return M(f)}},Rn=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},$n=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Wt=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw b.error("WarpIndex: Error searching for warps: ",i),i}}};var xt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?Z(t):V(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?zt(t):_t(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(Nn(p,i.chain,l,i.identifier),p.meta.query=c?Gt(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new $(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return b.error("Error detecting warp link",a),n}}},Nn=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Pt(null,"alias",e.alias):Pt(t,"hash",e?.hash??n))};var le=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new rt(e));return new nt(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new yt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new xt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},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=V(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");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??N(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=ot(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 Q(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new _(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ut(this.config)}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 st(t,this.config)}};var ce=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function On(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ue(t,n)!==i)return!1;return!0}function Bn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ue(t,i):i;return e}function ue(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractInlineOutput,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpInputAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolveNextStrings,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var nt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var it=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Er=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Se=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>Se(r.user?.wallets?.[t]||null),Te=r=>r?typeof r=="string"?r:r.privateKey||null:null,Ee=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Re=r=>r?typeof r=="string"?r:r.externalId||null:null,Rr=(r,t)=>Te(r.user?.wallets?.[t]||null)?.trim()||null,$r=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,$e=(r,t)=>Re(r.user?.wallets?.[t]||null)?.trim()||null,Nr=(r,t)=>{let e=$e(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Or=r=>typeof r=="string",Br=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},jr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Ne=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Oe=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Lr=(r,t=24)=>{let e=Ne(r);return Oe(e,t),e};var Be=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(Be||{}),Mt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Mt||{}),kt=Object.values(Mt),Fr=["ethereum","base","arbitrum","polygon","somnia","tempo"],Ur=["multiversx","claws"],Dr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:"}},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",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},qt=typeof window<"u"?window:{open:()=>{}};var z={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${z.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${z.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","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 zr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var at="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",P={baseUrl:at,chainLogo:r=>`${at}/chains/logos/${r}`,tokenLogo:r=>`${at}/tokens/logos/${r}`,walletLogo:r=>`${at}/wallets/logos/${r}`},je={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},_r=r=>je[r]??r.charAt(0).toUpperCase()+r.slice(1),Le={ethereum:{light:P.chainLogo("ethereum-white.svg"),dark:P.chainLogo("ethereum-black.svg")},base:{light:P.chainLogo("base-white.svg"),dark:P.chainLogo("base-black.svg")},arbitrum:P.chainLogo("arbitrum.svg"),polygon:P.chainLogo("polygon.svg"),somnia:P.chainLogo("somnia.png"),tempo:{light:P.chainLogo("tempo-white.svg"),dark:P.chainLogo("tempo-black.svg")},multiversx:P.chainLogo("multiversx.svg"),claws:P.chainLogo("claws.png"),sui:P.chainLogo("sui.svg"),solana:P.chainLogo("solana.svg"),near:{light:P.chainLogo("near-white.svg"),dark:P.chainLogo("near-black.svg")},fastset:{light:P.chainLogo("fastset-white.svg"),dark:P.chainLogo("fastset-black.svg")}},Jr=(r,t="dark")=>{let e=Le[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var bt=(r,t)=>r[t]??r.default??Object.values(r)[0],Kr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:bt(r.logo,e)},Xr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return bt(r.logoUrl,e)},Zr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return bt(r.logoUrl,e)};var wt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},It=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},D=null;function zt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new wt,D;if(typeof process<"u"&&process.versions?.node)return D=new It,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function tn(r){D=r}async function Gt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||zt()).getRandomBytes(r)}function Ve(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 en(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 _t(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Gt(r/2,t);return Ve(e)}async function rn(){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 Gt(16),r.randomBytes=!0}catch{}return r}function nn(){return zt()}var on=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},st=r=>{if(r==="warp")return`warp:${z.Warp}`;if(r==="brand")return`brand:${z.Brand}`;if(r==="abi")return`abi:${z.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],He=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!He.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},Pt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,ot=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Jt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},B=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),M=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),dn=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},k=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var gn={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"},pt=(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""},hn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,mn=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,vn=(r,t)=>!r||!t?!1:K(r)===K(t),St=(r,t,e)=>{let n=K(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},F=r=>{let t=decodeURIComponent(r).trim(),e=K(t),n=e.split("?")[0],i=Qt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=Fe(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},X=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return F(i)},Fe=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ue=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Qt=r=>{let t=Ue(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Qt(a);return[i,...s]},Kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Xt=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},An=r=>{let t=F(r);return(t?t.identifierBase:K(r)).trim()},Cn=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 Tt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},In=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Tt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=pt(a,e);return[i,B(s,t)]});return Object.fromEntries(n)};import De from"qr-code-styling";var G=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=F(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return U.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new De({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 Me="https://",ke=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=M(r.when,t);if(!k(e))return null}return r.identifier},qe=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),$t=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(qe(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=ke(a,e);s!==null&&i.push(s)}return i.length>0?i:null},Fn=(r,t,e)=>$t(r,t,e)?.[0]??null,Yt=(r,t,e,n,i)=>{if(n.startsWith(Me))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=B(a,{...e.vars,...i});return[{identifier:f,url:Rt(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=B(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Rt(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:f,field:y?y.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:x,field:C}of h){let v=C?ze(f,C):f;if(v==null)return null;g=g.replace(x,v)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Rt(t,y,r)}}).filter(f=>f!==null)},lt=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=$t(a,"success",i);if(!s)return null;let p=s.flatMap(l=>Yt(r,t,e,l,i));return p.length>0?p:null},ct=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=$t(p,s,i);if(!l)return null;let o=l.flatMap(c=>Yt(r,t,e,c,i));return o.length>0?o:null},Rt=(r,t,e)=>{let[n,i]=t.split("?"),a=new G(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},ze=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var q=class q{static debug(...t){q.isTestEnv||console.debug(...t)}static info(...t){q.isTestEnv||console.info(...t)}static warn(...t){q.isTestEnv||console.warn(...t)}static error(...t){q.isTestEnv||console.error(...t)}};q.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var b=q;function Ge(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function te(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]=te(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 j(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function _(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;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(u.Position.Payload)){let s=Ge(n.input.position,i,a);e=te(e,s)}else e[i]=a}),e}function ut(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var ee=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Xe(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=ee(r,e,p),d=_(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await re(r,c,t,e,n,i,a)}},re=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Je(p,r,n,i,a),p=await Qe(r,p,e,i,a,s.transform?.runner||null),p},Je=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Qe=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Ke(e),inputs:ut(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){b.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Ke=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},ne=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=ee(r,e,s),c=await re(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:_(n,i)},output:c}},Xe=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 Ze=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:kt.some(t=>t in r),ie=(r,t)=>{if(!Ze(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 Zn=(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 Ye(r,t,e,n=5){let i=await _t(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 Nt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ye(r,i,e,5)}function Ot(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function ri(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Nt(r,e,n),p=await t(i);return Ot(r,p,a,s)}function ni(r){let t=new Date(r).getTime();return Date.now()<t}function ii(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 tr=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,""),ae=(r,t=24)=>{let e=er(r);return e?e.slice(0,t):"action"},se=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()}},si=(r,t,e)=>{let n=ae((e||t||"").trim()||"action"),i=`${r.type}|${rr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=se(i);return`private_src_${n}_${a}`},nr=r=>{let t=tr(r),e=ae(t),n=se(t.trim().toLowerCase());return`private_gen_${e}_${n}`},oi=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||nr(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},pi=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ci(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 di(r,t,e){return null}var ir=(r,t)=>{let e=null;try{e=N(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},hi=async(r,t,e,n)=>{try{let i=W(e,n),a=ir(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as ar,tempo as sr}from"mppx/client";async function oe(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return b.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),ar.create({methods:[sr({account:e})],polyfill:!1}).fetch}return fetch}var pe=/^(.+)\[\]$/,le={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=le[t]??t,pe.test(t))return t+u.ArgParamsSeparator+JSON.stringify(e);if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(m.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(m.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=le[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(pe.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.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.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var wi=r=>new w().nativeToString(m.String,r),Ii=r=>new w().nativeToString(m.Uint8,r),Pi=r=>new w().nativeToString(m.Uint16,r),Si=r=>new w().nativeToString(m.Uint32,r),Ti=r=>new w().nativeToString(m.Uint64,r),Ei=r=>new w().nativeToString(m.Biguint,r),Ri=r=>new w().nativeToString(m.Bool,r),$i=r=>new w().nativeToString(m.Address,r),ce=r=>new w().nativeToString(m.Asset,r),Ni=r=>new w().nativeToString(m.Hex,r),Oi=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Bi=(...r)=>new w().nativeToString(m.Tuple,r),ji=r=>new w().nativeToString(m.Struct,r),Li=r=>new w().nativeToString(m.Vector,r);import or from"ajv";var ue=class{constructor(t){this.pendingBrand={protocol:st("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 or,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import lr from"ajv";var de={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{type:"string"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string",description:"Variable name to store the LLM-generated response in. Defaults to MESSAGE if not set."},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var cr=new Set(["POST","PUT","PATCH","DELETE"]),ur=/^[A-Z][A-Z0-9_]*$/,dt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=N(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||ur.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!cr.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():de,n=new lr({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ft=class{constructor(t){this.config=t;this.pendingWarp={protocol:st("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Jt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new dt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};import{existsSync as jt,mkdirSync as dr,readdirSync as fe,readFileSync as fr,unlinkSync as Lt,writeFileSync as gr}from"fs";import{join as ge,resolve as he}from"path";var Bt="$bigint:",gt=(r,t)=>typeof t=="bigint"?Bt+t.toString():t,J=(r,t)=>typeof t=="string"&&t.startsWith(Bt)?BigInt(t.slice(Bt.length)):t;var ht=class{constructor(t,e){let n=e?.path;this.cacheDir=n?he(n):he(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){jt(this.cacheDir)||dr(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ge(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!jt(e))return null;let n=fr(e,"utf-8"),i=JSON.parse(n,J);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Lt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);gr(a,JSON.stringify(i,gt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);jt(e)&&Lt(e)}catch{}}async keys(t){try{let e=fe(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{fe(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Lt(ge(this.cacheDir,e))})}catch{}}};var Y=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,J);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,gt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{constructor(t,e){}async get(t){let e=L.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;L.cache.set(t,{value:e,expiresAt:i})}async delete(t){L.cache.delete(t)}async keys(t){let e=Array.from(L.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){L.cache.clear()}};L.cache=new Map;var tt=L;import{readFileSync as hr}from"fs";import{resolve as me}from"path";var mt=class{constructor(t,e){let n=e?.path?me(e.path):me(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=hr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,J)))}catch(e){return b.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ye={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},yt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new mt(t,e):e?.type==="filesystem"?new ht(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Vt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ht=(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)},Ft=r=>{try{return JSON.parse(r)}catch{return null}},mr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Nt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Ot(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=Ht(e.resolvedInputs,et.Headers,i);if(p){let l=Ft(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},yr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Vt.Get){let s=Ht(e.resolvedInputs,et.Queries,i);if(s){let p=Ft(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},Wr=(r,t,e,n,i)=>{if(r===Vt.Get)return;let a=Ht(t.resolvedInputs,et.Payload,n);if(a&&Ft(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},We=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Vt.Get,o=await mr(r,t,e,n,a,p),c=yr(r,t,e,l,a),d=Wr(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${xr(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=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(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return B(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},xr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var vr=["collect","compute","mcp","state","mount","unmount"],Ar=new Set(Object.values(m)),Cr=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:Ar.has(r.slice(0,t))},Q=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 yt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return j(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),c=E(o,e),{action:d,index:h}=N(o),f=[],g=[];if(h===e-1){let I=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,I,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let y=g.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,x=this.getDestinationFromAction(c),C=y?this.serializer.stringToNative(y)[1]:x;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!vr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(c,g);v=v.map(I=>l.applyInputs(I,g,this.serializer));let T=g.find(I=>I.input.position==="value")?.value||null,A="value"in c?c.value:null,O=T?.split(u.ArgParamsSeparator)[1]||A||"0",V=l.applyInputs(O,g,this.serializer),$=BigInt(V),H=g.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),Ce=[...("transfers"in c?c.transfers:[])||[],...H||[]].map(I=>{let Ct=l.applyInputs(I,g,this.serializer),Pe=Ct.startsWith(`asset${u.ArgParamsSeparator}`)?Ct:`asset${u.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Pe)[1]}),be=g.find(I=>I.input.position==="data")?.value,we="data"in c?c.data||"":null,Ut=be||we||null,Ie=Ut?l.applyInputs(Ut,g,this.serializer):null,Dt={adapter:p,warp:o,chain:s,action:e,destination:C,args:v,value:$,transfers:Ce,data:Ie,resolvedInputs:g};return await this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Dt.resolvedInputs,ye.OneWeek),Dt}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||Cr(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let x=S(this.config,t);return x?this.serializer.nativeToString("address",x):null}if(c.source==="hidden"){if(c.default===void 0)return null;let x=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,x)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),y=f||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),p=new R(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=ot(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=ot(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ut(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Tt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=ot(p,o.decimals);return ce({...o,amount:c})}else return e}catch(n){throw b.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var xt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this.handlers=n,this.factory=new Q(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let f=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(f){let g=await new R(this.config,f,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:h}=N(t);for(let f=1;f<=t.actions.length;f++){let g=E(t,f);if(!Pt(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:x,chain:C,immediateExecution:v,executable:T}=await this.executeAction(t,f,e,y);if(x&&i.push(x),C&&(a=C),v&&s.push(v),v?.output){let{_DATA:A,...O}=v.output;Object.assign(d,O)}v?.values?.mapped&&Object.assign(d,v.values.mapped),T&&f===h+1&&T.resolvedInputs&&(p=j(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 f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):qt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=M(a.when,o);if(!k(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[y,x]of Object.entries(c.meta?.query||{}))h[y]=x.replace(/\{\{(.+?)\}\}/g,(C,v)=>{let T=d[v.trim()];return T==null?"":typeof T=="object"?JSON.stringify(T):String(T)});c.meta={...c.meta,query:h};let{immediateExecutions:f}=await this.execute(c,[],i),g=f[0];return g?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),{tx:null,chain:null,immediateExecution:g,executable:null}):{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Pt(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={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:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=br(c,d.output);return d.next=ct(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=S(this.config,t.chain.name),a=E(t.warp,t.action),s=this.factory.getSerializer(),p=_(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await Z(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=_(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new R(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await We(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));s&&(o=B(o,s)),b.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},y=await(await oe(this.adapters))(o,f);b.debug("Collect response status",{status:y.status});let x=await y.json();b.debug("Collect response content",{content:x});let{values:C,output:v}=await Z(t.warp,x,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),y.ok?"success":"error",C,v,x)}catch(f){b.error("WarpActionExecutor: Error executing collect",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs: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=E(t.warp,t.action);if(!i.destination){let f=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=j(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:g}}let p=this.factory.getSerializer(),l=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let y=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=y}),b.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:O})=>{if(O&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let V=A.position.replace("payload:",""),[$,H]=p.stringToNative(O);if($==="string")y[V]=String(H);else if($==="bool")y[V]=!!H;else if($==="uint8"||$==="uint16"||$==="uint32"||$==="uint64"||$==="uint128"||$==="uint256"||$==="biguint"){let rt=Number(H);y[V]=(Number.isInteger(rt),rt)}else y[V]=H}}),e&&Object.assign(y,e);let x=await g.callTool({name:d,arguments:y});await g.close();let C;if(x.content&&x.content.length>0){let A=x.content[0];if(A.type==="text")try{C=JSON.parse(A.text)}catch{C=A.text}else A.type,C=A}else C=x;let{values:v,output:T}=await Z(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",v,T,x)}catch(f){b.error("WarpExecutor: Error executing MCP",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=ct(this.config,this.adapters,t.warp,t.action,a,n),l=j(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:Et(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=M(s.when,h);try{if(!k(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),b.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=M(e.when,l);if(!k(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let x=o[y.trim()];return x!=null?String(x):h});c[d]=wr(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),O=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(O)}else{let{action:A}=N(o),O=this.factory.getStringTypedInputs(A,i),V=await this.factory.getResolvedInputs(s.name,A,O,l,a.queries);d=await this.factory.getModifiedInputs(V)}let h=ie(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=B(f,a.envs));let g=j(d),y=S(this.config,s.name),x=this.factory.getSerializer(),{values:C,output:v}=await ne(o,f,n,d,x,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f,c.expect);A&&(v.MESSAGE=A,c.as&&(v[c.as]=A))}let T=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:lt(this.config,this.adapters,o,n,v),values:C,output:v,messages:Et(o,{...C.mapped,...v},this.config),destination:T,resolvedInputs:g}}catch(s){return b.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:ct(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new R(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=M(e.when,h);return k(f)}},br=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},wr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var vt=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 b.error("WarpIndex: Error searching for warps: ",i),i}}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?X(t):F(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Kt(t):Xt(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(Ir(p,i.chain,l,i.identifier),p.meta.query=c?Zt(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new R(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return b.error("Error detecting warp link",a),n}}},Ir=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?St(null,"alias",e.alias):St(t,"hash",e?.hash??n))};var xe=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new nt(e));return new it(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new xt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new At(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},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=F(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");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??N(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=lt(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 Q(this.config,this.chains)}get index(){return new vt(this.config)}get linkBuilder(){return new G(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ft(this.config)}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 pt(t,this.config)}};var ve=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function fs(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(Ae(t,n)!==i)return!1;return!0}function gs(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?Ae(t,i):i;return e}function Ae(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{wt as BrowserCryptoProvider,Dr as CLOUD_WALLET_PROVIDERS,ye as CacheTtl,Fr as EvmWalletChainNames,Ur as MultiversxWalletChainNames,It as NodeCryptoProvider,gn as WARP_LANGUAGES,P as WarpAssets,ue as WarpBrandBuilder,ft as WarpBuilder,yt as WarpCache,Wt as WarpCacheKey,je as WarpChainDisplayNames,Le as WarpChainLogos,Be as WarpChainName,nt as WarpChainResolver,xe as WarpClient,it as WarpCompositeResolver,U as WarpConfig,u as WarpConstants,xt as WarpExecutor,Q as WarpFactory,vt as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,G as WarpLinkBuilder,At as WarpLinkDetecter,b as WarpLogger,Mt as WarpPlatformName,kt as WarpPlatforms,z as WarpProtocolVersions,w as WarpSerializer,ve as WarpTypeRegistry,dt as WarpValidator,$i as address,Et as applyOutputToMessages,ce as asset,Ei as biguint,Ri as bool,nr as buildGeneratedFallbackWarpIdentifier,si as buildGeneratedSourceWarpIdentifier,ut as buildInputsContext,_ as buildMappedOutput,Ge as buildNestedPayload,en as bytesToBase64,Ve as bytesToHex,hi as checkWarpAssetBalance,K as cleanWarpIdentifier,Ot as createAuthHeaders,Nt as createAuthMessage,nn as createCryptoProvider,di as createDefaultWalletProvider,ri as createHttpAuthHeaders,Ye as createSignableMessage,mn as createWarpI18nText,St as createWarpIdentifier,dn as doesWarpRequireWallet,re as evaluateOutputCommon,k as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,ne as extractPromptOutput,Xt as extractQueryStringFromIdentifier,Kt as extractQueryStringFromUrl,j as extractResolvedInputValues,on as extractWarpSecrets,W as findWarpAdapterForChain,_r as getChainDisplayName,Jr as getChainLogo,zt as getCryptoProvider,tr as getGeneratedSourceWarpName,st as getLatestProtocolIdentifier,oe as getMppFetch,lt as getNextInfo,ct as getNextInfoForStatus,Zn as getProviderConfig,Gt as getRandomBytes,_t as getRandomHex,ir as getRequiredAssetIds,Er as getWalletFromConfigOrFail,E as getWarpActionByIndex,Kr as getWarpBrandLogoUrl,Xr as getWarpChainAssetLogoUrl,Zr as getWarpChainInfoLogoUrl,Cn as getWarpIdentifierWithQuery,F as getWarpInfoFromIdentifier,N as getWarpInputAction,Se as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,Re as getWarpWalletExternalId,$e as getWarpWalletExternalIdFromConfig,Nr as getWarpWalletExternalIdFromConfigOrFail,Ee as getWarpWalletMnemonic,$r as getWarpWalletMnemonicFromConfig,Te as getWarpWalletPrivateKey,Rr as getWarpWalletPrivateKeyFromConfig,In as hasInputPrefix,Ni as hex,ci as initializeWalletCache,vn as isEqualWarpIdentifier,pi as isGeneratedSourcePrivateIdentifier,Ze as isPlatformValue,Pt as isWarpActionAutoExecute,hn as isWarpI18nText,Or as isWarpWalletReadOnly,fs as matchesTrigger,te as mergeNestedPayload,Lr as normalizeAndValidateMnemonic,Ne as normalizeMnemonic,Oi as option,Xe as parseOutputOutIndex,ii as parseSignedMessage,Zt as parseWarpQueryStringToObject,An as removeWarpChainPrefix,jr as removeWarpWalletFromConfig,B as replacePlaceholders,M as replacePlaceholdersInWhenExpression,gs as resolveInputs,Fn as resolveNextString,$t as resolveNextStrings,Ae as resolvePath,ie as resolvePlatformValue,pt as resolveWarpText,qt as safeWindow,tn as setCryptoProvider,Br as setWarpWalletInConfig,ot as shiftBigintBy,Tt as splitInput,oi as stampGeneratedWarpMeta,wi as string,ji as struct,rn as testCryptoAvailability,_e as toInputPayloadValue,Jt as toPreviewText,Bi as tuple,Pi as uint16,Si as uint32,Ti as uint64,Ii as uint8,Oe as validateMnemonicLength,ni as validateSignedMessage,Li as vector,zr as withAdapterFallback};
|
|
1
|
+
var nt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var it=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Nr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Te=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>Te(r.user?.wallets?.[t]||null),Ee=r=>r?typeof r=="string"?r:r.privateKey||null:null,Re=r=>r?typeof r=="string"?r:r.mnemonic||null:null,$e=r=>r?typeof r=="string"?r:r.externalId||null:null,Or=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Br=(r,t)=>Re(r.user?.wallets?.[t]||null)?.trim()||null,Ne=(r,t)=>$e(r.user?.wallets?.[t]||null)?.trim()||null,jr=(r,t)=>{let e=Ne(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Lr=r=>typeof r=="string",Vr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Hr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Oe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Be=(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`)},Fr=(r,t=24)=>{let e=Oe(r);return Be(e,t),e};var je=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(je||{}),kt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(kt||{}),Mt=Object.values(kt),kr=["ethereum","base","arbitrum","polygon","somnia","tempo"],Mr=["multiversx","claws"],qr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:";",Append:{Prefix:"append:"},Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},qt=typeof window<"u"?window:{open:()=>{}};var z={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${z.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${z.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","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 Jr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var at="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",P={baseUrl:at,chainLogo:r=>`${at}/chains/logos/${r}`,tokenLogo:r=>`${at}/tokens/logos/${r}`,walletLogo:r=>`${at}/wallets/logos/${r}`},Le={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Kr=r=>Le[r]??r.charAt(0).toUpperCase()+r.slice(1),Ve={ethereum:{light:P.chainLogo("ethereum-white.svg"),dark:P.chainLogo("ethereum-black.svg")},base:{light:P.chainLogo("base-white.svg"),dark:P.chainLogo("base-black.svg")},arbitrum:P.chainLogo("arbitrum.svg"),polygon:P.chainLogo("polygon.svg"),somnia:P.chainLogo("somnia.png"),tempo:{light:P.chainLogo("tempo-white.svg"),dark:P.chainLogo("tempo-black.svg")},multiversx:P.chainLogo("multiversx.svg"),claws:P.chainLogo("claws.png"),sui:P.chainLogo("sui.svg"),solana:P.chainLogo("solana.svg"),near:{light:P.chainLogo("near-white.svg"),dark:P.chainLogo("near-black.svg")},fastset:{light:P.chainLogo("fastset-white.svg"),dark:P.chainLogo("fastset-black.svg")}},Xr=(r,t="dark")=>{let e=Ve[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var bt=(r,t)=>r[t]??r.default??Object.values(r)[0],Yr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:bt(r.logo,e)},tn=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return bt(r.logoUrl,e)},en=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return bt(r.logoUrl,e)};var wt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},It=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},D=null;function zt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new wt,D;if(typeof process<"u"&&process.versions?.node)return D=new It,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function nn(r){D=r}async function _t(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||zt()).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 an(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 Gt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await _t(r/2,t);return He(e)}async function sn(){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 _t(16),r.randomBytes=!0}catch{}return r}function on(){return zt()}var cn=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var W=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},st=r=>{if(r==="warp")return`warp:${z.Warp}`;if(r==="brand")return`brand:${z.Brand}`;if(r==="abi")return`abi:${z.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Fe=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Fe.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},Pt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,ot=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Jt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},B=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),k=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),hn=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},M=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 yn={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"},pt=(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""},Wn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,xn=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,bn=(r,t)=>!r||!t?!1:K(r)===K(t),St=(r,t,e)=>{let n=K(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},F=r=>{let t=decodeURIComponent(r).trim(),e=K(t),n=e.split("?")[0],i=Qt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=Ue(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},X=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return F(i)},Ue=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,De=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Qt=r=>{let t=De(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Qt(a);return[i,...s]},Kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Xt=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},wn=r=>{let t=F(r);return(t?t.identifierBase:K(r)).trim()},In=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 Tt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Tn=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Tt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=pt(a,e);return[i,B(s,t)]});return Object.fromEntries(n)};import ke from"qr-code-styling";var _=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=F(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return U.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new ke({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 Me="https://",qe=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=k(r.when,t);if(!M(e))return null}return r.identifier},ze=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),$t=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(ze(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=qe(a,e);s!==null&&i.push(s)}return i.length>0?i:null},kn=(r,t,e)=>$t(r,t,e)?.[0]??null,Yt=(r,t,e,n,i)=>{if(n.startsWith(Me))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=B(a,{...e.vars,...i});return[{identifier:f,url:Rt(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=B(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Rt(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:f,field:y?y.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:x,field:C}of h){let v=C?_e(f,C):f;if(v==null)return null;g=g.replace(x,v)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Rt(t,y,r)}}).filter(f=>f!==null)},lt=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=$t(a,"success",i);if(!s)return null;let p=s.flatMap(l=>Yt(r,t,e,l,i));return p.length>0?p:null},ct=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=E(e,n)?.next||e.next||null,l=$t(p,s,i);if(!l)return null;let o=l.flatMap(c=>Yt(r,t,e,c,i));return o.length>0?o:null},Rt=(r,t,e)=>{let[n,i]=t.split("?"),a=new _(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},_e=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var q=class q{static debug(...t){q.isTestEnv||console.debug(...t)}static info(...t){q.isTestEnv||console.info(...t)}static warn(...t){q.isTestEnv||console.warn(...t)}static error(...t){q.isTestEnv||console.error(...t)}};q.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var b=q;function Ge(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function te(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]=te(e[n],t[n]):e[n]=t[n]}),e}function Je(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 j(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Je(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ge(n.input.position,i,a);e=te(e,s)}else e[i]=a}),e}function ut(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var ee=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=Ye(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=ee(r,e,p),d=G(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await re(r,c,t,e,n,i,a)}},re=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Qe(p,r,n,i,a),p=await Ke(r,p,e,i,a,s.transform?.runner||null),p},Qe=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ke=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Xe(e),inputs:ut(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){b.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Xe=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},ne=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=ee(r,e,s),c=await re(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:G(n,i)},output:c}},Ze=(r,t)=>{let e=r.split(".");return e[0]!=="out"?r:e.length===1?t:e.slice(1).reduce((n,i)=>n&&n[i]!==void 0?n[i]:null,t)},ie=(r,t,e)=>{if(!r.output)return t.output;let n={...t.output||{},...t.values?.mapped||{}},i={};for(let[a,s]of Object.entries(r.output)){let p=s.startsWith(u.Append.Prefix),l=p?s.slice(u.Append.Prefix.length):s,o=Ze(l,n);if(p){let c=e?.[a],d=Array.isArray(c)?c:c!==void 0?[c]:[];i[a]=[...d,o]}else i[a]=o}return{...t.output,...i}},Ye=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 tr=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Mt.some(t=>t in r),ae=(r,t)=>{if(!tr(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 ei=(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 er(r,t,e,n=5){let i=await Gt(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 Nt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return er(r,i,e,5)}function Ot(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function ai(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Nt(r,e,n),p=await t(i);return Ot(r,p,a,s)}function si(r){let t=new Date(r).getTime();return Date.now()<t}function oi(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 rr=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",nr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),se=(r,t=24)=>{let e=nr(r);return e?e.slice(0,t):"action"},oe=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)},ir=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()}},li=(r,t,e)=>{let n=se((e||t||"").trim()||"action"),i=`${r.type}|${ir(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=oe(i);return`private_src_${n}_${a}`},ar=r=>{let t=rr(r),e=se(t),n=oe(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ci=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||ar(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ui=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function fi(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 hi(r,t,e){return null}var sr=(r,t)=>{let e=null;try{e=N(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Wi=async(r,t,e,n)=>{try{let i=W(e,n),a=sr(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as or,tempo as pr}from"mppx/client";async function pe(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return b.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),or.create({methods:[pr({account:e})],polyfill:!1}).fetch}return fetch}var lr=r=>{try{return JSON.parse(r)}catch{return null}},le=/^(.+)\[\]$/,ce={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=ce[t]??t,le.test(t)){let n=typeof e=="string"?lr(e):null;return t+u.ArgParamsSeparator+JSON.stringify(n??e)}if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(m.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(m.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=ce[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(le.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.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.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Si=r=>new w().nativeToString(m.String,r),Ti=r=>new w().nativeToString(m.Uint8,r),Ei=r=>new w().nativeToString(m.Uint16,r),Ri=r=>new w().nativeToString(m.Uint32,r),$i=r=>new w().nativeToString(m.Uint64,r),Ni=r=>new w().nativeToString(m.Biguint,r),Oi=r=>new w().nativeToString(m.Bool,r),Bi=r=>new w().nativeToString(m.Address,r),ue=r=>new w().nativeToString(m.Asset,r),ji=r=>new w().nativeToString(m.Hex,r),Li=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Vi=(...r)=>new w().nativeToString(m.Tuple,r),Hi=r=>new w().nativeToString(m.Struct,r),Fi=r=>new w().nativeToString(m.Vector,r);import cr from"ajv";var de=class{constructor(t){this.pendingBrand={protocol:st("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 cr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import dr from"ajv";var fe={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{type:"string"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},output:{additionalProperties:{type:"string"},type:"object"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var fr=new Set(["POST","PUT","PATCH","DELETE"]),gr=/^[A-Z][A-Z0-9_]*$/,dt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=N(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||gr.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!fr.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():fe,n=new dr({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ft=class{constructor(t){this.config=t;this.pendingWarp={protocol:st("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Jt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new dt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};import{existsSync as jt,mkdirSync as hr,readdirSync as ge,readFileSync as mr,unlinkSync as Lt,writeFileSync as yr}from"fs";import{join as he,resolve as me}from"path";var Bt="$bigint:",gt=(r,t)=>typeof t=="bigint"?Bt+t.toString():t,J=(r,t)=>typeof t=="string"&&t.startsWith(Bt)?BigInt(t.slice(Bt.length)):t;var ht=class{constructor(t,e){let n=e?.path;this.cacheDir=n?me(n):me(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){jt(this.cacheDir)||hr(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return he(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!jt(e))return null;let n=mr(e,"utf-8"),i=JSON.parse(n,J);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Lt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);yr(a,JSON.stringify(i,gt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);jt(e)&&Lt(e)}catch{}}async keys(t){try{let e=ge(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{ge(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Lt(he(this.cacheDir,e))})}catch{}}};var Y=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,J);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,gt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{constructor(t,e){}async get(t){let e=L.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;L.cache.set(t,{value:e,expiresAt:i})}async delete(t){L.cache.delete(t)}async keys(t){let e=Array.from(L.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){L.cache.clear()}};L.cache=new Map;var tt=L;import{readFileSync as Wr}from"fs";import{resolve as ye}from"path";var mt=class{constructor(t,e){let n=e?.path?ye(e.path):ye(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=Wr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,J)))}catch(e){return b.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var We={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},yt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new mt(t,e):e?.type==="filesystem"?new ht(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Vt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ht=(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)},Ft=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:l,nonce:o,expiresAt:c}=await Nt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Ot(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=Ht(e.resolvedInputs,et.Headers,i);if(p){let l=Ft(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},vr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Vt.Get){let s=Ht(e.resolvedInputs,et.Queries,i);if(s){let p=Ft(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},Ar=(r,t,e,n,i)=>{if(r===Vt.Get)return;let a=Ht(t.resolvedInputs,et.Payload,n);if(a&&Ft(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},xe=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Vt.Get,o=await xr(r,t,e,n,a,p),c=vr(r,t,e,l,a),d=Ar(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Cr(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=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(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return B(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},Cr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var br=["collect","compute","mcp","state","mount","unmount"],wr=new Set(Object.values(m)),Ir=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:wr.has(r.slice(0,t))},Q=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 yt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return j(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),c=E(o,e),{action:d,index:h}=N(o),f=[],g=[];if(h===e-1){let I=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,I,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let y=g.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,x=this.getDestinationFromAction(c),C=y?this.serializer.stringToNative(y)[1]:x;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!br.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(c,g);v=v.map(I=>l.applyInputs(I,g,this.serializer));let T=g.find(I=>I.input.position==="value")?.value||null,A="value"in c?c.value:null,O=T?.split(u.ArgParamsSeparator)[1]||A||"0",V=l.applyInputs(O,g,this.serializer),$=BigInt(V),H=g.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),be=[...("transfers"in c?c.transfers:[])||[],...H||[]].map(I=>{let Ct=l.applyInputs(I,g,this.serializer),Se=Ct.startsWith(`asset${u.ArgParamsSeparator}`)?Ct:`asset${u.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Se)[1]}),we=g.find(I=>I.input.position==="data")?.value,Ie="data"in c?c.data||"":null,Ut=we||Ie||null,Pe=Ut?l.applyInputs(Ut,g,this.serializer):null,Dt={adapter:p,warp:o,chain:s,action:e,destination:C,args:v,value:$,transfers:be,data:Pe,resolvedInputs:g};return await this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Dt.resolvedInputs,We.OneWeek),Dt}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||Ir(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let x=S(this.config,t);return x?this.serializer.nativeToString("address",x):null}if(c.source==="hidden"){if(c.default===void 0)return null;let x=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,x)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),y=f||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),p=new R(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=ot(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=ot(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ut(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Tt(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=ot(p,o.decimals);return ue({...o,amount:c})}else return e}catch(n){throw b.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var xt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this.handlers=n,this.factory=new Q(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let f=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(f){let g=await new R(this.config,f,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:h}=N(t);for(let f=1;f<=t.actions.length;f++){let g=E(t,f);if(!Pt(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:x,chain:C,immediateExecution:v,executable:T}=await this.executeAction(t,f,e,y);if(x&&i.push(x),C&&(a=C),v&&s.push(v),v?.output){let{_DATA:A,...O}=v.output;Object.assign(d,O)}v?.values?.mapped&&Object.assign(d,v.values.mapped),T&&f===h+1&&T.resolvedInputs&&(p=j(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 f=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(f))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):qt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=k(a.when,o);if(!M(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[y,x]of Object.entries(c.meta?.query||{}))h[y]=x.replace(/\{\{(.+?)\}\}/g,(C,v)=>{let T=d[v.trim()];return T==null?"":typeof T=="object"?JSON.stringify(T):String(T)});c.meta={...c.meta,query:h};let{immediateExecutions:f}=await this.execute(c,[],i),g=f[0];if(g){if(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),o.output){let y=ie(o,g,i.envs);return{tx:null,chain:null,immediateExecution:{...g,output:y},executable:null}}return{tx:null,chain:null,immediateExecution:g,executable:null}}return{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Pt(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={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:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=Pr(c,d.output);return d.next=ct(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=S(this.config,t.chain.name),a=E(t.warp,t.action),s=this.factory.getSerializer(),p=G(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await Z(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=S(this.config,t.chain.name),n=this.factory.getSerializer(),i=G(t.resolvedInputs,n),{values:a,output:s}=await Z(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new R(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await xe(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));s&&(o=B(o,s)),b.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},y=await(await pe(this.adapters))(o,f);b.debug("Collect response status",{status:y.status});let x=await y.json();b.debug("Collect response content",{content:x});let{values:C,output:v}=await Z(t.warp,x,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),y.ok?"success":"error",C,v,x)}catch(f){b.error("WarpActionExecutor: Error executing collect",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs: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=E(t.warp,t.action);if(!i.destination){let f=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=j(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:g}}let p=this.factory.getSerializer(),l=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let y=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=y}),b.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let y={};t.resolvedInputs.forEach(({input:A,value:O})=>{if(O&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let V=A.position.replace("payload:",""),[$,H]=p.stringToNative(O);if($==="string")y[V]=String(H);else if($==="bool")y[V]=!!H;else if($==="uint8"||$==="uint16"||$==="uint32"||$==="uint64"||$==="uint128"||$==="uint256"||$==="biguint"){let rt=Number(H);y[V]=(Number.isInteger(rt),rt)}else y[V]=H}}),e&&Object.assign(y,e);let x=await g.callTool({name:d,arguments:y});await g.close();let C;if(x.content&&x.content.length>0){let A=x.content[0];if(A.type==="text")try{C=JSON.parse(A.text)}catch{C=A.text}else A.type,C=A}else C=x;let{values:v,output:T}=await Z(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",v,T,x)}catch(f){b.error("WarpExecutor: Error executing MCP",f);let g=j(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=ct(this.config,this.adapters,t.warp,t.action,a,n),l=j(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:Et(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=k(s.when,h);try{if(!M(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),b.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=k(e.when,l);if(!M(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let x=o[y.trim()];return x!=null?String(x):h});c[d]=Sr(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),O=await this.factory.getResolvedInputs(s.name,e,A,l,a.queries);d=await this.factory.getModifiedInputs(O)}else{let{action:A}=N(o),O=this.factory.getStringTypedInputs(A,i),V=await this.factory.getResolvedInputs(s.name,A,O,l,a.queries);d=await this.factory.getModifiedInputs(V)}let h=ae(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=B(f,a.envs));let g=j(d),y=S(this.config,s.name),x=this.factory.getSerializer(),{values:C,output:v}=await ne(o,f,n,d,x,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(f,c.expect);A&&(v.MESSAGE=A,c.as&&(v[c.as]=A))}let T=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:lt(this.config,this.adapters,o,n,v),values:C,output:v,messages:Et(o,{...C.mapped,...v},this.config),destination:T,resolvedInputs:g}}catch(s){return b.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:ct(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new R(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=k(e.when,h);return M(f)}},Pr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},Sr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var vt=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 b.error("WarpIndex: Error searching for warps: ",i),i}}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?X(t):F(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Kt(t):Xt(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);l=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);l=y.registryInfo,o=y.brand,y.registryInfo&&(p=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(p&&p.meta&&(Tr(p,i.chain,l,i.identifier),p.meta.query=c?Zt(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new R(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return b.error("Error detecting warp link",a),n}}},Tr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?St(null,"alias",e.alias):St(t,"hash",e?.hash??n))};var ve=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new nt(e));return new it(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new xt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new At(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},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=F(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");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??N(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=lt(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 Q(this.config,this.chains)}get index(){return new vt(this.config)}get linkBuilder(){return new _(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ft(this.config)}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 pt(t,this.config)}};var Ae=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function ms(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(Ce(t,n)!==i)return!1;return!0}function ys(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?Ce(t,i):i;return e}function Ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{wt as BrowserCryptoProvider,qr as CLOUD_WALLET_PROVIDERS,We as CacheTtl,kr as EvmWalletChainNames,Mr as MultiversxWalletChainNames,It as NodeCryptoProvider,yn as WARP_LANGUAGES,P as WarpAssets,de as WarpBrandBuilder,ft as WarpBuilder,yt as WarpCache,Wt as WarpCacheKey,Le as WarpChainDisplayNames,Ve as WarpChainLogos,je as WarpChainName,nt as WarpChainResolver,ve as WarpClient,it as WarpCompositeResolver,U as WarpConfig,u as WarpConstants,xt as WarpExecutor,Q as WarpFactory,vt as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,_ as WarpLinkBuilder,At as WarpLinkDetecter,b as WarpLogger,kt as WarpPlatformName,Mt as WarpPlatforms,z as WarpProtocolVersions,w as WarpSerializer,Ae as WarpTypeRegistry,dt as WarpValidator,Bi as address,Et as applyOutputToMessages,ue as asset,Ni as biguint,Oi as bool,ar as buildGeneratedFallbackWarpIdentifier,li as buildGeneratedSourceWarpIdentifier,ut as buildInputsContext,G as buildMappedOutput,Ge as buildNestedPayload,an as bytesToBase64,He as bytesToHex,Wi as checkWarpAssetBalance,K as cleanWarpIdentifier,Ot as createAuthHeaders,Nt as createAuthMessage,on as createCryptoProvider,hi as createDefaultWalletProvider,ai as createHttpAuthHeaders,er as createSignableMessage,xn as createWarpI18nText,St as createWarpIdentifier,hn as doesWarpRequireWallet,re as evaluateOutputCommon,M as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,ie as extractInlineOutput,ne as extractPromptOutput,Xt as extractQueryStringFromIdentifier,Kt as extractQueryStringFromUrl,j as extractResolvedInputValues,cn as extractWarpSecrets,W as findWarpAdapterForChain,Kr as getChainDisplayName,Xr as getChainLogo,zt as getCryptoProvider,rr as getGeneratedSourceWarpName,st as getLatestProtocolIdentifier,pe as getMppFetch,lt as getNextInfo,ct as getNextInfoForStatus,ei as getProviderConfig,_t as getRandomBytes,Gt as getRandomHex,sr as getRequiredAssetIds,Nr as getWalletFromConfigOrFail,E as getWarpActionByIndex,Yr as getWarpBrandLogoUrl,tn as getWarpChainAssetLogoUrl,en as getWarpChainInfoLogoUrl,In as getWarpIdentifierWithQuery,F as getWarpInfoFromIdentifier,N as getWarpInputAction,Te as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,$e as getWarpWalletExternalId,Ne as getWarpWalletExternalIdFromConfig,jr as getWarpWalletExternalIdFromConfigOrFail,Re as getWarpWalletMnemonic,Br as getWarpWalletMnemonicFromConfig,Ee as getWarpWalletPrivateKey,Or as getWarpWalletPrivateKeyFromConfig,Tn as hasInputPrefix,ji as hex,fi as initializeWalletCache,bn as isEqualWarpIdentifier,ui as isGeneratedSourcePrivateIdentifier,tr as isPlatformValue,Pt as isWarpActionAutoExecute,Wn as isWarpI18nText,Lr as isWarpWalletReadOnly,ms as matchesTrigger,te as mergeNestedPayload,Fr as normalizeAndValidateMnemonic,Oe as normalizeMnemonic,Li as option,Ye as parseOutputOutIndex,oi as parseSignedMessage,Zt as parseWarpQueryStringToObject,wn as removeWarpChainPrefix,Hr as removeWarpWalletFromConfig,B as replacePlaceholders,k as replacePlaceholdersInWhenExpression,ys as resolveInputs,kn as resolveNextString,$t as resolveNextStrings,Ce as resolvePath,ae as resolvePlatformValue,pt as resolveWarpText,qt as safeWindow,nn as setCryptoProvider,Vr as setWarpWalletInConfig,ot as shiftBigintBy,Tt as splitInput,ci as stampGeneratedWarpMeta,Si as string,Hi as struct,sn as testCryptoAvailability,Je as toInputPayloadValue,Jt as toPreviewText,Vi as tuple,Ei as uint16,Ri as uint32,$i as uint64,Ti as uint8,Be as validateMnemonicLength,si as validateSignedMessage,Fi as vector,Jr as withAdapterFallback};
|