import { C as getWalletAccountsFromState, I as setCookie, M as emitEvent, S as getWalletAccounts, Z as isCookieEnabled, a as DYNAMIC_WAAS_METADATA, g as DYNAMIC_AUTH_COOKIE_NAME, lt as getCore, n as isWaasWalletProvider, o as isUserMissingMfaAuth, t as InvalidParamError, w as formatWalletProviderKey, x as NoWalletProviderFoundError, y as getWalletProviderRegistry } from "./InvalidParamError-DZjc7Tjc.esm.js";
import { WalletProviderEnum } from "@dynamic-labs/sdk-api-core";

//#region src/modules/wallets/emitWalletAccountsChangedEvent/emitWalletAccountsChangedEvent.ts
/**
* Emits the `walletAccountsChanged` event.
* @notInstrumented
*/
const emitWalletAccountsChangedEvent = (client) => {
	emitEvent({
		args: { walletAccounts: getWalletAccounts(client) },
		event: "walletAccountsChanged"
	}, client);
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent/checkAndRaiseWalletAccountsChangedEvent.ts
/** @notInstrumented */
const checkAndRaiseWalletAccountsChangedEvent = ({ previousState }, client) => {
	const core = getCore(client);
	if (getWalletAccountsHash(previousState, client) !== getWalletAccountsHash(core.state.get(), client)) emitWalletAccountsChangedEvent(client);
};
const getWalletAccountsHash = (state, client) => getWalletAccountsFromState(state, client).map((walletAccount) => JSON.stringify(walletAccount)).sort().join("-");

//#endregion
//#region src/modules/wallets/getWalletProviders/getWalletProviders.ts
/**
* Get all available wallet providers to interact with internally.
* @notInstrumented
*/
const getWalletProviders = (client) => {
	return getWalletProviderRegistry(client).listProviders();
};

//#endregion
//#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
/** @notInstrumented */
const findWaasWalletProviderByChain = ({ chain }, client) => {
	const providers = getWalletProviders(client);
	const waasProviderKey = formatWalletProviderKey({
		chain,
		displayName: DYNAMIC_WAAS_METADATA.displayName,
		walletProviderType: WalletProviderEnum.EmbeddedWallet
	});
	const waasProvider = providers.find((provider) => provider.key === waasProviderKey && provider.chain === chain);
	if (!waasProvider || !isWaasWalletProvider(waasProvider)) return null;
	return waasProvider;
};

//#endregion
//#region src/modules/waas/isWaasWalletAccount/isWaasWalletAccount.ts
/**
* This function determines whether the provided wallet account is a Dynamic
* WaaS wallet account.
*
* @param params.walletAccount - The wallet account to check.
* @returns True if the wallet account is a WaaS wallet account, false otherwise.
* @notInstrumented
*/
const isWaasWalletAccount = ({ walletAccount }) => {
	return walletAccount.walletProviderKey.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
};

//#endregion
//#region src/modules/waas/initializeWaasClientsForEagerRecovery/initializeWaasClientsForEagerRecovery.ts
/**
* On login, boots the WaaS client once per chain so the SDK eagerly recovers
* key shares itself (the `eagerlyRecoverKeyShares` capability) instead of the
* host looping per wallet. Booting calls `initialize()`, which sends the auth
* token the iframe needs to self-recover.
*
* @notInstrumented
*/
const initializeWaasClientsForEagerRecovery = async (client) => {
	/**
	* Booting triggers recovery, which fails if the user is missing the MFA auth.
	* This early return avoids attempting a call we know will fail and just adds
	* noise to the logs.
	*/
	if (isUserMissingMfaAuth(client)) return;
	const waasChains = new Set(getWalletAccounts(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount })).map((walletAccount) => walletAccount.chain));
	await Promise.all([...waasChains].map(async (chain) => {
		const provider = findWaasWalletProviderByChain({ chain }, client);
		/**
		* The environment might not have the embedded wallet extensions installed.
		* In that case there is no provider for the chain and nothing to boot.
		*/
		if (!provider) return;
		try {
			await provider.getWaasClient();
		} catch (error) {
			getCore(client).logger.warn("[initializeWaasClientsForEagerRecovery] failed to boot waas client", error);
		}
	}));
};

