'use strict';

/**
 * The authentication methods we support through our UI.
 * Currently we support `emailMagicLinks`, `emailOtp`, `sso`, `passwords`, and `oauth`.
 */ const AuthFlowType = {
    Discovery: 'Discovery',
    Organization: 'Organization',
    PasswordReset: 'PasswordReset'
};
const RedirectURLType = {
    ResetPassword: 'reset_password'
};
/**
 * The OAuth providers we support in our B2B OAuth product.
 */ const B2BOAuthProviders = {
    Google: 'google',
    Microsoft: 'microsoft',
    HubSpot: 'hubspot',
    Slack: 'slack',
    GitHub: 'github'
};
const B2BMFAProducts = {
    smsOtp: 'smsOtp',
    totp: 'totp'
};

/* eslint-disable @typescript-eslint/no-explicit-any */ /**
 * An Error class thrown when the SDK is unable to reach the Stytch servers,
 * or when the Stytch servers return a value the SDK cannot understand.
 * Usually - it means that you're offline!
 */ class SDKAPIUnreachableError extends Error {
    details;
    constructor(message, details){
        super(message + '\n' + details);
        this.message = message + '\n' + details;
        this.name = 'SDKAPIUnreachableError';
        this.details = details;
        Object.setPrototypeOf(this, SDKAPIUnreachableError.prototype);
    }
}
/**
 * An Error class thrown when the provided input fails client-side validation -
 * for example if a field that was expected to be a number is instead a string.
 */ class StytchSDKUsageError extends Error {
    constructor(methodName, message){
        super();
        this.name = 'StytchSDKUsageError';
        this.message = `Invalid call to ${methodName}\n` + message;
    }
}
/**
 * An Error class thrown when the provided input does not adhere to the Stytch API schema -
 * for example if a field that was expected to be a number is instead a string.
 */ class StytchSDKSchemaError extends Error {
    constructor(schemaError){
        super();
        this.name = 'StytchSDKSchemaError';
        const messages = schemaError.body?.map((err)=>`${err.dataPath}: ${err.message}`).join('\n');
        this.message = `[400] Request does not match expected schema\n${messages}`;
    }
}
/**
 * An Error class wrapping a well-formed JSON error from the Stytch API.
 * The Stytch error should match one listed at {@link https://stytch.com/docs/api/errors}
 */ class StytchSDKAPIError extends Error {
    error_type;
    error_message;
    error_url;
    request_id;
    status_code;
    error_details;
    constructor(details){
        super();
        this.name = 'StytchSDKAPIError';
        const { status_code, error_type, error_message, error_url, request_id, error_details } = details;
        this.error_type = error_type;
        this.error_message = error_message;
        this.error_url = error_url;
        this.request_id = request_id;
        this.status_code = status_code;
        this.error_details = error_details;
        this.message = `[${status_code}] ${error_type}\n` + `${error_message}\n` + `See ${error_url} for more information.\n` + // Web-Backend doesn't have request IDs yet, so if a request fails there it won't have one.
        // We should figure out how returning tracing info should work
        (request_id ? `request_id: ${request_id}\n` : '') + (this.error_details ? `Details: \n` + JSON.stringify(this.error_details) + '\n' : '');
    }
}
/**
 * If the SDK throws an error with an error type included in this array, the local session and
 * user state will be cleared locally.
 */ const UNRECOVERABLE_ERROR_TYPES = [
    'unauthorized_credentials',
    'user_unauthenticated',
    'invalid_secret_authentication',
    'session_not_found'
];
/**
 * An Error class representing an error within Stytch.
 */ class StytchError extends Error {
    constructor(name, message){
        super(message);
        this.name = name;
    }
}
/**
 * An Error class thrown when the SDK is unable to reach the Stytch servers,
 * or when the Stytch servers return a value the SDK cannot understand.
 * Usually - it means that you're offline!
 */ class StytchAPIUnreachableError extends StytchError {
    constructor(details){
        super('StytchAPIUnreachableError', details);
        Object.setPrototypeOf(this, StytchAPIUnreachableError.prototype);
    }
}
/**
 * An Error class thrown when the provided input does not adhere to the Stytch API schema -
 * for example if a field that was expected to be a number is instead a string.
 */ class StytchAPISchemaError extends StytchError {
    constructor(schemaError){
        const messages = schemaError.body?.map((err)=>`${err.dataPath}: ${err.message}`).join('\n');
        super('StytchAPISchemaError', `Request does not match expected schema\n${messages}`);
    }
}
/**
 * An Error class wrapping a well-formed JSON error from the Stytch API.
 * The Stytch error should match one listed at {@link https://stytch.com/docs/api/errors}
 */ class StytchAPIError extends StytchError {
    error_type;
    error_message;
    error_url;
    request_id;
    status_code;
    error_details;
    constructor(details){
        const { status_code, error_type, error_message, error_url, request_id, error_details } = details;
        super('StytchAPIError', `[${status_code}] ${error_type}\n` + `${error_message}\n` + `See ${error_url} for more information.\n` + // Web-Backend doesn't have request IDs yet, so if a request fails there it won't have one.
        // We should figure out how returning tracing info should work
        (request_id ? `request_id: ${request_id}\n` : '') + (error_details ? `Details: \n` + JSON.stringify(error_details) + '\n' : ''));
        this.error_type = error_type;
        this.error_message = error_message;
        this.error_url = error_url;
        this.request_id = request_id;
        this.status_code = status_code;
        this.error_details = error_details;
    }
    static from(err) {
        if (err instanceof StytchAPIError) {
            return err;
        }
        if (err && typeof err === 'object') {
            const maybe = err;
            if (typeof maybe.status_code === 'number' && typeof maybe.error_type === 'string' && typeof maybe.error_message === 'string' && typeof maybe.error_url === 'string') {
                return new StytchAPIError({
                    status_code: maybe.status_code,
                    error_type: maybe.error_type,
                    error_message: maybe.error_message,
                    error_url: maybe.error_url,
                    request_id: typeof maybe.request_id === 'string' ? maybe.request_id : undefined,
                    error_details: typeof maybe.error_details === 'object' ? maybe.error_details : undefined
                });
            }
        }
        const message = err instanceof Error ? err.message : 'Unknown error: ' + String(err);
        return new StytchAPIError({
            status_code: 400,
            error_type: 'unknown_error',
            error_message: message,
            error_url: '',
            request_id: undefined,
            error_details: undefined
        });
    }
}
/**
 * An Error class used in the Stytch SDK.
 */ class StytchSDKError extends StytchError {
    options;
    constructor(name, description, options){
        super(name, description);
        this.options = options;
    }
}
/**
 * Thrown when you attempt to perform an action that requires a session, but no local session exists
 */ class NoCurrentSessionError extends StytchSDKError {
    constructor(){
        super('NoCurrentSessionError', 'There is no session currently available. Make sure the user is authenticated with a valid session.');
    }
}
/**
 * Thrown when an unrecognized error is thrown
 */ class InternalError extends StytchSDKError {
    nativeStack;
    constructor(error){
        super(error.name ? error.name : 'Internal Error', error.message ? error.message : 'An internal error has occurred. Please contact Stytch if this occurs.');
        this.nativeStack = error.nativeStackAndroid || error.nativeStackIOS;
    }
}
/**
 * Thrown when no biometric registration exists
 */ class NoBiometricsRegistrationError extends StytchSDKError {
    constructor(){
        super('NoBiometricsRegistrationError', 'There is no biometric registration available. Authenticate with another method and add a new biometric registration first.');
    }
}
/**
 * Thrown when biometrics are unavailable on the device
 */ class BiometricsUnavailableError extends StytchSDKError {
    constructor(){
        super('BiometricsUnavailableError', 'Biometrics is not available on the device.');
    }
}
/**
 * Thrown when the biometrics enrollment has changed, and the underlying key is no longer usable
 */ class KeyInvalidatedError extends StytchSDKError {
    constructor(){
        super('KeyInvalidatedError', 'The biometrics enrollment on the device has changed.');
    }
}
/**
 * Thrown when the Keystore is determined to be unavailable
 */ class KeystoreUnavailableError extends StytchSDKError {
    constructor(){
        super('KeystoreUnavailableError', 'The Android keystore is unavailable on the device. Consider setting allowFallbackToCleartext to true.');
    }
}
/**
 * Thrown when there is no biometric factor enrolled on device
 */ class NoBiometricsEnrolledError extends StytchSDKError {
    constructor(){
        super('NoBiometricsEnrolledError', 'There is no biometric factor enrolled on the device. Add a biometric factor in the device settings.');
    }
}
/**
 * Thrown when there is no biometric factor enrolled on device
 */ class BiometricsAlreadyEnrolledError extends StytchSDKError {
    constructor(){
        super('BiometricsAlreadyEnrolledError', 'There is already a biometric factor enrolled on this device. Fully authenticate with all factors and remove the existing registration before attempting to register again.');
    }
}
/**
 * Thrown when the user has cancelled the prompt
 */ class UserCancellationError extends StytchSDKError {
    constructor(){
        super('UserCancellationError', 'The user canceled the prompt. Ask the user to try again.');
    }
}
/**
 * Thrown when the user has been locked out of biometrics
 */ class UserLockedOutError extends StytchSDKError {
    constructor(){
        super('UserLockedOutError', 'The user has been locked out due to too many failed attempts. Ask the user to try again later.');
    }
}
/**
 * Thrown when biometrics register/authenticate calls are made with mismatched `allowDeviceCredentials` parameter
 */ class DeviceCredentialsNotAllowedError extends StytchSDKError {
    constructor(){
        super('DeviceCredentialsNotAllowedError', 'The device credentials allowment is mismatched. Change the allowDeviceCredentials parameter to be the same in both the register and authenticate methods.');
    }
}
/**
 * Thrown when no Google client ID is found for the project
 */ class MissingGoogleClientIDError extends StytchSDKError {
    constructor(){
        super('MissingGoogleClientIDError', 'No Google client ID was found in the project.');
    }
}
/**
 * Thrown when there was an error generating or retrieving a PKCE keypair
 */ class MissingPKCEError extends StytchSDKError {
    constructor(){
        super('MissingPKCEError', 'Make sure this flow is completed on the same device on which it was started.');
    }
}
/**
 * Thrown when a native OAuth flow is missing the id_token
 */ class MissingAuthorizationCredentialIDTokenError extends StytchSDKError {
    constructor(){
        super('MissingAuthorizationCredentialIDTokenError', 'The authorization credential is missing an ID token.');
    }
}
/**
 * Thrown when a native OAuth flow returns an invalid credential
 */ class InvalidAuthorizationCredentialError extends StytchSDKError {
    constructor(){
        super('InvalidAuthorizationCredentialError', 'The authorization credential is invalid. Verify that OAuth is set up correctly in the developer console, and call the start flow method.');
    }
}
/**
 * Thrown when a Google OneTap flow is not completed successfully
 */ class NoCredentialsPresentError extends StytchSDKError {
    constructor(){
        super('NoCredentialsPresentError', 'The user did not provide credentials for a Google OneTap attempt');
    }
}
/**
 * Thrown when a public key was not found
 */ class MissingPublicKeyError extends StytchSDKError {
    constructor(){
        super('MissingPublicKeyError', 'Failed to retrieve the public key. Add a new biometric registration.');
    }
}
/**
 * Thrown when the challenge string failed to be signed
 */ class ChallengeSigningFailedError extends StytchSDKError {
    constructor(){
        super('ChallengeSigningFailedError', 'Failed to sign the challenge with the key.');
    }
}
/**
 * Thrown when the SDK has not been configured
 */ class SDKNotConfiguredError extends StytchSDKError {
    constructor(){
        super('SDKNotConfiguredError', 'Stytch client is not confiured. You must call the configure method before using the SDK');
    }
}
/**
 * Thrown when the code challenge failed to be generated
 */ class FailedCodeChallengeError extends StytchSDKError {
    constructor(){
        super('FailedCodeChallengeError', 'Failed to create a code challenge');
    }
}
/**
 * Thrown when Passkeys are unsupported on a device
 */ class PasskeysUnsupportedError extends StytchSDKError {
    constructor(){
        super('PasskeysUnsupportedError', 'Passkeys are not supported on this device');
    }
}
/**
 * Thrown when user data failed to be decrypted
 */ class FailedToDecryptDataError extends StytchSDKError {
    constructor(){
        super('FailedToDecryptDataError', 'Failed to decrypt user data');
    }
}
/**
 * Thrown when Biometrics failed
 */ class BiometricsFailedError extends StytchSDKError {
    constructor(){
        super('BiometricsFailedError', 'Biometric authentication failed');
    }
}
/**
 * Thrown when a start URL was invalid
 */ class InvalidStartUrlError extends StytchSDKError {
    constructor(){
        super('InvalidStartUrlError', 'The start URL was invalid or improperly formatted.');
    }
}
/**
 * Thrown when a redirect url was invalid
 */ class InvalidRedirectSchemeError extends StytchSDKError {
    constructor(){
        super('InvalidRedirectSchemeError', 'The scheme from the given redirect urls was invalid. Possible reasons include: nil scheme, non-custom scheme (using http or https), or differing schemes for login/signup urls.');
    }
}
/**
 * Thrown when the underlying web authentication service failed to return a URL.
 */ class MissingUrlError extends StytchSDKError {
    constructor(){
        super('MissingUrlError', 'The underlying web authentication service failed to return a URL.');
    }
}
/**
 * Thrown when the public key credential type was not of the expected type.
 */ class InvalidCredentialTypeError extends StytchSDKError {
    constructor(){
        super('InvalidCredentialTypeError', 'The public key credential type was not of the expected type.');
    }
}
/**
 * Thrown when the public key credential is missing the attestation object
 */ class MissingAttestationObjectError extends StytchSDKError {
    constructor(){
        super('MissingAttestationObjectError', 'The public key credential is missing the attestation object.');
    }
}
/**
 * Thrown when we received JSON data that could not be converted to a string
 */ class JSONDataNotConvertibleToStringError extends StytchSDKError {
    constructor(){
        super('JSONDataNotConvertibleToStringError', 'JSON data unable to be converted to String type.');
    }
}
/**
 * Thrown when RNG fails
 */ class RandomNumberGenerationFailed extends StytchSDKError {
    constructor(){
        super('RandomNumberGenerationFailed', 'Random number generation failed');
    }
}
/**
 * Thrown when there was an invalid encoding used for a Passkeys request
 */ class PasskeysInvalidEncoding extends StytchSDKError {
    constructor(){
        super('PasskeysInvalidEncoding', 'Invalid passkey encoding');
    }
}
/**
 * Thrown when Passkeys support is misconfigured
 */ class PasskeysMisconfigured extends StytchSDKError {
    constructor(){
        super('PasskeysMisconfigured', 'Passkeys are misconfigured. Verify that you have added the correct associated domain for your application, and that the signing information is correct.');
    }
}
/**
 * Thrown when there was an invalid encoding used for a Passkeys request
 */ class SignInWithAppleMisconfigured extends StytchSDKError {
    constructor(){
        super('SignInWithAppleMisconfigured', 'Sign In With Apple is misconfigured. Verify that you have correctly configured Apple OAuth in the Stytch Dashboard and added the Sign In With Apple capability to your project.');
    }
}
class MissingCipherIv extends StytchSDKError {
    constructor(){
        super('MissingCipherIv', 'The expected cipher Iv was not found when attempting to decrypt an existing biometric key.');
    }
}
class InvalidPrivateKeyLength extends StytchSDKError {
    constructor(){
        super('InvalidPrivateKeyLength', `The private key was of an incorrect length.`);
    }
}
class BiometricRegistrationIdIsNullOrBlank extends StytchSDKError {
    constructor(){
        super('BiometricRegistrationIdIsNullOrBlank', 'Attempted to set a blank or null biometric registration ID. This is not allowed, and indicates no registration was created on the server. Consider deleting any local keys that may have been generated.');
    }
}
class DFPNotConfigured extends StytchSDKError {
    constructor(){
        super('DFPNotConfigured', 'You have attempted to retrieve a telemetry ID before the DFP client has been configured.');
    }
}
/**
 * Thrown when a client attempts to start an OAuth flow but does not pass all required fields
 */ class IDPOAuthFlowMissingParamError extends StytchSDKError {
    constructor(details){
        super('IDPOAuthFlowMissingParamError', details);
    }
}
function errorToStytchError(error) {
    if (error instanceof StytchSDKError) return error;
    switch(error.message){
        case 'no_current_session':
            return new NoCurrentSessionError();
        case 'no_biometrics_registration':
            return new NoBiometricsRegistrationError();
        case 'biometrics_unavailable':
            return new BiometricsUnavailableError();
        case 'key_invalidated':
            return new KeyInvalidatedError();
        case 'device_hardware_error':
            return new BiometricsUnavailableError();
        case 'biometrics_not_available':
            return new BiometricsUnavailableError();
        case 'no_biometrics_enrolled':
            return new NoBiometricsEnrolledError();
        case 'keystore_unavailable':
            return new KeystoreUnavailableError();
        case 'no_biometric_key':
            return new KeyInvalidatedError();
        case 'device_credentials_not_allowed':
            return new DeviceCredentialsNotAllowedError();
        case 'user_cancellation':
            return new UserCancellationError();
        case 'user_locked_out':
            return new UserLockedOutError();
        case 'google_onetap_missing_id_token':
            return new MissingAuthorizationCredentialIDTokenError();
        case 'google_onetap_missing_member':
            return new InvalidAuthorizationCredentialError();
        case 'oauth_apple_missing_id_token':
            return new MissingAuthorizationCredentialIDTokenError();
        case 'oauth_apple_credential_invalid':
            return new InvalidAuthorizationCredentialError();
        case 'missing_public_key':
            return new MissingPublicKeyError();
        case 'challenge_signing_failed':
            return new ChallengeSigningFailedError();
        case 'missing_authorization_credential_id_token':
            return new MissingAuthorizationCredentialIDTokenError();
        case 'invalid_authorization_credential':
            return new InvalidAuthorizationCredentialError();
        case 'no_credentials_present':
            return new NoCredentialsPresentError();
        case 'sdk_not_configured':
            return new SDKNotConfiguredError();
        case 'failed_code_challenge':
            return new FailedCodeChallengeError();
        case 'passkeys_unsupported':
            return new PasskeysUnsupportedError();
        case 'failed_to_decrypt_data':
            return new FailedToDecryptDataError();
        case 'biometrics_failed':
            return new BiometricsFailedError();
        case 'invalid_start_url':
            return new InvalidStartUrlError();
        case 'invalid_redirect_scheme':
            return new InvalidRedirectSchemeError();
        case 'missing_url':
            return new MissingUrlError();
        case 'invalid_credential_type':
            return new InvalidCredentialTypeError();
        case 'missing_attestation_object':
            return new MissingAttestationObjectError();
        case 'json_data_not_convertible_to_string':
            return new JSONDataNotConvertibleToStringError();
        case 'random_number_generation_failed':
            return new RandomNumberGenerationFailed();
        case 'passkeys_invalid_encoding':
            return new PasskeysInvalidEncoding();
        case 'passkeys_misconfigured':
            return new PasskeysMisconfigured();
        case 'signinwithapple_misconfigured':
            return new SignInWithAppleMisconfigured();
        case 'missing_cipher_iv':
            return new MissingCipherIv();
        case 'invalid_private_key_length':
            return new InvalidPrivateKeyLength();
        case 'biometric_registration_id_is_null_or_blank':
            return new BiometricRegistrationIdIsNullOrBlank();
        case 'dfp_not_configured':
            return new DFPNotConfigured();
        default:
            return new InternalError(error);
    }
}

