var stytch=function(e){"use strict";let t="https://accounts.google.com/gsi",i=`${t}/client`,r="It looks like you're creating multiple copies of the Stytch client. This behavior is unsupported, and unintended side effects may occur. Make sure you are creating the Stytch client at the global level, and not inside a component's render function.",s={Google:"google",Microsoft:"microsoft",HubSpot:"hubspot",Slack:"slack",GitHub:"github"};class o extends Error{details;constructor(e,t){super(e+"\n"+t),this.message=e+"\n"+t,this.name="SDKAPIUnreachableError",this.details=t,Object.setPrototypeOf(this,o.prototype)}}class n extends Error{constructor(e,t){super(),this.name="StytchSDKUsageError",this.message=`Invalid call to ${e}
`+t}}class a extends Error{constructor(e){super(),this.name="StytchSDKSchemaError";const t=e.body?.map(e=>`${e.dataPath}: ${e.message}`).join("\n");this.message=`[400] Request does not match expected schema
${t}`}}class c extends Error{error_type;error_message;error_url;request_id;status_code;error_details;constructor(e){super(),this.name="StytchSDKAPIError";const{status_code:t,error_type:i,error_message:r,error_url:s,request_id:o,error_details:n}=e;this.error_type=i,this.error_message=r,this.error_url=s,this.request_id=o,this.status_code=t,this.error_details=n,this.message=`[${t}] ${i}
${r}
See ${s} for more information.
`+(o?`request_id: ${o}
`:"")+(this.error_details?`Details: 
`+JSON.stringify(this.error_details)+"\n":"")}}let l=["unauthorized_credentials","user_unauthenticated","invalid_secret_authentication","session_not_found"];class d extends Error{constructor(e,t){super(t),this.name=e}}class h extends d{constructor(e){super("StytchAPIUnreachableError",e),Object.setPrototypeOf(this,h.prototype)}}class u extends d{constructor(e){const t=e.body?.map(e=>`${e.dataPath}: ${e.message}`).join("\n");super("StytchAPISchemaError",`Request does not match expected schema
${t}`)}}class _ extends d{error_type;error_message;error_url;request_id;status_code;error_details;constructor(e){const{status_code:t,error_type:i,error_message:r,error_url:s,request_id:o,error_details:n}=e;super("StytchAPIError",`[${t}] ${i}
${r}
See ${s} for more information.
`+(o?`request_id: ${o}
`:"")+(n?`Details: 
`+JSON.stringify(n)+"\n":"")),this.error_type=i,this.error_message=r,this.error_url=s,this.request_id=o,this.status_code=t,this.error_details=n}static from(e){return e instanceof _?e:e&&"object"==typeof e&&"number"==typeof e.status_code&&"string"==typeof e.error_type&&"string"==typeof e.error_message&&"string"==typeof e.error_url?new _({status_code:e.status_code,error_type:e.error_type,error_message:e.error_message,error_url:e.error_url,request_id:"string"==typeof e.request_id?e.request_id:void 0,error_details:"object"==typeof e.error_details?e.error_details:void 0}):new _({status_code:400,error_type:"unknown_error",error_message:e instanceof Error?e.message:"Unknown error: "+String(e),error_url:"",request_id:void 0,error_details:void 0})}}class p extends d{options;constructor(e,t,i){super(e,t),this.options=i}}class m extends p{constructor(){super("NoCurrentSessionError","There is no session currently available. Make sure the user is authenticated with a valid session.")}}class g extends p{nativeStack;constructor(e){super(e.name?e.name:"Internal Error",e.message?e.message:"An internal error has occurred. Please contact Stytch if this occurs."),this.nativeStack=e.nativeStackAndroid||e.nativeStackIOS}}class y extends p{constructor(){super("NoBiometricsRegistrationError","There is no biometric registration available. Authenticate with another method and add a new biometric registration first.")}}class b extends p{constructor(){super("BiometricsUnavailableError","Biometrics is not available on the device.")}}class S extends p{constructor(){super("KeyInvalidatedError","The biometrics enrollment on the device has changed.")}}class w extends p{constructor(){super("KeystoreUnavailableError","The Android keystore is unavailable on the device. Consider setting allowFallbackToCleartext to true.")}}class f extends p{constructor(){super("NoBiometricsEnrolledError","There is no biometric factor enrolled on the device. Add a biometric factor in the device settings.")}}class k extends p{constructor(){super("UserCancellationError","The user canceled the prompt. Ask the user to try again.")}}class C extends p{constructor(){super("UserLockedOutError","The user has been locked out due to too many failed attempts. Ask the user to try again later.")}}class v extends p{constructor(){super("DeviceCredentialsNotAllowedError","The device credentials allowment is mismatched. Change the allowDeviceCredentials parameter to be the same in both the register and authenticate methods.")}}class P extends p{constructor(){super("MissingAuthorizationCredentialIDTokenError","The authorization credential is missing an ID token.")}}class T extends p{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.")}}class A extends p{constructor(){super("NoCredentialsPresentError","The user did not provide credentials for a Google OneTap attempt")}}class E extends p{constructor(){super("MissingPublicKeyError","Failed to retrieve the public key. Add a new biometric registration.")}}class D extends p{constructor(){super("ChallengeSigningFailedError","Failed to sign the challenge with the key.")}}class O extends p{constructor(){super("SDKNotConfiguredError","Stytch client is not confiured. You must call the configure method before using the SDK")}}class I extends p{constructor(){super("FailedCodeChallengeError","Failed to create a code challenge")}}class B extends p{constructor(){super("PasskeysUnsupportedError","Passkeys are not supported on this device")}}class R extends p{constructor(){super("FailedToDecryptDataError","Failed to decrypt user data")}}class U extends p{constructor(){super("BiometricsFailedError","Biometric authentication failed")}}class K extends p{constructor(){super("InvalidStartUrlError","The start URL was invalid or improperly formatted.")}}class F extends p{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.")}}class L extends p{constructor(){super("MissingUrlError","The underlying web authentication service failed to return a URL.")}}class N extends p{constructor(){super("InvalidCredentialTypeError","The public key credential type was not of the expected type.")}}class M extends p{constructor(){super("MissingAttestationObjectError","The public key credential is missing the attestation object.")}}class x extends p{constructor(){super("JSONDataNotConvertibleToStringError","JSON data unable to be converted to String type.")}}class z extends p{constructor(){super("RandomNumberGenerationFailed","Random number generation failed")}}class $ extends p{constructor(){super("PasskeysInvalidEncoding","Invalid passkey encoding")}}class j extends p{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.")}}class W extends p{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 G extends p{constructor(){super("MissingCipherIv","The expected cipher Iv was not found when attempting to decrypt an existing biometric key.")}}class q extends p{constructor(){super("InvalidPrivateKeyLength","The private key was of an incorrect length.")}}class H extends p{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 V extends p{constructor(){super("DFPNotConfigured","You have attempted to retrieve a telemetry ID before the DFP client has been configured.")}}let Y={embedded:"embedded",floating:"floating",embeddedOnly:"embeddedOnly",floatingOrEmbedded:"floatingOrEmbedded",forceLegacyEmbedded:"forceLegacyEmbedded"};var J,X,Z,Q,ee=((Z={}).MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",Z.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",Z.OTPsAuthenticate="OTP_AUTHENTICATE",Z.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",Z.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE",Z.PasswordCreate="PASSWORD_CREATE",Z.PasswordAuthenticate="PASSWORD_AUTHENTICATE",Z.PasswordResetByEmailStart="PASSWORD_RESET_BY_EMAIL_START",Z.PasswordResetByEmail="PASSWORD_RESET_BY_EMAIL",Z.PasskeyRegister="PASSKEY_REGISTER",Z.PasskeyAuthenticate="PASSKEY_AUTHENTICATE",Z.PasskeySkip="PASSKEY_SKIP",Z.PasskeyDone="PASSKEY_DONE",Z.AuthenticateFlowComplete="AUTHENTICATE_FLOW_COMPLETE",Z.OAuthAuthorizeFlowStart="OAUTH_AUTHORIZE_FLOW_START",Z.OAuthAuthorizeFlowComplete="OAUTH_AUTHORIZE_FLOW_COMPLETE",Z.OAuthAuthorizeFlowConsentDenied="OAUTH_AUTHORIZE_FLOW_CONSENT_DENIED",Z.B2BMagicLinkEmailLoginOrSignup="B2B_MAGIC_LINK_EMAIL_LOGIN_OR_SIGNUP",Z.B2BMagicLinkAuthenticate="B2B_MAGIC_LINK_AUTHENTICATE",Z.B2BMagicLinkEmailDiscoverySend="B2B_MAGIC_LINK_EMAIL_DISCOVERY_SEND",Z.B2BMagicLinkDiscoveryAuthenticate="B2B_MAGIC_LINK_DISCOVERY_AUTHENTICATE",Z.B2BSSOStart="B2B_SSO_START",Z.B2BSSOAuthenticate="B2B_SSO_AUTHENTICATE",Z.B2BSSODiscoverConnections="B2B_SSO_DISCOVER_CONNECTIONS",Z.B2BOAuthAuthenticate="B2B_OAUTH_AUTHENTICATE",Z.B2BOAuthDiscoveryAuthenticate="B2B_OAUTH_DISCOVERY_AUTHENTICATE",Z.B2BDiscoveryOrganizationsCreate="B2B_DISCOVERY_ORGANIZATIONS_CREATE",Z.B2BDiscoveryIntermediateSessionExchange="B2B_DISCOVERY_INTERMEDIATE_SESSION_EXCHANGE",Z.B2BPasswordAuthenticate="B2B_PASSWORD_AUTHENTICATE",Z.B2BPasswordDiscoveryAuthenticate="B2B_PASSWORD_DISCOVERY_AUTHENTICATE",Z.B2BPasswordResetByEmailStart="B2B_PASSWORD_RESET_BY_EMAIL_START",Z.B2BPasswordResetByEmail="B2B_PASSWORD_RESET_BY_EMAIL",Z.B2BPasswordResetBySession="B2B_PASSWORD_RESET_BY_SESSION",Z.B2BSMSOTPSend="B2B_SMS_OTP_SEND",Z.B2BSMSOTPAuthenticate="B2B_SMS_OTP_AUTHENTICATE",Z.B2BTOTPCreate="B2B_TOTP_CREATE",Z.B2BTOTPAuthenticate="B2B_TOTP_AUTHENTICATE",Z.B2BRecoveryCodesRecover="B2B_RECOVERY_CODES_RECOVER",Z.B2BPasswordDiscoveryResetStart="B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL_START",Z.B2BDiscoveryPasswordReset="B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL",Z.B2BImpersonationAuthenticate="B2B_IMPERSONATION_AUTHENTICATE",Z.B2BOTPsEmailAuthenticate="B2B_OTPS_EMAIL_AUTHENTICATE",Z.B2BOTPsEmailDiscoveryAuthenticate="B2B_OTPS_EMAIL_DISCOVERY_AUTHENTICATE",Z.B2BOTPsEmailDiscoverySend="B2B_OTPS_EMAIL_DISCOVERY_SEND",Z.B2BOTPsEmailLoginOrSignup="B2B_OTPS_EMAIL_LOGIN_OR_SIGNUP",Z.B2BOrganizationsGetBySlug="B2B_ORGANIZATIONS_GET_BY_SLUG",Z),et=((J={})[J.emailMagicLinks=0]="emailMagicLinks",J[J.oauth=1]="oauth",J[J.otp=2]="otp",J[J.passwords=3]="passwords",J),ei=((X={}).RequiredCaptcha="CAPTCHA required",X);class er extends Error{type;constructor(e){super(e),this.type=e}}async function es({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:o,retryCallback:n}){let a={method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:o};try{return await eo(a)}catch(e){if(e instanceof er)return a=await n(e,a),await eo(a);throw e}}async function eo({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:o}){let n,a,c={Authorization:i,"Content-Type":"application/json","X-SDK-Client":r};s&&(c["X-SDK-Parent-Host"]=s);let l={method:e,headers:c,body:o&&JSON.stringify(o),credentials:"include"};try{n=await fetch(t,l)}catch(e){if("Failed to fetch"===e.message)throw new h("Unable to contact our servers.");throw e}if(n.status<=299)try{return(await n.json()).data}catch{throw new h("Invalid JSON response from our servers.")}if(200!==n.status&&n.headers.get("content-type")?.includes("application/json")){let e;try{e=await n.json()}catch{throw new h("Invalid or no response from server")}if("body"in e||"params"in e||"query"in e)throw new u(e);throw new _(e)}try{a=await n.text()}catch{throw new h("Invalid response from our servers.")}if(a.includes("Captcha required"))throw new er("CAPTCHA required");throw new h("Invalid response from our servers.")}async function en({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:o}){let n={...o||{},__Authorization:i,"__X-SDK-Client":r};s&&(n["__X-SDK-Parent-Host"]=s);let a=Object.entries(n).map(([e,t])=>{let i=document.createElement("input");return i.type="hidden",i.name=e,i.value=t,i}),c=document.createElement("form");c.method=e,c.action=t,c.append(...a),document.body.appendChild(c),c.submit()}for(var ea=new Uint8Array(16),ec=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,el=[],ed=0;ed<256;++ed)el.push((ed+256).toString(16).substr(1));function eh(e,t,i){var r=(e=e||{}).random||(e.rng||function(){if(!Q&&!(Q="u">typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"u">typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Q(ea)})();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(el[e[t+0]]+el[e[t+1]]+el[e[t+2]]+el[e[t+3]]+"-"+el[e[t+4]]+el[e[t+5]]+"-"+el[e[t+6]]+el[e[t+7]]+"-"+el[e[t+8]]+el[e[t+9]]+"-"+el[e[t+10]]+el[e[t+11]]+el[e[t+12]]+el[e[t+13]]+el[e[t+14]]+el[e[t+15]]).toLowerCase();if(!("string"==typeof i&&ec.test(i)))throw TypeError("Stringified UUID is invalid");return i}(r)}let eu=e=>{try{let t=new URL(e);return`https://${t.hostname}`}catch{}try{let t=new URL(`https://${e}`);return`https://${t.hostname}`}catch{}},e_=["%c[Stytch]%c","background: #19303d; color: #13E5C0; padding: 2px;border-radius: 4px",""],ep=(...e)=>console.warn(...e_,...e),em=(...e)=>console.error(...e_,...e),eg=`
You can find your public token at https://stytch.com/dashboard/api-keys.`,ey={};async function eb(e,t){var i,r;return void 0!==ey[e]||(ey[e]=(i=e,r=t,new Promise((e,t)=>{var s;let o,n=function(e){let t=document.querySelectorAll(`script[src="${e}"]`);if(t[0])return t[0]}(i);if(n&&"true"===n.dataset.loaded)try{e(r())}catch(e){return t(Error(`${i} already loaded, but module was not found in global scope: ${e}`))}let a=(s=i,(o=document.createElement("script")).setAttribute("src",s),o.setAttribute("async","true"),o.setAttribute("defer","true"),document.head.appendChild(o),o);a.addEventListener("load",()=>{a.dataset.loaded="true";try{e(r())}catch(e){t(Error(`${i} was loaded, but module was not found in global scope: ${e}`))}}),a.addEventListener("error",e=>{t(Error(`${i} could not be loaded: ${e}`))})}))),ey[e]}class eS{bootstrapPromise;state;constructor(e,t,i,r,s=()=>Promise.resolve(void 0)){this.bootstrapPromise=r,this.state=r.then(async r=>r.runDFPProtectedAuth?(await eb(`${i}/telemetry.js`,()=>window.GetTelemetryID),{publicToken:e,dfpBackendURL:t,enabled:!0,mode:r.dfpProtectedAuthMode||"OBSERVATION",loaded:!0,executeRecaptcha:s}):{publicToken:e,dfpBackendURL:t,enabled:!1,loaded:!1,executeRecaptcha:s})}isEnabled=async()=>this.state.then(e=>e.enabled);getTelemetryID=async()=>{let{publicToken:e,enabled:t,dfpBackendURL:i}=await this.state;if(t)return await window.GetTelemetryID(e,`${i}/submit`)};getDFPTelemetryIDAndCaptcha=async()=>{let e,t,{enabled:i,executeRecaptcha:r,mode:s}=await this.state;return i||(t=await r()),"DECISIONING"===s?e=await this.getTelemetryID():"OBSERVATION"===s&&(e=await this.getTelemetryID(),t=await r()),{dfp_telemetry_id:e,captcha_token:t}};retryWithCaptchaAndDFP=async(e,t)=>{let{enabled:i,executeRecaptcha:r}=await this.state;if(e.type===ei.RequiredCaptcha&&i)return t.body&&(t.body.dfp_telemetry_id=await this.getTelemetryID(),t.body.captcha_token=await r()),t;throw Error("Unable to query captcha and/or dfp telemetry ID")}}let ew=()=>({isEnabled:async()=>!1,getTelemetryID:async()=>void 0,getDFPTelemetryIDAndCaptcha:async()=>({dfp_telemetry_id:void 0,captcha_token:void 0}),retryWithCaptchaAndDFP:async()=>{throw Error("DFP protected auth is disabled")}});class ef{static inflate(e,t){let i=new e(t);return Object.assign(i,t),Object.setPrototypeOf(i,e.prototype),i}static unmarshall(e){if("name"in e)switch(e.name){case"SDKAPIUnreachableError":return ef.inflate(o,e);case"StytchSDKSchemaError":return ef.inflate(a,e);case"StytchAPIUnreachableError":return ef.inflate(h,e);case"StytchAPISchemaError":return ef.inflate(u,e);case"StytchSDKAPIError":return ef.inflate(c,e);case"StytchAPIError":return ef.inflate(_,e);case"TypeError":return ef.inflate(TypeError,e);case"SyntaxError":return ef.inflate(SyntaxError,e);case"ReferenceError":return ef.inflate(ReferenceError,e);case"RangeError":return ef.inflate(RangeError,e);case"EvalError":return ef.inflate(EvalError,e);case"URIError":return ef.inflate(URIError,e)}return ef.inflate(Error,e)}}class ek{maxBatchSize;logEventURL;batch;constructor(e){this.maxBatchSize=e.maxBatchSize,this.logEventURL=e.logEventURL,setInterval(this.flush.bind(this),e.intervalDurationMs),this.batch=[]}logEvent(e,t){this.batch.push({telemetry:e,event:t}),this.batch.length>=this.maxBatchSize&&this.flush()}async flush(){if(!this.batch.length)return;let e=this.batch;this.batch=[];try{await fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}}let eC=(e,t,i)=>{let r=[];for(let[s,o]of Object.entries(i)){if(null==o)continue;let i=t[s];if(!o.startsWith("optional")||null!=i)switch(o){case"object":case"optionalObject":("object"!=typeof i||Array.isArray(i)||null===i)&&r.push(new n(e,`${s} must be an object.`));break;case"string":case"optionalString":"string"!=typeof i&&r.push(new n(e,`${s} must be a string.`));break;case"number":case"optionalNumber":"number"!=typeof i&&r.push(new n(e,`${s} must be a number.`));break;case"stringArray":case"optionalStringArray":Array.isArray(i)&&i.every(e=>"string"==typeof e)||r.push(new n(e,`${s} must be an array of strings.`));break;case"boolean":case"optionalBoolean":"boolean"!=typeof i&&r.push(new n(e,`${s} must be a boolean.`))}}if(r.length>0)if(1===r.length)throw r[0];else throw AggregateError(r)};class ev{_networkClient;_subscriptionService;organizations;intermediateSessions;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.organizations={list:async()=>this._networkClient.fetchSDK({url:"/b2b/discovery/organizations",body:{intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST"}),create:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.discovery.organizations.create",e,{session_duration_minutes:"number",organization_name:"optionalString",organization_slug:"optionalString",organization_logo_url:"optionalString",sso_jit_provisioning:"optionalString",email_allowed_domains:"optionalStringArray",email_invites:"optionalString",auth_methods:"optionalString",allowed_auth_methods:"optionalStringArray",mfa_policy:"optionalString"});let t={...e,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.fetchSDK({url:"/b2b/discovery/organizations/create",body:t,method:"POST"})})},this.intermediateSessions={exchange:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.discovery.intermediateSessions.exchange",e,{organization_id:"string",session_duration_minutes:"number",locale:"optionalString"});let t={...e,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.fetchSDK({url:"/b2b/discovery/intermediate_sessions/exchange",body:t,method:"POST"})})}}}class eP{_networkClient;constructor(e){this._networkClient=e}oauthAuthorizeStart=async e=>this._networkClient.fetchSDK({url:"/idp/b2b/oauth/authorize/start",method:"POST",body:e});oauthAuthorizeSubmit=async e=>this._networkClient.fetchSDK({url:"/idp/b2b/oauth/authorize/submit",method:"POST",body:e});oauthLogoutStart=async e=>this._networkClient.fetchSDK({url:"/b2b/oauth/logout/start",method:"POST",body:e})}class eT{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.impersonation.authenticate",e,{impersonation_token:"string"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/impersonation/authenticate",body:{...e,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}let eA=Promise.resolve({pkceRequiredForEmailMagicLinks:!1});class eE{_networkClient;_subscriptionService;_pkceManager;_passwordResetPKCEManager;_config;dfpProtectedAuth;email;authenticate;discovery;constructor(e,t,i,r,s=eA,o=ew()){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._passwordResetPKCEManager=r,this._config=s,this.dfpProtectedAuth=o,this.email={invite:async e=>(eC("stytch.magicLinks.email.invite",e,{email_address:"string",invite_redirect_url:"optionalString",invite_template_id:"optionalString",name:"optionalString",locale:"optionalString",roles:"optionalStringArray",invite_expiration_minutes:"optionalNumber"}),this._networkClient.fetchSDK({url:"/b2b/magic_links/email/invite",body:e,method:"POST"})),loginOrSignup:async e=>{eC("stytch.magicLinks.email.loginOrSignup",e,{email_address:"string",organization_id:"string",login_redirect_url:"optionalString",login_template_id:"optionalString",signup_redirect_url:"optionalString",signup_template_id:"optionalString",locale:"optionalString",login_expiration_minutes:"optionalNumber",signup_expiration_minutes:"optionalNumber"});let t=await this.getCodeChallenge(),i={...e,pkce_code_challenge:t};return this._networkClient.fetchSDK({url:"/b2b/magic_links/email/login_or_signup",body:i,method:"POST"})},discovery:{send:async e=>{eC("stytch.magicLinks.email.discovery.send",e,{email_address:"string",discovery_redirect_url:"optionalString",login_template_id:"optionalString",locale:"optionalString",discovery_expiration_minutes:"optionalNumber"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this.getCodeChallenge(),s={...e,pkce_code_challenge:r,dfp_telemetry_id:t,captcha_token:i};return this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/email/discovery/send",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}}},this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.magicLinks.authenticate",e,{magic_links_token:"string",session_duration_minutes:"number",locale:"optionalString"});let t=await this._passwordResetPKCEManager.getPKPair(),i=null;if(t?.code_verifier)try{i=await this.handlePKCEForAuthenticate(this._passwordResetPKCEManager,e)}catch(e){if(e.message.includes("pkce"))console.log("Authenticate with passwords pkce namespace failed. Falling back to authenticate with magic_links namespace.");else throw e}return i||(i=await this.handlePKCEForAuthenticate(this._pkceManager,e)),i}),this.discovery={authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.magicLinks.discovery.authenticate",e,{discovery_magic_links_token:"string"});let t=await this._pkceManager.getPKPair(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s={pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,...e},o=await this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/discovery/authenticate",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),o})}}async getCodeChallenge(){let{pkceRequiredForEmailMagicLinks:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async handlePKCEForAuthenticate(e,t){let i=await e.getPKPair(),{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),o={pkce_code_verifier:i?.code_verifier,dfp_telemetry_id:r,captcha_token:s,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0,...t},n=await this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/authenticate",body:o,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return e.clearPKPair(),n}}let eD=class{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;dfpProtectedAuth;authenticate;discovery;google;microsoft;hubspot;slack;github;constructor(e,t,i,r,o,n){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._dynamicConfig=r,this._config=o,this.dfpProtectedAuth=n,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.oauth.authenticate",e,{oauth_token:"string",session_duration_minutes:"number",locale:"optionalString"});let t=await this._pkceManager.getPKPair();t||ep("No code verifier found in local storage for OAuth flow.\nConsider using stytch.oauth.$provider.start() to add PKCE to your OAuth flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._networkClient.retriableFetchSDK({url:"/b2b/oauth/authenticate",method:"POST",body:{pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0,...e},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),s}),this.discovery={authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.oauth.discovery.authenticate",e,{discovery_oauth_token:"string"});let t=await this._pkceManager.getPKPair(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s={pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,...e},o=await this._networkClient.retriableFetchSDK({url:"/b2b/oauth/discovery/authenticate",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),o})},this.google={start:this.startOAuthFlow(s.Google),discovery:{start:this.startDiscoveryOAuthFlow(s.Google)}},this.microsoft={start:this.startOAuthFlow(s.Microsoft),discovery:{start:this.startDiscoveryOAuthFlow(s.Microsoft)}},this.hubspot={start:this.startOAuthFlow(s.HubSpot),discovery:{start:this.startDiscoveryOAuthFlow(s.HubSpot)}},this.slack={start:this.startOAuthFlow(s.Slack),discovery:{start:this.startDiscoveryOAuthFlow(s.Slack)}},this.github={start:this.startOAuthFlow(s.GitHub),discovery:{start:this.startDiscoveryOAuthFlow(s.GitHub)}}}async getBaseApiUrl(){let{cnameDomain:e}=await this._dynamicConfig;return e?`https://${e}`:this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}startOAuthFlow(e){return async t=>{let{organization_id:i,organization_slug:r,login_redirect_url:s,signup_redirect_url:o,custom_scopes:n,provider_params:a}=t,{pkceRequiredForOAuth:c}=await this._dynamicConfig,l=await this.getBaseApiUrl(),d=new URL(`${l}/v1/b2b/public/oauth/${e}/start`);if(d.searchParams.set("public_token",this._config.publicToken),i&&""!=i&&d.searchParams.set("organization_id",i),r&&""!=r&&d.searchParams.set("slug",r),n&&(eC("startOAuthFlow",{custom_scopes:n},{custom_scopes:"stringArray"}),d.searchParams.set("custom_scopes",n.join(" "))),a)for(let e in eC("startOAuthFlow",{provider_params:a},{provider_params:"optionalObject"}),a)d.searchParams.set("provider_"+e,a[e]);if(c){let e=await this._pkceManager.startPKCETransaction();d.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();s&&d.searchParams.set("login_redirect_url",s),o&&d.searchParams.set("signup_redirect_url",o),this.navigate(d)}}startDiscoveryOAuthFlow(e){return async t=>{let{discovery_redirect_url:i,custom_scopes:r,provider_params:s}=t,{pkceRequiredForOAuth:o}=await this._dynamicConfig,n=await this.getBaseApiUrl(),a=new URL(`${n}/v1/b2b/public/oauth/${e}/discovery/start`);if(a.searchParams.set("public_token",this._config.publicToken),r&&(eC("startOAuthFlow",{custom_scopes:r},{custom_scopes:"stringArray"}),a.searchParams.set("custom_scopes",r.join(" "))),s)for(let e in eC("startOAuthFlow",{provider_params:s},{provider_params:"optionalObject"}),s)a.searchParams.set("provider_"+e,s[e]);if(o){let e=await this._pkceManager.startPKCETransaction();a.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();i&&a.searchParams.set("discovery_redirect_url",i),this.navigate(a)}}navigate(e){window.location.href=e.toString()}};class eO{_networkClient;_apiNetworkClient;_subscriptionService;constructor(e,t,i){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=i}get=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"GET"});return this._subscriptionService.updateOrganization(e.organization),e.organization};getSync=()=>this._subscriptionService.getOrganization();getInfo=()=>({organization:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.organization??null));update=async e=>{let t=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"PUT",body:e});return this._subscriptionService.updateOrganization(t.organization),t};delete=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"DELETE"});return this._subscriptionService.destroyState(),e};getBySlug=async e=>(eC("stytch.organization.getBySlug",e,{organization_slug:"string"}),this._networkClient.fetchSDK({url:"/b2b/organizations/search",method:"POST",body:e}));getConnectedApps=async()=>this._networkClient.fetchSDK({url:"/b2b/organizations/connected_apps",method:"GET"});getConnectedApp=async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/connected_apps/${e.connected_app_id}`,method:"GET"});members={create:async e=>this._networkClient.fetchSDK({url:"/b2b/organizations/members",method:"POST",body:e}),search:async e=>this._networkClient.fetchSDK({url:"/b2b/organizations/me/members/search",method:"POST",body:e}),update:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e.member_id}`,method:"PUT",body:e});return this.updateMemberIfSelf(t),t},deletePassword:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/passwords/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},deleteMFAPhoneNumber:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/mfa_phone_numbers/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},deleteMFATOTP:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/totp/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},delete:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e}`,method:"DELETE"});return e===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.destroyState(),t},reactivate:async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e}/reactivate`,method:"PUT"}),unlinkRetiredEmail:async e=>{let{member_id:t,...i}=e,r=await this._apiNetworkClient.fetchSDK({url:`/b2b/organizations/members/${t}/unlink_retired_email`,method:"POST",body:i});return this.updateMemberIfSelf(r),r},startEmailUpdate:async e=>{let{member_id:t,...i}=e,r=await this._apiNetworkClient.fetchSDK({url:`/b2b/organizations/members/${t}/start_email_update`,method:"POST",body:i});return this.updateMemberIfSelf(r),r},getConnectedApps:async e=>this._networkClient.fetchSDK({url:`b2b/organizations/members/${e.member_id}/connected_apps`,method:"GET"}),revokeConnectedApp:async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e.member_id}/connected_apps/${e.connected_app_id}/revoke`,method:"POST"})};updateMemberIfSelf=e=>{e.member_id===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.updateMember(e.member)}}class eI{_networkClient;_subscriptionService;dfpProtectedAuth;sms;email;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.sms={send:async e=>{eC("stytch.otps.sms.send",e,{organization_id:"string",member_id:"string",mfa_phone_number:"optionalString",locale:"optionalString"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/sms/send",body:{...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.otps.sms.authenticate",e,{session_duration_minutes:"number",organization_id:"string",member_id:"string",code:"string",set_mfa_enrollment:"optionalString"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/sms/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})},this.email={loginOrSignup:async e=>{eC("stytch.otps.email.loginOrSignup",e,{organization_id:"string",email_address:"string",login_template_id:"optionalString",signup_template_id:"optionalString",locale:"optionalString",login_expiration_minutes:"optionalNumber",signup_expiration_minutes:"optionalNumber"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/login_or_signup",body:{...e,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.otps.email.authenticate",e,{code:"string",email_address:"string",organization_id:"string",session_duration_minutes:"number",locale:"optionalString"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/authenticate",body:{...e,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),discovery:{send:async e=>{eC("stytch.otps.email.discovery.send",e,{email_address:"string",login_template_id:"optionalString",locale:"optionalString",discovery_expiration_minutes:"optionalNumber"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/discovery/send",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.otps.email.discovery.authenticate",e,{code:"string",email_address:"string"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={dfp_telemetry_id:t,captcha_token:i,...e};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/discovery/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}}}let eB=Promise.resolve({pkceRequiredForPasswordResets:!1});class eR{_networkClient;_subscriptionService;_pkceManager;_config;dfpProtectedAuth;authenticate;discovery;resetByEmail;resetByExistingPassword;resetBySession;constructor(e,t,i,r=eB,s){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._config=r,this.dfpProtectedAuth=s,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.authenticate",e,{organization_id:"string",password:"string",email_address:"string",session_duration_minutes:"number",locale:"optionalString"});let t=await this._pkceManager.getPKPair(),i=t?.code_verifier,{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/authenticate",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,password:e.password,session_duration_minutes:e.session_duration_minutes,locale:e.locale,captcha_token:s,dfp_telemetry_id:r,code_verifier:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),this.discovery={resetByEmailStart:async e=>{eC("stytch.passwords.discovery.resetByEmailStart",e,{email_address:"string",discovery_redirect_url:"optionalString",reset_password_redirect_url:"optionalString",reset_password_template_id:"optionalString",reset_password_expiration_minutes:"optionalNumber",verify_email_template_id:"optionalString",locale:"optionalString"});let t=await this.getCodeChallenge(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/reset/start",method:"POST",body:{email_address:e.email_address,discovery_redirect_url:e.discovery_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,verify_email_template_id:e.verify_email_template_id,locale:e.locale,pkce_code_challenge:t,captcha_token:r,dfp_telemetry_id:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},resetByEmail:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.discovery.resetByEmail",e,{password_reset_token:"string",password:"string"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._pkceManager.getPKPair(),s=r?.code_verifier,o=await this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/reset",method:"POST",body:{password_reset_token:e.password_reset_token,password:e.password,captcha_token:i,dfp_telemetry_id:t,pkce_code_verifier:s,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),o}),authenticate:this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.discovery.authenticate",e,{password:"string",email_address:"string"});let t=await this._pkceManager.getPKPair(),i=t?.code_verifier,{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/authenticate",method:"POST",body:{email_address:e.email_address,password:e.password,captcha_token:s,dfp_telemetry_id:r,code_verifier:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})},this.resetByEmail=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByEmail",e,{password_reset_token:"string",password:"string",session_duration_minutes:"number",locale:"optionalString"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._pkceManager.getPKPair(),s=r?.code_verifier,o=await this._networkClient.retriableFetchSDK({url:"/b2b/passwords/email/reset",method:"POST",body:{password_reset_token:e.password_reset_token,password:e.password,session_duration_minutes:e.session_duration_minutes,locale:e.locale,captcha_token:i,dfp_telemetry_id:t,code_verifier:s,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),o}),this.resetByExistingPassword=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByExistingPassword",e,{email_address:"string",existing_password:"string",new_password:"string",locale:"optionalString",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/existing_password/reset",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,existing_password:e.existing_password,new_password:e.new_password,locale:e.locale,session_duration_minutes:e.session_duration_minutes,captcha_token:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),this.resetBySession=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetBySession",e,{password:"string"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/session/reset",method:"POST",body:{password:e.password,captcha_token:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async getCodeChallenge(){let{pkceRequiredForPasswordResets:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async resetByEmailStart(e){eC("stytch.passwords.resetByEmailStart",e,{email_address:"string",login_redirect_url:"optionalString",reset_password_redirect_url:"optionalString",reset_password_template_id:"optionalString",reset_password_expiration_minutes:"optionalNumber",verify_email_template_id:"optionalString",locale:"optionalString"});let t=await this.getCodeChallenge(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/email/reset/start",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,login_redirect_url:e.login_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,verify_email_template_id:e.verify_email_template_id,locale:e.locale,code_challenge:t,captcha_token:r,dfp_telemetry_id:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async strengthCheck(e){return eC("stytch.passwords.strengthCheck",e,{email_address:"optionalString",password:"string"}),this._networkClient.fetchSDK({url:"/b2b/passwords/strength_check",method:"POST",body:{email_address:e.email_address,password:e.password}})}}class eU{roles;resources;rolesByID;constructor(e,t){this.roles=e,this.resources=t,this.rolesByID={},e.forEach(e=>this.rolesByID[e.role_id]=e)}static fromJSON(e){return new eU(e.roles,e.resources)}mergeWithCustomRoles(e){return new eU([...this.roles,...e],this.resources)}callerIsAuthorized(e,t,i){return!!e.map(e=>this.rolesByID[e]).filter(e=>e).flatMap(e=>e.permissions).filter(e=>e.resource_id===t).find(e=>e.actions.includes(i)||e.actions.includes("*"))}allPermissionsForCaller(e){let t=Object.create(null);return this.resources.forEach(i=>{t[i.resource_id]={},i.actions.forEach(r=>{t[i.resource_id][r]=this.callerIsAuthorized(e,i.resource_id,r)})}),t}}class eK{_subscriptionService;cachedPolicy;policyPromise;constructor(e,t,i){this._subscriptionService=i,this.cachedPolicy=e.rbacPolicy?eU.fromJSON(e.rbacPolicy):null,this.policyPromise=t.then(e=>e.rbacPolicy?(this.cachedPolicy=eU.fromJSON(e.rbacPolicy),this.cachedPolicy):(em("Unable to retrieve RBAC policy from servers. Assuming caller has no permissions."),new eU([],[])))}async getEffectivePolicy(){let e=await this.policyPromise,t=this._subscriptionService.getOrganization();return t?.custom_roles?.length?e.mergeWithCustomRoles(t.custom_roles):e}getEffectivePolicySync(){if(!this.cachedPolicy)return null;let e=this._subscriptionService.getOrganization();return e?.custom_roles?.length?this.cachedPolicy.mergeWithCustomRoles(e.custom_roles):this.cachedPolicy}allPermissions(){return this.getEffectivePolicy().then(e=>e.allPermissionsForCaller(this.roleIds()))}isAuthorizedSync=(e,t)=>{let i=this.getEffectivePolicySync();return!!i?.callerIsAuthorized(this.roleIds(),e,t)};isAuthorized=(e,t)=>this.getEffectivePolicy().then(i=>i.callerIsAuthorized(this.roleIds(),e,t));roleIds(){let e=this._subscriptionService.getSession();return e?e.roles??[]:[]}}class eF{_networkClient;_subscriptionService;dfpProtectedAuth;recover;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.recover=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.recoveryCodes.recover",e,{organization_id:"string",member_id:"string",recovery_code:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/recovery_codes/recover",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async rotate(){let{dfp_telemetry_id:e,captcha_token:t}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/recovery_codes/rotate",body:{dfp_telemetry_id:e,captcha_token:t},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async get(){return this._networkClient.fetchSDK({url:"/b2b/recovery_codes",method:"GET"})}}class eL{_networkClient;_subscriptionService;constructor(e,t){this._networkClient=e,this._subscriptionService=t}async createConnection(e){return eC("stytch.scim.createConnection",e,{display_name:"optionalString",identity_provider:"optionalString"}),await this._networkClient.fetchSDK({url:"/b2b/scim",method:"POST",body:e})}async updateConnection(e){return eC("stytch.scim.updateConnection",e,{connection_id:"string",display_name:"optionalString",identity_provider:"optionalString"}),await this._networkClient.fetchSDK({url:`/b2b/scim/${e.connection_id}`,method:"PUT",body:e})}async deleteConnection(e){return eC("stytch.scim.deleteConnection",{connection_id:e},{connection_id:"string"}),await this._networkClient.fetchSDK({url:`/b2b/scim/${e}`,method:"DELETE"})}async getConnection(){return await this._networkClient.fetchSDK({url:"/b2b/scim",method:"GET"})}async getConnectionGroups(e){return eC("stytch.scim.getConnectionGroups",e,{limit:"optionalNumber",cursor:"optionalString"}),await this._networkClient.fetchSDK({url:"/b2b/scim/groups",method:"POST",body:e})}async rotateStart(e){return eC("stytch.scim.rotateStart",{connectionId:e},{connectionId:"string"}),await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/start",method:"POST",body:{connection_id:e}})}async rotateComplete(e){return eC("stytch.scim.rotateComplete",{connectionId:e},{connectionId:"string"}),await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/complete",method:"POST",body:{connection_id:e}})}async rotateCancel(e){return eC("stytch.scim.rotateCancel",{connectionId:e},{connectionId:"string"}),await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/cancel",method:"POST",body:{connection_id:e}})}}class eN{_networkClient;_apiNetworkClient;_subscriptionService;constructor(e,t,i){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=i}get=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/me",method:"GET"});return this._subscriptionService.updateMember(e.member),e.member};getSync=()=>this._subscriptionService.getMember();getInfo=()=>({member:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.member??null));update=async e=>{eC("stytch.self.update",e,{name:"optionalString",untrusted_metadata:"optionalObject",mfa_enrolled:"optionalBoolean",mfa_phone_number:"optionalString",default_mfa_method:"optionalString"});let t=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/update",body:e,method:"PUT"});return this._subscriptionService.updateMember(t.member),t};deleteMFAPhoneNumber=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/deletePhoneNumber",method:"DELETE"});return this._subscriptionService.updateMember(e.member),e};deleteMFATOTP=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/deleteTOTP",method:"DELETE"});return this._subscriptionService.updateMember(e.member),e};deletePassword=async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/passwords/${e}`,method:"DELETE"});return this._subscriptionService.updateMember(t.member),t};unlinkRetiredEmail=async e=>{let t=await this._apiNetworkClient.fetchSDK({url:"/b2b/organizations/members/unlink_retired_email",method:"POST",body:e});return this._subscriptionService.updateMember(t.member),t};startEmailUpdate=async e=>{let t=await this._apiNetworkClient.fetchSDK({url:"/b2b/organizations/members/start_email_update",method:"POST",body:e});return this._subscriptionService.updateMember(t.member),t};getConnectedApps=async()=>this._networkClient.fetchSDK({url:"/b2b/organizations/members/connected_apps",method:"GET"});revokeConnectedApp=async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/connected_apps/${e.connected_app_id}/revoke`,method:"POST"})}class eM{_networkClient;_subscriptionService;getSync=()=>this._subscriptionService.getSession();getInfo=()=>({session:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.session??null));revoke=async e=>{try{let e=await this._networkClient.fetchSDK({url:"/b2b/sessions/revoke",method:"POST"});return this._subscriptionService.destroyState(),e}catch(t){throw e?.forceClear?this._subscriptionService.destroyState():l.includes(t.error_type)&&this._subscriptionService.destroyState(),t}};revokeForMember=async e=>(eC("stytch.session.revokeForMember",e,{member_id:"string"}),await this._networkClient.fetchSDK({url:`/b2b/sessions/revoke/${e.member_id}`,method:"POST"}));_authenticate=async e=>{let t=this._subscriptionService.getSession(),i=()=>t?.member_session_id!==this._subscriptionService.getSession()?.member_session_id;try{let t={session_duration_minutes:e?.session_duration_minutes},r=await this._networkClient.fetchSDK({url:"/b2b/sessions/authenticate",body:t,method:"POST"});if(i())return this._authenticate(e);return r}catch(t){if(i())return this._authenticate(e);throw l.includes(t.error_type)&&this._subscriptionService.destroySession(),t}};authenticate;exchange;exchangeAccessToken;attest;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.authenticate=this._subscriptionService.withUpdateSession(this._authenticate),this.exchange=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.exchange",e,{organization_id:"string",session_duration_minutes:"number",locale:"optionalString"}),this._networkClient.fetchSDK({url:"/b2b/sessions/exchange",body:e,method:"POST"}))),this.exchangeAccessToken=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.exchange",e,{access_token:"string",session_duration_minutes:"number"}),this._networkClient.fetchSDK({url:"/b2b/sessions/exchange_access_token",body:e,method:"POST"}))),this.attest=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.attest",e,{organization_id:"optionalString",profile_id:"string",token:"string",session_duration_minutes:"optionalNumber"}),this._networkClient.fetchSDK({url:"/b2b/sessions/attest",body:e,method:"POST"})))}getTokens(){return this._subscriptionService.getTokens()}updateSession(e){eC("stytch.session.updateSession",e,{session_token:"string",session_jwt:"optionalString"}),this._subscriptionService.updateTokens(e)}}class ex{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;dfpProtectedAuth;authenticate;constructor(e,t,i,r,s,o){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._dynamicConfig=r,this._config=s,this.dfpProtectedAuth=o,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.sso.authenticate",e,{sso_token:"string",session_duration_minutes:"number",locale:"optionalString"});let t=await this._pkceManager.getPKPair();t||ep("No code verifier found in local storage for SSO flow.\nConsider using stytch.sso.start() to add PKCE to your SSO flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._networkClient.retriableFetchSDK({url:"/b2b/sso/authenticate",method:"POST",body:{pkce_code_verifier:t?.code_verifier,...e,dfp_telemetry_id:i,captcha_token:r,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),s})}async getBaseApiUrl(){return this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}async start({connection_id:e,login_redirect_url:t,signup_redirect_url:i}){let{pkceRequiredForSso:r}=await this._dynamicConfig,s=await this.getBaseApiUrl(),o=new URL(`${s}/v1/public/sso/start`);if(o.searchParams.set("public_token",this._config.publicToken),o.searchParams.set("connection_id",e),r){let e=await this._pkceManager.startPKCETransaction();o.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();t&&o.searchParams.set("login_redirect_url",t),i&&o.searchParams.set("signup_redirect_url",i),this.navigate(o)}navigate(e){window.location.href=e.toString()}async getConnections(){return await this._networkClient.fetchSDK({url:"/b2b/sso",method:"GET"})}async discoverConnections(e){return await this._networkClient.fetchSDK({url:`/b2b/sso/discovery/connections?email_address=${encodeURIComponent(e)}`,method:"GET"})}async deleteConnection(e){return this._networkClient.fetchSDK({url:`/b2b/sso/${e}`,method:"DELETE"})}saml={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/saml",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}`,method:"PUT",body:e}),updateConnectionByURL:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/url`,method:"PUT",body:e}),deleteVerificationCertificate:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/verification_certificates/${e.certificate_id}`,method:"DELETE"}),deleteEncryptionPrivateKey:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/encryption_private_key/${e.private_key_id}`,method:"DELETE"})};oidc={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/oidc",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/oidc/${e.connection_id}`,method:"PUT",body:e})};external={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/external",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/external/${e.connection_id}`,method:"PUT",body:e})}}class ez{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.totp.authenticate",e,{organization_id:"string",member_id:"string",code:"string",session_duration_minutes:"number",set_mfa_enrollment:"optionalString",set_default_mfa:"optionalBoolean"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/totp/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async create(e){eC("stytch.totp.create",e,{organization_id:"string",member_id:"string",expiration_minutes:"optionalNumber"});let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._networkClient.retriableFetchSDK({url:"/b2b/totp",body:{...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return r.member_id===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.updateMember(r.member),r}}Promise.resolve({siweRequiredForCryptoWallets:!1}),Promise.resolve({pkceRequiredForEmailMagicLinks:!1}),Promise.resolve({pkceRequiredForPasswordResets:!1});class e${iframeURL;frame;constructor(e){this.iframeURL=e,this.createIframe()}createIframe(){let e=document.querySelector(`[src~="${this.iframeURL}"]`);if(e?ep(r):((e=document.createElement("iframe")).src=this.iframeURL,e.style.position="absolute",e.style.width="0",e.style.height="0",e.style.border="0",e.role="none",document.body.appendChild(e)),"true"===e.dataset.loaded){this.frame=Promise.resolve(e);return}this.frame=new Promise(t=>{e.addEventListener("load",()=>{e.dataset.loaded="true",t(e)},{once:!0})})}async call(e,t){let i=await this.frame,r=new MessageChannel;return new Promise((s,o)=>{r.port1.onmessage=e=>{let t=e.data;r.port1.close(),t.success?s(t.payload):o(ef.unmarshall(t.error))},i.contentWindow?.postMessage({method:e,args:t},this.iframeURL,[r.port2])})}}class ej{_networkClient;dfpProtectedAuth;constructor(e,t){this._networkClient=e,this.dfpProtectedAuth=t}searchUser(e){return this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha().then(({dfp_telemetry_id:t,captcha_token:i})=>this._networkClient.fetchSDK({url:"/users/search",method:"POST",body:{email:e,dfp_telemetry_id:t,captcha_token:i}}))}searchMember(e,t){return this._networkClient.fetchSDK({url:"/b2b/organizations/members/search",method:"POST",body:{email_address:e,organization_id:t}})}}class eW{hasWarned=!1;registry=new Map;register(e,t){let i=this.registry.get(e);i&&i!==t&&(this.hasWarned||(ep(r),this.hasWarned=!0),i.cancelBackgroundRefresh()),this.registry.set(e,t)}unregister(e,t){let i=this.registry.get(e);i&&i===t&&this.registry.delete(e)}}class eG{_subscriptionService;_headlessSessionClient;_publicToken;_options;static REFRESH_INTERVAL_MS=18e4;timeout=null;lastAuthenticationSessionDuration;static registry=new eW;register(){eG.registry.register(this._publicToken,this)}unregister(){eG.registry.unregister(this._publicToken,this)}constructor(e,t,i,r){this._subscriptionService=e,this._headlessSessionClient=t,this._publicToken=i,this._options=r,this._subscriptionService.subscribeToState(this._onDataChange)}performBackgroundRefresh(){this._reauthenticateWithBackoff().then(()=>{this.scheduleBackgroundRefresh()}).catch(e=>{ep("Session background refresh failed. Signalling to app that user is logged out.",{error:e}),this._subscriptionService.destroySession()})}scheduleBackgroundRefresh(){this.cancelBackgroundRefresh(),this.register(),this.timeout=setTimeout(()=>{this.performBackgroundRefresh()},eG.REFRESH_INTERVAL_MS)}cancelBackgroundRefresh(){null!==this.timeout&&(this.unregister(),clearTimeout(this.timeout),this.timeout=null)}_onDataChange=e=>{null!=e&&e.sessionDurationMinutes&&(this.lastAuthenticationSessionDuration=e.sessionDurationMinutes),e?.session?this.scheduleBackgroundRefresh():this.cancelBackgroundRefresh()};_reauthenticateWithBackoff=async()=>{let e=0;for(;;)try{let e={session_duration_minutes:this._options.keepSessionAlive?this.lastAuthenticationSessionDuration:void 0};return await this._headlessSessionClient.authenticate(e)}catch(t){if(eG.isUnrecoverableError(t))return Promise.reject(t);e++,await new Promise(t=>setTimeout(t,eG.timeoutForAttempt(e)))}};static timeoutForAttempt(e){return e=Math.min(e,7),Math.floor(350*Math.random())-175+2e3*2**e}static isUnrecoverableError(e){return l.includes(e.error_type)}}class eq{_subscriptionService;emptyState;constructor(e,t){this._subscriptionService=e,this.emptyState=t}onStateChange=e=>this._subscriptionService.subscribeToState(t=>{e(t??this.emptyState)})}let eH=Symbol("__stytch_SSRStubKey"),eV=e=>new Proxy(()=>{},{get:(t,i)=>i===eH||eV(e+"."+String(i)),apply(){throw Error(`[Stytch] Invalid server-side function call to ${e}.
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.`)}}),eY="bootstrap",eJ=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class eX{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,i){this._publicToken=e,this._networkClient=t,this._dataLayer=i,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(eX.mapBootstrapData).then(e=>(this._dataLayer.setItem(eY,JSON.stringify(e)),e)).catch(e=>(em(e),eJ()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(eY);if(null===e)return eJ();try{return JSON.parse(e)}catch{return eJ()}}getAsync(){return this._bootstrapDataPromise}}class eZ{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,eb(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:i}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(i,{action:"LOGIN"})}}class eQ{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new e$(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}class e2{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,i,r,s){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=s,this.baseURL=i,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=r),this.eventLogger=new ek({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:i={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:i.error_code,error_description:i.error_description,http_status_code:i.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${eh()}`,app_session_id:`app-session-id-${eh()}`,persistent_id:`persistent-id-${eh()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"@stytch/vanilla-js@6.0.9"}}}async fetchSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return eo({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async submitFormSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return en({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async retriableFetchSDK({url:e,body:t,method:i,retryCallback:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,o="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),n=window.btoa(JSON.stringify(this.createTelemetryBlob())),a=window.location.origin;return es({basicAuthHeader:o,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:n,xSDKParentHostHeader:a,retryCallback:r})}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}function e0(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class e1{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await e1.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{ep("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let i=Array.from(t).map(e0).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:i}}}function e6(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var e3=function e(t,i){function r(e,r,s){if("u">typeof document){"number"==typeof(s=e6({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var n in s)s[n]&&(o+="; "+n,!0!==s[n]&&(o+="="+s[n].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},s=0;s<i.length;s++){var o=i[s].split("="),n=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(r[a]=t.read(n,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",e6({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,e6({},this.attributes,t))},withConverter:function(t){return e(e6({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let e5=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[i]=t.split("=");return e===i}).length>1,e9=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function e4(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,i){let r=e9(t,i);try{return e.getItem(r)}catch{return null}},setItem(t,i,r){let s=e9(t,i);try{r&&e.setItem(s,r)}catch{}},removeItem(t,i){let r=e9(t,i);try{e.removeItem(r)}catch{}}}}let e8=e4(globalThis.localStorage),e7=e4(globalThis.sessionStorage);function te(e,t){return{getItem:i=>e.getItem(t,i),setItem(i,r){e.setItem(t,i,r)},removeItem(i){e.removeItem(t,i)}}}let tt="seen_domains";class ti{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let i;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=te(e8,e),this.browserSessionStorage=te(e7,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const r=this._localStorage.getItem("");if(!r)return;try{i=JSON.parse(r)}catch{this.syncToLocalStorage();return}this.state=i}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:e3.get(this.opaqueTokenCookieName),session_jwt:e3.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return e3.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:i,session_jwt:r}=e,s=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});s.domain&&this.addSeenDomain(s.domain),e3.set(this.opaqueTokenCookieName,i,s),e3.set(this.jwtCookieName,r,s);let o=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});o.domain&&this.addSeenDomain(o.domain),e5(this.jwtCookieName)&&e3.remove(this.jwtCookieName,o),e5(this.opaqueTokenCookieName)&&e3.remove(this.opaqueTokenCookieName,o),e5(this.jwtCookieName)&&ep("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),e5(this.opaqueTokenCookieName)&&ep("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),i=ti.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});e3.set(this.istCookieName,e,i)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}removeCookies(e){let t=this.getSeenDomains(),i=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(r=>{i.forEach(i=>{let s=ti.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:r,domain:i});e.forEach(e=>{e3.remove(e,s)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(tt);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(tt,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:i,expiresAt:r}){let s={expires:new Date(r),sameSite:"lax"};return e&&(s.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?s.secure=!1:(i&&(s.domain=t||window.location.host),s.secure=!0),s}}class tr extends ti{}let ts=Symbol.for("__stytch_b2b_DataLayer"),to=(e,t)=>{Object.values(e).forEach(e=>e(t))},tn=(({KEYS_TO_EXCLUDE:e=[]}={})=>{let t=(i,r)=>typeof i==typeof r&&(null===i||null===r?i===r:"object"==typeof i?!(Object.keys(i).length!==Object.keys(r).length||Object.keys(i).some(e=>!(e in r)))&&Object.entries(i).filter(([t])=>!e.includes(t)).every(([e,i])=>t(i,r[e])):i===r);return t})({KEYS_TO_EXCLUDE:["last_accessed_at"]});class ta{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:i}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!i){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==e9(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let i=this._datalayer.state,r=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=r;let s=this.getFromCache();if(this.setCacheRefreshed(),s||!tn(i,r)){let e;e=null==r||t.fromCache?r:{...r,sessionDurationMinutes:t.sessionDurationMinutes},to(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let i=this._datalayer.state,r=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=r;let s=this.getFromCache();this.setCacheRefreshed();let o=!tn(i,r);(s||o)&&(to(this._datalayer.subscriptions,r),o&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:i}=e,r={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:i};"string"==typeof t||"string"==typeof i?(this._datalayer.writeSessionCookie(r),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let i;return t=this._datalayer.subscriptions,t[i=Math.random().toString(36).slice(-10)]=e,()=>delete t[i]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class tc extends ta{updateMember=e=>this.updateState({member:e});getMember=()=>this.getState()?.member??null;updateOrganization=e=>this.updateState({organization:e});getOrganization=()=>this.getState()?.organization??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{if("member_session"in e&&e.member_session){let i=e.session_token&&e.session_jwt?{session_token:e.session_token,session_jwt:e.session_jwt}:{session_token:!0,session_jwt:!0};this.updateStateAndTokens({state:{session:e.member_session,member:e.member,organization:e.organization},...i,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})}else this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:e.intermediate_session_token||!0},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async t=>{let i=await e(t);return this.updateSession(i,{sessionDurationMinutes:t?.session_duration_minutes}),i}}let tl=Symbol.for("stytch__internal_b2b");class td extends eD{_oneTap;constructor(e,t,i,r,s,o=ew(),n){super(e,t,i,r,s,o),this._oneTap=n}startOneTapDiscovery=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnDiscoverySuccessHandler({discoveryRedirectUrl:e.discovery_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};startOneTap=async e=>{if(!e.organization_id)throw new n("stytch.oauth.googleOneTap.start","organization_id is a required argument");let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnSuccessHandler({organizationId:e.organization_id,signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={discovery:{start:this.startOneTapDiscovery},start:this.startOneTap}}let th="u">typeof window&&"IdentityCredential"in window,tu=e=>e===Y.forceLegacyEmbedded?"force":e===Y.embeddedOnly||e===Y.embedded||e===Y.floatingOrEmbedded;class t_{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:i,cancelOnTapOutside:r=!0}){let s,o=tu(i.position),n="force"===(s=tu(i.position))||s&&!th,a={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==o,cancel_on_tap_outside:r};return n&&(a.prompt_parent_id="google-parent-prompt",a.cancel_on_tap_outside=!1),this._googleClient.initialize(a),new Promise(e=>{this._googleClient.prompt(i=>{if(i.isSkippedMoment()){let r=i.getSkippedReason?.()??"unknown_reason";return"user_cancel"===r&&t?.(),e({success:!1,reason:r})}return!i.isNotDisplayed&&n||i.isNotDisplayed?.()?e({success:!1,reason:i.getNotDisplayedReason?.()??"unknown_reason"}):i.isDismissedMoment()?void 0:(this.styleFrame(n),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEach(e=>{e.src.includes(t)&&(e.style.width="100%")})}}let tp=Promise.resolve({pkceRequiredForOAuth:!1});class tm{_networkClient;_pkceManager;_config;googleClientID;constructor(e,t,i=tp){this._networkClient=e,this._pkceManager=t,this._config=i}async fetchGoogleStart(){if(this.googleClientID)return this.googleClientID;let e=await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/start",method:"GET"});return this.googleClientID=e.google_client_id,this.googleClientID}async submitGoogleOneTapTokenDiscovery({credential:e,discoveryRedirectUrl:t}){let i,{pkceRequiredForOAuth:r}=await this._config;return r?i=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/discovery/submit",method:"POST",body:{id_token:e,discovery_redirect_url:t,pkce_code_challenge:i}})}async submitGoogleOneTapToken({credential:e,organizationId:t,signupRedirectUrl:i,loginRedirectUrl:r}){let s,{pkceRequiredForOAuth:o}=await this._config;return o?s=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/submit",method:"POST",body:{id_token:e,organization_id:t,signup_redirect_url:i,login_redirect_url:r,pkce_code_challenge:s}})}async createOneTapClient(){let e;try{e=await this.fetchGoogleStart()}catch(e){return{success:!1,reason:_.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new t_(await eb(i,()=>window.google.accounts.id),e)}}createOnDiscoverySuccessHandler=({discoveryRedirectUrl:e,onSuccess:t,onError:i})=>async r=>{let{credential:s}=r,o=this.submitGoogleOneTapTokenDiscovery({credential:s,discoveryRedirectUrl:e}).then(e=>t(e.redirect_url));i&&(o=o.catch(e=>i(e))),await o};createOnSuccessHandler=({organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i,onSuccess:r,onError:s})=>async o=>{let{credential:n}=o,a=this.submitGoogleOneTapToken({credential:n,organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i}).then(e=>r(e.redirect_url));s&&(a=a.catch(e=>s(e))),await a};redirectOnSuccess=e=>{window.location.href=e}}class tg{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;magicLinks;session;member;self;organization;oauth;sso;discovery;passwords;otps;totp;recoveryCodes;rbac;scim;impersonation;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchB2BClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchB2BClient()` instead.");(e=>{"string"!=typeof e?ep(`Public token is malformed. Expected a string, got ${typeof e}.${eg}`):""===e?ep(`Public token is malformed. Expected "public-token-...", got an empty string.${eg}`):e.startsWith("public-token-")||ep(`Public token is malformed. Expected "public-token-...", got ${e}.${eg}`)})(e);const i=e??"",r=((e,t={})=>{let{cookieOptions:i,keepSessionAlive:r}=t;return eC(e,t,{keepSessionAlive:"optionalBoolean"}),i&&eC(`${e}.cookieOptions`,i,{opaqueTokenCookieName:"optionalString",jwtCookieName:"optionalString",istCookieName:"optionalString",path:"optionalString",domain:"optionalString"}),{cookieOptions:i,keepSessionAlive:r,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"testApiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"apiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";ep(`Unable to use custom DFPPA domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";ep(`Unable to use custom DFP CDN domain \`${t}\`. ${i} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),s=((e,t={})=>{let{customBaseUrl:i,endpointOptions:r}=t;return e.includes("public-token-test")?!!(i||r?.testApiDomain):!!(i||r?.apiDomain)})(i,t);this._dataLayer=((e,t)=>{let i,r=((i=window)[ts]||(i[ts]={}),i[ts]);return r[e]||(r[e]=new tr(e,t)),r[e]})(i,r),this._subscriptionService=new tc(i,this._dataLayer,{usingCustomApiEndpoint:s}),this._stateChangeClient=new eq(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const o=()=>({stytch_member_id:this._dataLayer.state?.member?.member_id,stytch_member_session_id:this._dataLayer.state?.session?.member_session_id}),n=new e1(this._dataLayer,"passwords"),a=new e2(i,this._dataLayer,r.endpoints.liveAPIURL,r.endpoints.testAPIURL,o);this._networkClient=a;const c=new eX(i,a,this._dataLayer),l=new eZ(c.getAsync()),d=new eS(i,r.endpoints.dfpBackendURL,r.endpoints.dfpCdnURL,c.getAsync(),l.executeRecaptcha),h=new eQ(r.endpoints.clientsideServicesIframeURL),u=new e1(this._dataLayer,"oauth"),_=new tm(a,u,c.getAsync());this.organization=new eO(a,a,this._subscriptionService),this.member=new eN(a,a,this._subscriptionService),this.self=new eN(a,a,this._subscriptionService),this.session=new eM(a,this._subscriptionService),this.magicLinks=new eE(a,this._subscriptionService,new e1(this._dataLayer,"magic_links"),n,c.getAsync(),d),this.oauth=new td(a,this._subscriptionService,u,c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d,_),this.sso=new ex(a,this._subscriptionService,new e1(this._dataLayer,"sso"),c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d),this.discovery=new ev(a,this._subscriptionService),this.passwords=new eR(a,this._subscriptionService,n,c.getAsync(),d),this.otps=new eI(a,this._subscriptionService,d),this.totp=new ez(a,this._subscriptionService,d),this.recoveryCodes=new eF(a,this._subscriptionService,d),this.rbac=new eK(c.getSync(),c.getAsync(),this._subscriptionService),this.scim=new eL(this._networkClient,this._subscriptionService),this.impersonation=new eT(this._networkClient,this._subscriptionService,d),this.idp=new eP(a),this._sessionManager=new eG(this._subscriptionService,this.session,i,{keepSessionAlive:r.keepSessionAlive});const p=new ej(a,d);(s||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh();const{authenticateByUrl:m,parseAuthenticateUrl:g}=(e=>{let t=Object.keys(e),i=(e=window.location.href)=>{let i=new URL(e),r=i.searchParams.get("stytch_token_type"),s=i.searchParams.get("token");return s&&r?t.includes(r)?{handled:!0,token:s,tokenType:r}:{handled:!1,token:s,tokenType:r}:null};return{authenticateByUrl:async({clearParams:t,...r},s=window.location.href)=>{let o,n,a,c=t??s===window.location.href,l=i(s);if(null==l)return null;if(!l.handled)return l;let{token:d,tokenType:h}=l,u=e[h];return c&&((n=(o=new URL(window.location.toString())).searchParams).delete("token"),n.delete("stytch_token_type"),a=o,window.history.replaceState(null,document.title,a)),{handled:!0,tokenType:h,data:await u(d,r)}},parseAuthenticateUrl:i}})({discovery:e=>this.magicLinks.discovery.authenticate({discovery_magic_links_token:e}),discovery_oauth:e=>this.oauth.discovery.authenticate({discovery_oauth_token:e}),oauth:(e,t)=>this.oauth.authenticate({oauth_token:e,...t}),sso:(e,t)=>this.sso.authenticate({sso_token:e,...t}),multi_tenant_magic_links:(e,t)=>this.magicLinks.authenticate({magic_links_token:e,...t}),multi_tenant_impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=m,this.parseAuthenticateUrl=g,a.logEvent({name:"b2b_sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),c.getAsync().then(e=>{"CONSUMER"===e.vertical&&em("This application is using a Stytch client for B2B projects, but the public token is for a Stytch Consumer project. Use a Consumer Stytch client instead, or verify that the public token is correct.")}),((e,t)=>{Object.assign(e,{[tl]:t})})(this,{bootstrap:c,clientsideServices:h,publicToken:i,searchManager:p,dataLayer:this._dataLayer,networkClient:a,oneTap:_})}}let ty=["openid","email","profile"],tb=(...e)=>"u"<typeof window?eV("stytch"):new tg(...e);return e.AuthFlowType={Discovery:"Discovery",Organization:"Organization",PasswordReset:"PasswordReset"},e.B2BMFAProducts={smsOtp:"smsOtp",totp:"totp"},e.B2BOAuthProviders=s,e.BiometricRegistrationIdIsNullOrBlank=H,e.BiometricsAlreadyEnrolledError=class extends p{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.")}},e.BiometricsFailedError=U,e.BiometricsUnavailableError=b,e.ChallengeSigningFailedError=D,e.DFPNotConfigured=V,e.DeviceCredentialsNotAllowedError=v,e.FailedCodeChallengeError=I,e.FailedToDecryptDataError=R,e.IDPOAuthFlowMissingParamError=class extends p{constructor(e){super("IDPOAuthFlowMissingParamError",e)}},e.InternalError=g,e.InvalidAuthorizationCredentialError=T,e.InvalidCredentialTypeError=N,e.InvalidPrivateKeyLength=q,e.InvalidRedirectSchemeError=F,e.InvalidStartUrlError=K,e.JSONDataNotConvertibleToStringError=x,e.KeyInvalidatedError=S,e.KeystoreUnavailableError=w,e.MissingAttestationObjectError=M,e.MissingAuthorizationCredentialIDTokenError=P,e.MissingCipherIv=G,e.MissingGoogleClientIDError=class extends p{constructor(){super("MissingGoogleClientIDError","No Google client ID was found in the project.")}},e.MissingPKCEError=class extends p{constructor(){super("MissingPKCEError","Make sure this flow is completed on the same device on which it was started.")}},e.MissingPublicKeyError=E,e.MissingUrlError=L,e.NoBiometricsEnrolledError=f,e.NoBiometricsRegistrationError=y,e.NoCredentialsPresentError=A,e.NoCurrentSessionError=m,e.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"},e.OTPMethods={SMS:"sms",WhatsApp:"whatsapp",Email:"email"},e.OneTapPositions=Y,e.PasskeysInvalidEncoding=$,e.PasskeysMisconfigured=j,e.PasskeysUnsupportedError=B,e.RNUIProducts=et,e.RandomNumberGenerationFailed=z,e.RedirectURLType={ResetPassword:"reset_password"},e.SDKAPIUnreachableError=o,e.SDKNotConfiguredError=O,e.SignInWithAppleMisconfigured=W,e.StytchAPIError=_,e.StytchAPISchemaError=u,e.StytchAPIUnreachableError=h,e.StytchB2BClient=tg,e.StytchB2BHeadlessClient=tg,e.StytchError=d,e.StytchEventType=ee,e.StytchSDKAPIError=c,e.StytchSDKError=p,e.StytchSDKSchemaError=a,e.StytchSDKUsageError=n,e.UNRECOVERABLE_ERROR_TYPES=l,e.UserCancellationError=k,e.UserLockedOutError=C,e.Wallets={Phantom:"Phantom",Metamask:"Metamask",Coinbase:"Coinbase",Binance:"Binance",GenericEthereumWallet:"GenericEthereumWallet",GenericSolanaWallet:"GenericSolanaWallet"},e.createStytchB2BClient=tb,e.createStytchB2BHeadlessClient=tb,e.errorToStytchError=function(e){if(e instanceof p)return e;switch(e.message){case"no_current_session":return new m;case"no_biometrics_registration":return new y;case"biometrics_unavailable":case"device_hardware_error":case"biometrics_not_available":return new b;case"key_invalidated":case"no_biometric_key":return new S;case"no_biometrics_enrolled":return new f;case"keystore_unavailable":return new w;case"device_credentials_not_allowed":return new v;case"user_cancellation":return new k;case"user_locked_out":return new C;case"google_onetap_missing_id_token":case"oauth_apple_missing_id_token":case"missing_authorization_credential_id_token":return new P;case"google_onetap_missing_member":case"oauth_apple_credential_invalid":case"invalid_authorization_credential":return new T;case"missing_public_key":return new E;case"challenge_signing_failed":return new D;case"no_credentials_present":return new A;case"sdk_not_configured":return new O;case"failed_code_challenge":return new I;case"passkeys_unsupported":return new B;case"failed_to_decrypt_data":return new R;case"biometrics_failed":return new U;case"invalid_start_url":return new K;case"invalid_redirect_scheme":return new F;case"missing_url":return new L;case"invalid_credential_type":return new N;case"missing_attestation_object":return new M;case"json_data_not_convertible_to_string":return new x;case"random_number_generation_failed":return new z;case"passkeys_invalid_encoding":return new $;case"passkeys_misconfigured":return new j;case"signinwithapple_misconfigured":return new W;case"missing_cipher_iv":return new G;case"invalid_private_key_length":return new q;case"biometric_registration_id_is_null_or_blank":return new H;case"dfp_not_configured":return new V;default:return new g(e)}},e.parseOAuthAuthorizeParams=e=>{let t={client_id:"",redirect_uri:"",response_type:"code",scopes:[...ty]};for(let i of["client_id","redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}for(let i of["response_type","scope","code_challenge","state","nonce","prompt"]){let r=e.get(i);r&&("scope"===i?t.scopes=r.split(" ").filter(Boolean):t[i]=r)}return e.has("resource")&&(t.resources=e.getAll("resource")),{error:null,result:t}},e.parseOAuthLogoutParams=e=>{let t={client_id:"",post_logout_redirect_uri:""};for(let i of["client_id","post_logout_redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}return t.id_token_hint=e.get("id_token_hint")||void 0,t.state=e.get("state")||void 0,{error:null,result:t}},e}({});
//# sourceMappingURL=index.headless.js.map