//#endregion
//#region src/modules/auth/decodeJwt/decodeJwt.ts
/**
* Decodes a JWT token and returns the full payload.
*
* This function extracts and returns the complete JWT payload including scopes,
* expiration time, and other claims.
*
* @param jwt - The JWT token string.
* @returns The decoded JWT payload object.
* @throws InvalidParamError if the token is invalid or cannot be decoded.
*
* @example
* ```typescript
* const payload = decodeJwt(jwt);
* // Returns: { scopes: ['wallet:export'], exp: 1234567890, ... }
* ```
* @notInstrumented
*/
const decodeJwt = (jwt) => {
	try {
		const parts = jwt.split(".");
		if (parts.length !== 3) throw new InvalidParamError("Invalid JWT format");
		const base64Payload = parts[1].replaceAll("-", "+").replaceAll("_", "/");
		const paddedPayload = base64Payload + "=".repeat((4 - base64Payload.length % 4) % 4);
		const decodedPayload = atob(paddedPayload);
		return JSON.parse(decodedPayload);
	} catch (error) {
		if (error instanceof InvalidParamError) throw error;
		throw new InvalidParamError(`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`);
	}
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.ts
/**
* Normalizes scopes by deduplicating and sorting them.
* This creates a canonical representation for comparison.
*
* @param scopes - Array of scope strings (may contain duplicates)
* @returns Normalized, sorted array of unique scopes
* @notInstrumented
*/
const normalizeScopes = (scopes) => {
	return [...new Set(scopes)].sort((a, b) => a.localeCompare(b));
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.ts
/**
* Validates and parses an elevated access token from a JWT string.
* Extracts scopes, expiration, and validates the token structure.
*
* Policy decisions:
* - Tokens without scopes are rejected (returns null)
* - Tokens with empty scopes array are rejected (returns null)
* - Tokens without exp field are rejected (returns null)
* - Expired tokens are rejected (returns null)
*
* @returns Parsed token data or null if token is invalid/expired
* @notInstrumented
*/
const parseElevatedAccessToken = ({ token }) => {
	const payload = decodeJwt(token);
	const filteredScopes = ((payload?.scope)?.split(" ") ?? []).filter((s) => s.length > 0);
	const singleUse = payload.singleUse ?? false;
	if (!filteredScopes || filteredScopes.length === 0) return null;
	if (!payload.exp) return null;
	const expiresAt = /* @__PURE__ */ new Date(payload.exp * 1e3);
	if (expiresAt <= /* @__PURE__ */ new Date()) return null;
	return {
		expiresAt,
		normalizedScopes: normalizeScopes(filteredScopes),
		scopes: filteredScopes,
		singleUse,
		token
	};
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken/upsertElevatedAccessToken.ts
/**
* Upserts an elevated access token into the current tokens array.
*
* Policy: Only one token per normalized scope-set is allowed.
* If a token with the same normalized scopes exists, it is replaced.
* This ensures we don't accumulate multiple tokens for the same scope combination.
*
* @param currentTokens - Current array of elevated access tokens
* @param newToken - New token to upsert
* @returns Updated array of tokens with the new token upserted
* @notInstrumented
*/
const upsertElevatedAccessToken = ({ currentTokens, newToken }) => {
	const newScopeKey = normalizeScopes(newToken.scopes).join(" ");
	return [...currentTokens.filter((existingToken) => {
		return normalizeScopes(existingToken.scopes).join(" ") !== newScopeKey;
	}), {
		expiresAt: newToken.expiresAt,
		scopes: newToken.scopes,
		singleUse: newToken.singleUse,
		token: newToken.token
	}];
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.ts
/** @notInstrumented */
const updateAuthFromVerifyResponse = ({ response }, client) => {
	const core = getCore(client);
	const previousState = { ...core.state.get() };
	const { user, minifiedJwt, jwt, expiresAt, mfaToken, elevatedAccessToken } = response;
	const sessionExpiresAt = /* @__PURE__ */ new Date(expiresAt * 1e3);
	const newState = {
		legacyToken: jwt ?? null,
		sessionExpiresAt,
		token: minifiedJwt ?? null,
		user
	};
	if (mfaToken) newState.mfaToken = mfaToken;
	const currentTokens = core.state.get().elevatedAccessTokens || [];
	newState.elevatedAccessTokens = currentTokens;
	if (elevatedAccessToken) {
		const parsedToken = parseElevatedAccessToken({ token: elevatedAccessToken });
		if (parsedToken) newState.elevatedAccessTokens = upsertElevatedAccessToken({
			currentTokens,
			newToken: parsedToken
		});
	}
	core.state.set(newState);
	/**
	* For customers using a sandbox environment with cookies enabled, we need to set the cookie
	* programmatically because Redcoast won't set the cookie via headers. We set the cookie programmatically
	* so customers can access the cookie from document.cookie consistently between sandbox and live environments.
	*/
	if (minifiedJwt && isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax`);
	checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
	if (!previousState.user && Boolean(newState.user)) initializeWaasClientsForEagerRecovery(client);
};

//#endregion
//#region src/modules/wallets/utils/getVerifiedCredentialForWalletAccount/getVerifiedCredentialForWalletAccount.ts
/** @notInstrumented */
const getVerifiedCredentialForWalletAccount = ({ walletAccount }, client) => {
	return client.user?.verifiedCredentials.find((vc) => vc.id === walletAccount.verifiedCredentialId);
};

//#endregion
//#region src/modules/wallets/getWalletProviderByKey/getWalletProviderByKey.ts
/** @notInstrumented */
const getWalletProviderByKey = ({ walletProviderKey }, client) => {
	const walletProvider = getWalletProviders(client).find((walletProvider$1) => walletProvider$1.key === walletProviderKey);
	if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey });
	return walletProvider;
};

//#endregion
export { parseElevatedAccessToken as a, findWaasWalletProviderByChain as c, emitWalletAccountsChangedEvent as d, upsertElevatedAccessToken as i, getWalletProviders as l, getVerifiedCredentialForWalletAccount as n, initializeWaasClientsForEagerRecovery as o, updateAuthFromVerifyResponse as r, isWaasWalletAccount as s, getWalletProviderByKey as t, checkAndRaiseWalletAccountsChangedEvent as u };
//# sourceMappingURL=getWalletProviderByKey-DWYF9IxH.esm.js.map