/**
 * The OAuth providers we support in our OAuth product.
 * Currently we support `Amazon`, `Apple`, `Bitbucket`, `Discord`, `Facebook`, `Figma`, `Google`, `GitLab`,
 * `LinkedIn`, `Microsoft`, `Salesforce`, `Slack`, `Snapchat`, `TikTok`, `Twitch`, `Twitter`, and `Yahoo`.
 */ const OAuthProviders = {
    Google: 'google',
    Microsoft: 'microsoft',
    Apple: 'apple',
    Github: 'github',
    GitLab: 'gitlab',
    Facebook: 'facebook',
    Discord: 'discord',
    Salesforce: 'salesforce',
    Slack: 'slack',
    Amazon: 'amazon',
    Bitbucket: 'bitbucket',
    LinkedIn: 'linkedin',
    Coinbase: 'coinbase',
    Twitch: 'twitch',
    Twitter: 'twitter',
    TikTok: 'tiktok',
    Snapchat: 'snapchat',
    Figma: 'figma',
    Yahoo: 'yahoo'
};
/**
 * The Crypto Wallets we support in our crypto product.
 * Currently we support all ethereum and solana wallets.
 * We additionally detect and show popular wallets as distinct options.
 * The list of poular wallets include `Binance`, `Coinbase`, `Metamask`, and `Phantom`
 */ const Wallets = {
    Phantom: 'Phantom',
    Metamask: 'Metamask',
    Coinbase: 'Coinbase',
    Binance: 'Binance',
    GenericEthereumWallet: 'GenericEthereumWallet',
    GenericSolanaWallet: 'GenericSolanaWallet'
};
/**
 * Supported behaviors for positioning Google One Tap. The actual behavior
 * depends on browser support and Google's One Tap implementation.
 */ const OneTapPositions = {
    /**
   * Display Google One Tap using a native browser prompt if available, or
   * embedded in the existing SDK login form otherwise.
   * @deprecated This option has been renamed to `floatingOrEmbedded`
   */ embedded: 'embedded',
    /**
   * Display the One Tap prompt using a native browser prompt if available, or
   * in the top right corner otherwise. This is the default option.
   */ floating: 'floating',
    /**
   * Display the One Tap prompt embedded in the existing SDK login form if a
   * native browser prompt is not available, or not at all otherwise. This
   * option is not recommended for new applications.
   */ embeddedOnly: 'embeddedOnly',
    /**
   * Display the One Tap prompt using a native browser prompt if available, or
   * embedded in the existing SDK login form otherwise.
   */ floatingOrEmbedded: 'floatingOrEmbedded',
    /**
   * Attempt to display the One Tap prompt embedded in the existing SDK login
   * form, even if a native browser prompt is supported. This option is not
   * recommended. It disables native browser FedCM support even where it is
   * available, and will stop being honored by Google in the future.
   */ forceLegacyEmbedded: 'forceLegacyEmbedded'
};
/**
 * The methods array allows you to specify the authentication methods that you would like to expose
 * to your users. The order of the products that you include here will also be the order in which
 * they appear in the login form, with the first product specified appearing at the top of the login
 * form. We currently support passcodes on `email`, `sms` and `whatsapp`
 */ const OTPMethods = {
    SMS: 'sms',
    WhatsApp: 'whatsapp',
    Email: 'email'
};
var StytchEventType = /*#__PURE__*/ function(StytchEventType) {
    StytchEventType["MagicLinkLoginOrCreateEvent"] = "MAGIC_LINK_LOGIN_OR_CREATE";
    StytchEventType["OTPsLoginOrCreateEvent"] = "OTP_LOGIN_OR_CREATE";
    StytchEventType["OTPsAuthenticate"] = "OTP_AUTHENTICATE";
    StytchEventType["CryptoWalletAuthenticateStart"] = "CRYPTO_WALLET_AUTHENTICATE_START";
    StytchEventType["CryptoWalletAuthenticate"] = "CRYPTO_WALLET_AUTHENTICATE";
    StytchEventType["PasswordCreate"] = "PASSWORD_CREATE";
    StytchEventType["PasswordAuthenticate"] = "PASSWORD_AUTHENTICATE";
    StytchEventType["PasswordResetByEmailStart"] = "PASSWORD_RESET_BY_EMAIL_START";
    StytchEventType["PasswordResetByEmail"] = "PASSWORD_RESET_BY_EMAIL";
    StytchEventType["PasskeyRegister"] = "PASSKEY_REGISTER";
    StytchEventType["PasskeyAuthenticate"] = "PASSKEY_AUTHENTICATE";
    StytchEventType["PasskeySkip"] = "PASSKEY_SKIP";
    StytchEventType["PasskeyDone"] = "PASSKEY_DONE";
    /**
   * The authentication UI flow has completed successfully, including any steps
   * that take place after obtaining a valid session (such as saving recovery
   * codes).
   */ StytchEventType["AuthenticateFlowComplete"] = "AUTHENTICATE_FLOW_COMPLETE";
    /**
   * An OAuth Authorization flow has been initiated by a Connected Application.
   * The end-user may be prompted for consent to continue depending on the application
   * that is requesting access.
   */ StytchEventType["OAuthAuthorizeFlowStart"] = "OAUTH_AUTHORIZE_FLOW_START";
    /**
   * The end-user has completed the Authorization flow and is about to be redirected
   * back to the Connected Application
   */ StytchEventType["OAuthAuthorizeFlowComplete"] = "OAUTH_AUTHORIZE_FLOW_COMPLETE";
    /**
   * The end-user has denied the Authorization flow and is about to be redirected
   * back to the Connected Application with an error message
   */ StytchEventType["OAuthAuthorizeFlowConsentDenied"] = "OAUTH_AUTHORIZE_FLOW_CONSENT_DENIED";
    // More Events will go here ...
    // B2B Events
    StytchEventType["B2BMagicLinkEmailLoginOrSignup"] = "B2B_MAGIC_LINK_EMAIL_LOGIN_OR_SIGNUP";
    StytchEventType["B2BMagicLinkAuthenticate"] = "B2B_MAGIC_LINK_AUTHENTICATE";
    StytchEventType["B2BMagicLinkEmailDiscoverySend"] = "B2B_MAGIC_LINK_EMAIL_DISCOVERY_SEND";
    StytchEventType["B2BMagicLinkDiscoveryAuthenticate"] = "B2B_MAGIC_LINK_DISCOVERY_AUTHENTICATE";
    StytchEventType["B2BSSOStart"] = "B2B_SSO_START";
    StytchEventType["B2BSSOAuthenticate"] = "B2B_SSO_AUTHENTICATE";
    StytchEventType["B2BSSODiscoverConnections"] = "B2B_SSO_DISCOVER_CONNECTIONS";
    StytchEventType["B2BOAuthAuthenticate"] = "B2B_OAUTH_AUTHENTICATE";
    StytchEventType["B2BOAuthDiscoveryAuthenticate"] = "B2B_OAUTH_DISCOVERY_AUTHENTICATE";
    StytchEventType["B2BDiscoveryOrganizationsCreate"] = "B2B_DISCOVERY_ORGANIZATIONS_CREATE";
    StytchEventType["B2BDiscoveryIntermediateSessionExchange"] = "B2B_DISCOVERY_INTERMEDIATE_SESSION_EXCHANGE";
    StytchEventType["B2BPasswordAuthenticate"] = "B2B_PASSWORD_AUTHENTICATE";
    StytchEventType["B2BPasswordDiscoveryAuthenticate"] = "B2B_PASSWORD_DISCOVERY_AUTHENTICATE";
    StytchEventType["B2BPasswordResetByEmailStart"] = "B2B_PASSWORD_RESET_BY_EMAIL_START";
    StytchEventType["B2BPasswordResetByEmail"] = "B2B_PASSWORD_RESET_BY_EMAIL";
    StytchEventType["B2BPasswordResetBySession"] = "B2B_PASSWORD_RESET_BY_SESSION";
    StytchEventType["B2BSMSOTPSend"] = "B2B_SMS_OTP_SEND";
    StytchEventType["B2BSMSOTPAuthenticate"] = "B2B_SMS_OTP_AUTHENTICATE";
    StytchEventType["B2BTOTPCreate"] = "B2B_TOTP_CREATE";
    StytchEventType["B2BTOTPAuthenticate"] = "B2B_TOTP_AUTHENTICATE";
    StytchEventType["B2BRecoveryCodesRecover"] = "B2B_RECOVERY_CODES_RECOVER";
    StytchEventType["B2BPasswordDiscoveryResetStart"] = "B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL_START";
    StytchEventType["B2BDiscoveryPasswordReset"] = "B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL";
    StytchEventType["B2BImpersonationAuthenticate"] = "B2B_IMPERSONATION_AUTHENTICATE";
    StytchEventType["B2BOTPsEmailAuthenticate"] = "B2B_OTPS_EMAIL_AUTHENTICATE";
    StytchEventType["B2BOTPsEmailDiscoveryAuthenticate"] = "B2B_OTPS_EMAIL_DISCOVERY_AUTHENTICATE";
    StytchEventType["B2BOTPsEmailDiscoverySend"] = "B2B_OTPS_EMAIL_DISCOVERY_SEND";
    StytchEventType["B2BOTPsEmailLoginOrSignup"] = "B2B_OTPS_EMAIL_LOGIN_OR_SIGNUP";
    StytchEventType["B2BOrganizationsGetBySlug"] = "B2B_ORGANIZATIONS_GET_BY_SLUG";
    return StytchEventType;
}({});
var RNUIProducts = /*#__PURE__*/ function(RNUIProducts) {
    RNUIProducts[RNUIProducts["emailMagicLinks"] = 0] = "emailMagicLinks";
    RNUIProducts[RNUIProducts["oauth"] = 1] = "oauth";
    RNUIProducts[RNUIProducts["otp"] = 2] = "otp";
    RNUIProducts[RNUIProducts["passwords"] = 3] = "passwords";
    return RNUIProducts;
}({});

