'use strict';

var dev = require('./dev-DaCGDI6V.js');

/**
 * 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'
};

/**
 * 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
function serverRenderError(name) {
    dev.RUN_IN_DEV(()=>{
        if (typeof window === 'undefined') {
            throw new Error(`<${name} /> cannot be rendered on the server. If you are using Next.js, use the @stytch/nextjs package or 'use client' directives`);
        }
    });
}
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}.
The Stytch JavaScript SDK is intended to only be used on the client side.
Make sure to wrap your API calls in a hook to ensure they are executed on the client.

\`\`\`
const myComponent = () => {
  const stytch = useStytch();
  // This will error out on the server.
  stytch.magicLinks.authenticate(...);
  useEffect(() => {
    // This will work well
    stytch.magicLinks.authenticate(...);
  }, []);
}
\`\`\`

If you want to make API calls from server environments, please use the Stytch Node Library
https://www.npmjs.com/package/stytch.`;

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.EMAIL_REGEX = EMAIL_REGEX;
exports.OAuthProviders = OAuthProviders;
exports.OTPMethods = OTPMethods;
exports.OneTapPositions = OneTapPositions;
exports.RNUIProducts = RNUIProducts;
exports.RedirectURLType = RedirectURLType;
exports.StytchEventType = StytchEventType;
exports.Wallets = Wallets;
exports.convertMagicLinkOptions = convertMagicLinkOptions;
exports.convertPasswordResetOptions = convertPasswordResetOptions;
exports.createDeepEqual = createDeepEqual;
exports.debounce = debounce;
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.serverRenderError = serverRenderError;
exports.ssrSafeClientFactory = ssrSafeClientFactory;
exports.writeB2BInternals = writeB2BInternals;
exports.writeB2CInternals = writeB2CInternals;
//# sourceMappingURL=StytchSSRProxy-D0nfqCWX.js.map