const createDeepEqual = ({ KEYS_TO_EXCLUDE = [] } = {})=>{
    // If comparing functions, this may need some work. Not sure the
    // best path for this: compare instance (what it currently does),
    // stringify and compare, etc.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const deepEqual = (a, b)=>{
        // Ensures type is the same
        if (typeof a !== typeof b) return false;
        // arrays, null, and objects all have type 'object'
        if (a === null || b === null) return a === b;
        if (typeof a === 'object') {
            if (Object.keys(a).length !== Object.keys(b).length || Object.keys(a).some((k)=>!(k in b))) return false;
            return Object.entries(a).filter(([k])=>!KEYS_TO_EXCLUDE.includes(k)).every(([k, v])=>deepEqual(v, b[k]));
        }
        // boolean, string, number, undefined
        return a === b;
    };
    return deepEqual;
};

// You can't actually validate email just from regex. RFC 5322 is pretty complex and there are some *wild*
// rules that we would never really expect to handle, but are technically valid like:
//   1. Emails can contain comments -> cursed(comment)@example.com
//   2. Emails can contain symbols -> cursed{email}@example.com != cursedemail@example.com
//   3. Dots are allowed, but not consecutively -> ab.cd@example.com is okay, but not ab..cd@example.com
//   4. ... unless quoted -> "ab..cd"@example.com is okay
//      because yes, emails can also contain quotes
//      but then they *can't* contain comments
//   5. Emails can also consist of spaces and tabs if you use quoting
//
// TL;DR: it's really complicated. I once heard a joke that the only real way to validate an email is to check
// for the presence of an @ symbol and then see if you can send an email without it bouncing. Anyway, the below
// regex *attempts* to make some limitations on the regex to help end-users while not being overly constrained.
// We relaxed it as part of https://linear.app/stytch/issue/OBACK-583/email-pattern-bug-in-fe-sdk if you want some
// historical context here.
const EMAIL_REGEX = /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const convertMagicLinkOptions = (options = {})=>({
        signup_magic_link_url: options.signupRedirectURL,
        signup_expiration_minutes: options.signupExpirationMinutes,
        login_magic_link_url: options.loginRedirectURL,
        login_expiration_minutes: options.loginExpirationMinutes,
        login_template_id: options.loginTemplateId,
        signup_template_id: options.signupTemplateId,
        locale: options.locale
    });
const convertPasswordResetOptions = (email, options = {})=>({
        email: email,
        login_redirect_url: options.loginRedirectURL,
        login_expiration_minutes: options.loginExpirationMinutes,
        reset_password_redirect_url: options.resetPasswordRedirectURL,
        reset_password_expiration_minutes: options.resetPasswordExpirationMinutes,
        reset_password_template_id: options.resetPasswordTemplateId,
        locale: options.locale
    });
const debounce = (func, waitFor = 500)=>{
    let timeout;
    return (...args)=>{
        clearTimeout(timeout);
        timeout = window.setTimeout(()=>func(...args), waitFor);
    };
};
// Borrowed from Create React App's service worker registration logic
const isLocalhost = ()=>Boolean(window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));
const hasMultipleCookies = (cookieName)=>{
    const cookiePairs = document.cookie ? document.cookie.split('; ') : [];
    const matchedCookies = cookiePairs.filter((pair)=>{
        const [name] = pair.split('=');
        return cookieName === name;
    });
    return matchedCookies.length > 1;
};
const noop = ()=>{
// Noop
};

const PERSISTENT_STORAGE_KEY_PREFIX = 'stytch_sdk_state_';
const getPersistentStorageKey = (publicToken, key)=>{
    return `${PERSISTENT_STORAGE_KEY_PREFIX}${publicToken}${key ? `::${key}` : ''}`;
};
function makeSafeStorage(storage) {
    if (storage == null) {
        return {
            getItem () {
                return null;
            },
            removeItem () {
            // Noop
            },
            setItem () {
            // Noop
            }
        };
    }
    return {
        getItem (publicKey, key) {
            const persistentStorageKey = getPersistentStorageKey(publicKey, key);
            try {
                return storage.getItem(persistentStorageKey);
            } catch  {
                // Swallow error
                return null;
            }
        },
        setItem (publicKey, key, value) {
            const persistentStorageKey = getPersistentStorageKey(publicKey, key);
            try {
                if (value) storage.setItem(persistentStorageKey, value);
            } catch  {
            // Swallow error
            }
        },
        removeItem (publicKey, key) {
            const persistentStorageKey = getPersistentStorageKey(publicKey, key);
            try {
                storage.removeItem(persistentStorageKey);
            } catch  {
            // Swallow error
            }
        }
    };
}
const safeLocalStorage = makeSafeStorage(globalThis.localStorage);
const safeSessionStorage = makeSafeStorage(globalThis.sessionStorage);
function getKeyBoundStorage(storage, publicToken) {
    return {
        getItem (key) {
            return storage.getItem(publicToken, key);
        },
        setItem (key, value) {
            storage.setItem(publicToken, key, value);
        },
        removeItem (key) {
            storage.removeItem(publicToken, key);
        }
    };
}

const internalSymB2B = Symbol.for('stytch__internal_b2b');
const internalSymB2C = Symbol.for('stytch__internal_b2c');
const writeB2BInternals = (obj, internals)=>{
    Object.assign(obj, {
        [internalSymB2B]: internals
    });
};
const readB2BInternals = (obj)=>{
    const casted = obj;
    if (!casted[internalSymB2B]) {
        throw Error('Internals not found!');
    }
    return casted[internalSymB2B];
};
const writeB2CInternals = (obj, internals)=>{
    Object.assign(obj, {
        [internalSymB2C]: internals
    });
};
const readB2CInternals = (obj)=>{
    const casted = obj;
    if (!casted[internalSymB2C]) {
        throw Error('Internals not found!');
    }
    return casted[internalSymB2C];
};

// The strings in this file are only for developers
const noProviderError = (item, provider = 'StytchProvider')=>`${item} can only be used inside <${provider}>.`;
const providerMustBeUniqueError = 'You cannot render a <StytchProvider> inside another <StytchProvider>.';
const cannotInvokeMethodOnServerError = (path)=>`[Stytch] Invalid server-side function call to ${path}` ;

const SSRStubKey = Symbol('__stytch_SSRStubKey');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isStytchSSRProxy = (proxy)=>{
    return !!proxy[SSRStubKey];
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createProxy = (path)=>{
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    const noop = ()=>{};
    return new Proxy(noop, {
        get (target, p) {
            if (p === SSRStubKey) {
                return true;
            }
            return createProxy(path + '.' + String(p));
        },
        apply () {
            throw new Error(cannotInvokeMethodOnServerError(path));
        }
    });
};
// Exported for testing
const createStytchSSRProxy = ()=>createProxy('stytch');
function ssrSafeClientFactory(ClientConstructor) {
    return (...args)=>{
        if (typeof window === 'undefined') {
            return createStytchSSRProxy();
        }
        return new ClientConstructor(...args);
    };
}

exports.AuthFlowType = AuthFlowType;
exports.B2BMFAProducts = B2BMFAProducts;
exports.B2BOAuthProviders = B2BOAuthProviders;
exports.BiometricRegistrationIdIsNullOrBlank = BiometricRegistrationIdIsNullOrBlank;
exports.BiometricsAlreadyEnrolledError = BiometricsAlreadyEnrolledError;
exports.BiometricsFailedError = BiometricsFailedError;
exports.BiometricsUnavailableError = BiometricsUnavailableError;
exports.ChallengeSigningFailedError = ChallengeSigningFailedError;
exports.DFPNotConfigured = DFPNotConfigured;
exports.DeviceCredentialsNotAllowedError = DeviceCredentialsNotAllowedError;
exports.EMAIL_REGEX = EMAIL_REGEX;
exports.FailedCodeChallengeError = FailedCodeChallengeError;
exports.FailedToDecryptDataError = FailedToDecryptDataError;
exports.IDPOAuthFlowMissingParamError = IDPOAuthFlowMissingParamError;
exports.InternalError = InternalError;
exports.InvalidAuthorizationCredentialError = InvalidAuthorizationCredentialError;
exports.InvalidCredentialTypeError = InvalidCredentialTypeError;
exports.InvalidPrivateKeyLength = InvalidPrivateKeyLength;
exports.InvalidRedirectSchemeError = InvalidRedirectSchemeError;
exports.InvalidStartUrlError = InvalidStartUrlError;
exports.JSONDataNotConvertibleToStringError = JSONDataNotConvertibleToStringError;
exports.KeyInvalidatedError = KeyInvalidatedError;
exports.KeystoreUnavailableError = KeystoreUnavailableError;
exports.MissingAttestationObjectError = MissingAttestationObjectError;
exports.MissingAuthorizationCredentialIDTokenError = MissingAuthorizationCredentialIDTokenError;
exports.MissingCipherIv = MissingCipherIv;
exports.MissingGoogleClientIDError = MissingGoogleClientIDError;
exports.MissingPKCEError = MissingPKCEError;
exports.MissingPublicKeyError = MissingPublicKeyError;
exports.MissingUrlError = MissingUrlError;
exports.NoBiometricsEnrolledError = NoBiometricsEnrolledError;
exports.NoBiometricsRegistrationError = NoBiometricsRegistrationError;
exports.NoCredentialsPresentError = NoCredentialsPresentError;
exports.NoCurrentSessionError = NoCurrentSessionError;
exports.OAuthProviders = OAuthProviders;
exports.OTPMethods = OTPMethods;
exports.OneTapPositions = OneTapPositions;
exports.PasskeysInvalidEncoding = PasskeysInvalidEncoding;
exports.PasskeysMisconfigured = PasskeysMisconfigured;
exports.PasskeysUnsupportedError = PasskeysUnsupportedError;
exports.RNUIProducts = RNUIProducts;
exports.RandomNumberGenerationFailed = RandomNumberGenerationFailed;
exports.RedirectURLType = RedirectURLType;
exports.SDKAPIUnreachableError = SDKAPIUnreachableError;
exports.SDKNotConfiguredError = SDKNotConfiguredError;
exports.SignInWithAppleMisconfigured = SignInWithAppleMisconfigured;
exports.StytchAPIError = StytchAPIError;
exports.StytchAPISchemaError = StytchAPISchemaError;
exports.StytchAPIUnreachableError = StytchAPIUnreachableError;
exports.StytchError = StytchError;
exports.StytchEventType = StytchEventType;
exports.StytchSDKAPIError = StytchSDKAPIError;
exports.StytchSDKError = StytchSDKError;
exports.StytchSDKSchemaError = StytchSDKSchemaError;
exports.StytchSDKUsageError = StytchSDKUsageError;
exports.UNRECOVERABLE_ERROR_TYPES = UNRECOVERABLE_ERROR_TYPES;
exports.UserCancellationError = UserCancellationError;
exports.UserLockedOutError = UserLockedOutError;
exports.Wallets = Wallets;
exports.convertMagicLinkOptions = convertMagicLinkOptions;
exports.convertPasswordResetOptions = convertPasswordResetOptions;
exports.createDeepEqual = createDeepEqual;
exports.debounce = debounce;
exports.errorToStytchError = errorToStytchError;
exports.getKeyBoundStorage = getKeyBoundStorage;
exports.getPersistentStorageKey = getPersistentStorageKey;
exports.hasMultipleCookies = hasMultipleCookies;
exports.isLocalhost = isLocalhost;
exports.isStytchSSRProxy = isStytchSSRProxy;
exports.noProviderError = noProviderError;
exports.noop = noop;
exports.providerMustBeUniqueError = providerMustBeUniqueError;
exports.readB2BInternals = readB2BInternals;
exports.readB2CInternals = readB2CInternals;
exports.safeLocalStorage = safeLocalStorage;
exports.safeSessionStorage = safeSessionStorage;
exports.ssrSafeClientFactory = ssrSafeClientFactory;
exports.writeB2BInternals = writeB2BInternals;
exports.writeB2CInternals = writeB2CInternals;
//# sourceMappingURL=StytchSSRProxy-9SPT89Z8.js.map
