@clerk/clerk-js 6.0.0-canary-core3.v20251203181537 → 6.0.0-snapshot.v20251203203405
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clerk.browser.js +4 -4
- package/dist/clerk.channel.browser.js +4 -4
- package/dist/clerk.chips.browser.js +4 -4
- package/dist/clerk.headless.browser.js +4 -4
- package/dist/clerk.headless.js +2 -2
- package/dist/clerk.js +1 -1
- package/dist/clerk.legacy.browser.js +1 -1
- package/dist/clerk.mjs +1 -1
- package/dist/clerk.no-rhc.js +1 -1
- package/dist/clerk.no-rhc.mjs +1 -1
- package/dist/types/utils/errorThrower.d.ts +1 -1
- package/dist/types/utils/web3.d.ts +2 -2
- package/package.json +3 -3
- /package/dist/{308_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 308_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{415_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 415_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 507_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 507_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 507_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 507_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{521_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 521_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 527_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 527_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 527_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 527_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 527_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{604_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 604_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{694_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 694_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{783_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 783_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{973_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 973_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
package/dist/clerk.no-rhc.mjs
CHANGED
|
@@ -16,4 +16,4 @@ ${a.message}`)}})(ex(e)):e).some(e=>e.test(ex(r.origin))));return n||Q(`Clerk: R
|
|
|
16
16
|
${e.trim()}
|
|
17
17
|
(This notice only appears in development)`,eN={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>eD(`The <${e}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`),cannotRenderAnyBillingComponent:e=>eD(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eN)){let a=eN[e];"function"!=typeof a&&(eN[e]=eD(a))}let eW="clerk:beforeunload",eL=["http:","https:","wails:","chrome-extension:"];function e$(e){let a=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eW)),window.location.href=a.href}function eK(e){return/^http(s)?:\/\//.test(e||"")}function eB(e){return e.startsWith("/")}var eJ=class{#c;#E=864e5;constructor(e){this.#c=e}isEventThrottled(e){let a=Date.now(),t=this.#M(e),r=this.#c.getItem(t);return!!r&&!(a-r>this.#E)||(this.#c.setItem(t,a),!1)}#M(e){let{sk:a,pk:t,payload:r,...i}=e,n={...r,...i};return JSON.stringify(Object.keys({...r,...i}).sort().map(e=>n[e]))}},eV=class{#R="clerk_telemetry_throttler";getItem(e){return this.#F()[e]}setItem(e,a){try{let t=this.#F();t[e]=a,localStorage.setItem(this.#R,JSON.stringify(t))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#R)}}removeItem(e){try{let a=this.#F();delete a[e],localStorage.setItem(this.#R,JSON.stringify(a))}catch{}}#F(){try{let e=localStorage.getItem(this.#R);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eG=class{#c=new Map;#D=1e4;getItem(e){return this.#c.size>this.#D?void this.#c.clear():this.#c.get(e)}setItem(e,a){this.#c.set(e,a)}removeItem(e){this.#c.delete(e)}};let eH=new Set(["error","warn","info","debug","trace"]);var eQ=class{#N;#W;#L={};#$=[];#K=null;constructor(e){this.#N={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#L.clerkVersion=e.clerkVersion??"":this.#L.clerkVersion="",this.#L.sdk=e.sdk,this.#L.sdkVersion=e.sdkVersion,this.#L.publishableKey=e.publishableKey??"";let a=eh(e.publishableKey);a&&(this.#L.instanceType=a.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#W=new eJ(eV.isSupported()?new eV:new eG)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#N.disabled||"undefined"!=typeof process&&process.env&&ei(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#N.debug||"undefined"!=typeof process&&process.env&&ei(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let a=this.#B(e.event,e.payload);if(this.#J(a.event,a),!this.#V(a,e.eventSamplingRate))return;this.#$.push({kind:"event",value:a}),this.#G()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#H(e))return;let a="string"==typeof e?.level&&eH.has(e.level),t="string"==typeof e?.message&&e.message.trim().length>0,r=null,i=e?.timestamp;if("number"==typeof i||"string"==typeof i){let e=new Date(i);Number.isNaN(e.getTime())||(r=e)}if(!a||!t||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:a,messageIsValid:t,timestampIsValid:null!==r});return}let n=this.#Q(),s={sdk:n.name,sdkv:n.version,cv:this.#L.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#L.publishableKey||null,payload:this.#Y(e.context)};this.#$.push({kind:"log",value:s}),this.#G()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#V(e,a){return this.isEnabled&&!this.isDebug&&this.#Z(e,a)}#H(e){return!0}#Z(e,a){let t=Math.random();return!!(t<=this.#N.samplingRate&&(!1===this.#N.perEventSampling||void 0===a||t<=a))&&!this.#W.isEventThrottled(e)}#G(){if("undefined"==typeof window)return void this.#X();if(this.#$.length>=this.#N.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#X();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#X(),this.#K=null}):this.#K=setTimeout(()=>{this.#X(),this.#K=null},0))}#X(){let e=[...this.#$];if(this.#$=[],this.#K=null,0===e.length)return;let a=e.filter(e=>"event"===e.kind).map(e=>e.value),t=e.filter(e=>"log"===e.kind).map(e=>e.value);a.length>0&&fetch(new URL("/v1/event",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:a})}).catch(()=>void 0),t.length>0&&fetch(new URL("/v1/logs",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:t})}).catch(()=>void 0)}#J(e,a){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(a),console.groupEnd()):console.log("[clerk/telemetry]",e,a))}#Q(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let a=window;if(a.Clerk){let t=a.Clerk;if("object"==typeof t&&null!==t&&"constructor"in t&&"function"==typeof t.constructor&&t.constructor.sdkMetadata){let{name:a,version:r}=t.constructor.sdkMetadata;void 0!==a&&(e.name=a),void 0!==r&&(e.version=r)}}}return e}#B(e,a){let t=this.#Q();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:t.name,sdkv:t.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:a}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let a=JSON.parse(JSON.stringify(e));if(a&&"object"==typeof a&&!Array.isArray(a))return a;return null}catch{return null}}};let eY="COMPONENT_MOUNTED",eZ=new Set(["SignIn","SignUp"]);function eX(e){return function(a,t,r){return{event:e,eventSamplingRate:e===eY?eZ.has(a)?1:.1:.1,payload:{component:a,appearanceProp:!!t?.appearance,baseTheme:!!t?.appearance?.baseTheme,elements:!!t?.appearance?.elements,variables:!!t?.appearance?.variables,...r}}}}function e1(e,a,t){return eX(eY)(e,a,t)}function e2(e,a,t){return eX("COMPONENT_OPENED")(e,a,t)}function e0(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e9(e,a,t){return"function"==typeof e?e(a):void 0!==e?e:void 0!==t?t:void 0}let e3=(...e)=>{},e8=!1,e5=null,e4=!1,e6=[];function e7(e,a,t,r){e8&&(e6.push({level:e,message:a,context:t,source:r,ts:Date.now()}),e6.length>200&&e6.shift())}async function ae(e){try{if(!e8||e5)return;let{getDebugLogger:a}=await Promise.resolve().then(i.bind(i,854)),t=await a({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(t&&(e5=t)&&0!==e6.length){for(let e of e6){let a={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e5.error(e.message,a,e.source);break;case"warn":e5.warn(e.message,a,e.source);break;case"info":e5.info(e.message,a,e.source);break;case"debug":e5.debug(e.message,a,e.source)}}e6.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let aa={debug(e,a,t){e5?e5.debug(e,a,t):e7("debug",e,a,t)},error(e,a,t){e5?e5.error(e,a,t):e7("error",e,a,t)},info(e,a,t){e5?e5.info(e,a,t):e7("info",e,a,t)},warn(e,a,t){e5?e5.warn(e,a,t):e7("warn",e,a,t)}},at={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,a)=>a<5,retryImmediately:!1,jitter:!0},ar=async e=>new Promise(a=>setTimeout(a,e)),ai=(e,a)=>a?e*(1+Math.random()):e,an=async(e,a={})=>{var t;let r,i=0,{shouldRetry:n,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:u}={...at,...a},h=(t={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await ar((e=ai(e=t.initialDelay*Math.pow(t.factor,r),t.jitter),Math.min(t.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!n(e,++i))throw e;u&&await u(i),c&&1===i?await ar(ai(100,d)):await h()}},as=async e=>an(e,{initialDelay:100,shouldRetry:(e,a)=>a<=3,retryImmediately:!0,factor:2});class ao{#ee={"@zxcvbn-ts/core":()=>as(()=>Promise.resolve().then(i.bind(i,10))),"@zxcvbn-ts/language-common":()=>as(()=>Promise.resolve().then(i.bind(i,655))),"@base-org/account":()=>as(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@base-org/account'");throw e.code="MODULE_NOT_FOUND",e})),"@coinbase/wallet-sdk":()=>as(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@coinbase/wallet-sdk'");throw e.code="MODULE_NOT_FOUND",e})),"@stripe/stripe-js":()=>as(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@stripe/stripe-js'");throw e.code="MODULE_NOT_FOUND",e}))};import(e){return this.#ee[e]?this.#ee[e]():Promise.resolve(void 0)}}let al=(e=!1)=>{let a,t;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(a=!1,t=()=>a=!0,{startListening:()=>{window.addEventListener("beforeunload",t),window.addEventListener(eW,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eW,t)},isUnloading:()=>a});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ac=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),ad=e=>{let a={grandTotal:ac(e.grand_total),subtotal:ac(e.subtotal),taxTotal:ac(e.tax_total)};return"past_due"in e&&(a.pastDue=e.past_due?ac(e.past_due):null),"credit"in e&&(a.credit=e.credit?ac(e.credit):null),"total_due_now"in e&&(a.totalDueNow=ac(e.total_due_now)),"total_due_after_free_trial"in e&&(a.totalDueAfterFreeTrial=e.total_due_after_free_trial?ac(e.total_due_after_free_trial):null),a};function au(e,a=""){return e.errors&&!!e.errors.find(e=>e.code===a)}let ah=function({packageName:e,customMessages:a}){let t=e;function r(e,a){if(!a)return`${t}: ${e}`;let r=e;for(let t of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(a[t[1]]||"").toString();r=r.replace(`{{${t[1]}}}`,e)}return`${t}: ${r}`}let i={...x,...a};return{setPackageName({packageName:e}){return"string"==typeof e&&(t=e),this},setMessages({customMessages:e}){return Object.assign(i,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(i.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(i.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(i.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(i.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(i.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function am(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function ap(e){let a=(e||"").split("."),[t,r,i]=a;if(3!==a.length||!t||!r||!i)throw Error("JWT could not be decoded");let n=JSON.parse(am(r)),s={__raw:e};return Object.keys(n).forEach(e=>{s[e]=n[e]}),{encoded:{header:t,payload:r,signature:i},header:JSON.parse(am(t)),claims:s}}function ag(){if(!o())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function ab(){return void 0!==globalThis.document}function af(){if(!function(){if(!ab())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var ay=class e{#ea=[];#et={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #er=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#ei),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=e=>{let a=this.#ea.find(a=>a.info.name===this.#et[e])?.provider;return void 0!==a?a:window.ethereum};#ei=e=>{this.#ea.some(a=>a.info.uuid===e.detail.info.uuid)||this.#ea.push(e.detail)}};let ak=()=>(function(e){async function a(e){let{provider:a}=e,t=await u(a);if(!t)return"";let r=await t.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function t(e){let{identifier:a,nonce:t,provider:r}=e,i=await u(r);return i?await i.request({method:"personal_sign",params:[`0x${t.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,a]}):""}async function r(){return await a({provider:"metamask"})}async function i(){return await a({provider:"coinbase_wallet"})}async function n(){return await a({provider:"okx_wallet"})}async function s(){return await a({provider:"base"})}async function o(e){return await t({...e,provider:"metamask"})}async function l(e){return await t({...e,provider:"coinbase_wallet"})}async function c(e){return await t({...e,provider:"okx_wallet"})}async function d(e){return await t({...e,provider:"base"})}async function u(a){if("coinbase_wallet"===a){let a=await e.import("@coinbase/wallet-sdk");return a?a.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===a)try{let a=await e.import("@base-org/account");if(!a)return null;return a.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__unstable__environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return ay.getInstance().get(a)}return{getWeb3Identifier:a,generateWeb3Signature:t,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:i,getOKXWalletIdentifier:n,getBaseIdentifier:s,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:d}})(new ao),aw="environment",av=JSON.stringify,aj=JSON.parse;class a_{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,a,t){try{let r={value:a,...t&&{exp:Date.now()+t}};window.localStorage.setItem(this._key(e),av(r))}catch{}}static getItem(e,a){try{let t=window.localStorage.getItem(this._key(e));if(!t)return a;let r=aj(t);if(!r)return a;if(this.isExpired(r))return this.removeItem(e),a;return r?.value??a}catch{return a}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let az="ClerkJS:";function ax(e){console.warn(`${az} ${e} is not supported in this environment.`)}function aq(e=""){throw Error(`${az} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function aS(e){throw Error(`${az} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function aU(e){throw Error(`${az} You need to start a ${e} flow by calling ${e}.create() first.`)}function aA(e,a){throw Error(`${az} Strategy "${a}" is not a valid strategy for ${e}.`)}function aC(e){throw Error(`${az} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function aI(e=""){throw Error(`${az} Missing '${e}' option`)}function aP(e,a){throw Error(`${az} Response: ${e||0} not supported yet.
|
|
18
18
|
For more information contact us at ${a}`)}function aO(e){throw Error(`${az} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}let aT=e=>Promise.reject(Error("Captcha not supported in this environment")),aE=e=>{let a=e.__unstable__environment,t=a?a.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:a?a.displayConfig.captchaPublicKey:null,captchaWidgetType:a?a.displayConfig.captchaWidgetType:null,captchaProvider:t,captchaPublicKeyInvisible:a?a.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:a?a.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class aM{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaPublicKeyInvisible:r,nonce:i}=aE(this.clerk);return t&&a&&r?{...await aT({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||i||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaWidgetType:r,captchaProvider:i,captchaPublicKeyInvisible:n,nonce:s}=aE(this.clerk);if(t&&a&&n){let t=await aT({captchaProvider:i,invisibleSiteKey:n,nonce:s||void 0,siteKey:a,widgetType:r,...e}).catch(a=>a.captchaError?{captchaError:a.captchaError}:e?.action==="verify"?{captchaError:a?.message||a||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...t,captchaAction:"verify"}:t}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class aR{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return aR.instance||(aR.instance=new aR(tI,aM)),aR.instance}constructor(e,a){this.client=e,this.CaptchaChallengeImpl=a}async execute(e,a){if(this.captchaAttemptsExceeded())throw new A("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await a()}catch(r){let t;if(!E(r)||M(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await a();this.inflightException=new Promise(e=>t=e);try{let a=await this.managedChallenge(e);a?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(a),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{t(),this.inflightException=null}return await a()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class aF{static clerk;id;pathRoot="";static get fapiClient(){return aF.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:a}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:a})}isNew(){return!this.id}static async _fetch(e,a={}){return aR.getInstance().execute(this.clerk,()=>this._baseFetch(e,a))}static async _baseFetch(e,a={}){let t;aF.fapiClient||function(){throw Error(`${az} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=a;try{t=await aF.fapiClient.request(e,{fetchMaxTries:r})}catch(a){if(this.shouldRethrowOfflineNetworkErrors())throw new A(a?.message||a,{code:"network_error"});if(!u())return aa.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw a}let{payload:i,status:n,statusText:s,headers:o}=t;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||a.forceUpdateClient)&&this._updateClient(i),n>=200&&n<=299)return i;if(n>=400){let e=i?.errors,a=e?.[0]?.long_message,t=e?.[0]?.code;401===n&&"requires_captcha"!==t&&await aF.clerk.handleUnauthenticated(),function(e,a){var t;if(!a||!a[0])return;let r=a[0],i=r.long_message;if("origin_invalid"===r.code&&((t=aF.clerk.publishableKey).startsWith("live_")||t.startsWith("pk_live_"))){let t=aF.clerk.frontendApi.replace("clerk.","");throw new _(`Clerk: Production Keys are only allowed for domain "${t}".
|
|
19
|
-
API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new _(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aF.clerk&&aF.clerk.updateClient(tI.getOrCreateInstance().fromJSON(a))}path(e){let a=this.pathRoot;if(this.isNew())return a;let t=a.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?t.replace(/[^/]$/,"$&/")+encodeURIComponent(e):t}withDefault(e,a){return e??a}async _baseGet(e={}){let a=await aF._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(a?.response||a)}async _baseMutate(e){let{action:a,body:t,method:r,path:i}=e,n=await aF._fetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _baseMutateBypass(e){let{action:a,body:t,method:r,path:i}=e,n=await aF._baseFetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=aF.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aD(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aN extends aF{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?aD(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class aW extends aF{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?aD(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=w||(w={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let aL=[],{link:a$,unlink:aK,propagate:aB,checkDirty:aJ,endTracking:aV,startTracking:aG,shallowPropagate:aH}=function({update:e,notify:a,unwatched:t}){let r=0;return{link:function(e,a){let t,i=a.depsTail;if(void 0!==i&&i.dep===e)return;if(4&a.flags&&void 0!==(t=void 0!==i?i.nextDep:a.deps)&&t.dep===e){t.version=r,a.depsTail=t;return}let n=e.subsTail;if(void 0!==n&&n.version===r&&n.sub===a)return;let s=a.depsTail=e.subsTail={version:r,dep:e,sub:a,prevDep:i,nextDep:t,prevSub:n,nextSub:void 0};void 0!==t&&(t.prevDep=s),void 0!==i?i.nextDep=s:a.deps=s,void 0!==n?n.nextSub=s:e.subs=s},unlink:i,propagate:function(e){let t,r=e.nextSub;e:for(;;){let i=e.sub,n=i.flags;if(3&n&&(60&n?12&n?4&n?!(48&n)&&function(e,a){let t=a.depsTail;if(void 0!==t){let r=a.deps;do{if(r===e)return!0;if(r===t)break;r=r.nextDep}while(void 0!==r)}return!1}(e,i)?(i.flags=40|n,n&=1):n=0:i.flags=-9&n|32:n=0:i.flags=32|n,2&n&&a(i),1&n)){let a=i.subs;if(void 0!==a){e=a,void 0!==a.nextSub&&(t={value:r,prev:t},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==t;)if(e=t.value,t=t.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(a,t){let r,i=0;e:for(;;){let s=a.dep,o=s.flags,l=!1;if(16&t.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&n(e),l=!0}}else if((33&o)==33){(void 0!==a.nextSub||void 0!==a.prevSub)&&(r={value:a,prev:r}),a=s.deps,t=s,++i;continue}if(!l&&void 0!==a.nextDep){a=a.nextDep;continue}for(;i;){--i;let s=t.subs,o=void 0!==s.nextSub;if(o?(a=r.value,r=r.prev):a=s,l){if(e(t)){o&&n(s),t=a.sub;continue}}else t.flags&=-33;if(t=a.sub,void 0!==a.nextDep){a=a.nextDep;continue e}l=!1}return l}},endTracking:function(e){let a=e.depsTail,t=void 0!==a?a.nextDep:e.deps;for(;void 0!==t;)t=i(t,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:n};function i(e,a=e.sub){let r=e.dep,n=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=n:a.depsTail=n,void 0!==n?n.nextDep=s:a.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&t(r),s}function n(e){do{let t=e.sub,r=e.nextSub,i=t.flags;(48&i)==32&&(t.flags=16|i,2&i&&a(t)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?a9(e):a3(e,e.value),notify:function e(a){let t=a.flags;if(!(64&t)){a.flags=64|t;let r=a.subs;void 0!==r?e(r.sub):aL[aZ++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aK(a,e);while(void 0!==a)}}else"previousValue"in e||a6.call(e)}}),aQ=0,aY=0,aZ=0;function aX(a){let t=e;return e=a,t}function a1(e){return a4.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a2(e){return a5.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a0(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?a$(r,e):void 0!==a&&a$(r,a);let i=aX(r);try{r.fn()}finally{aX(i)}return a6.bind(r)}function a9(e){let a=aX(e);aG(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aX(a),aV(e)}}function a3(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a8(){for(;aY<aZ;){let e=aL[aY];aL[aY++]=void 0,function e(a,t){if(16&t||32&t&&aJ(a.deps,a)){let e=aX(a);aG(a);try{a.fn()}finally{aX(e),aV(a)}return}32&t&&(a.flags=-33&t);let r=a.deps;for(;void 0!==r;){let a=r.dep,t=a.flags;64&t&&e(a,a.flags=-65&t),r=r.nextDep}}(e,e.flags&=-65)}aY=0,aZ=0}function a5(){let t=this.flags;if(16&t||32&t&&aJ(this.deps,this)){if(a9(this)){let e=this.subs;void 0!==e&&aH(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?a$(this,e):void 0!==a&&a$(this,a),this.value}function a4(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aB(e),aQ||a8())}}else{let a=this.value;if(16&this.flags&&a3(this,a)){let e=this.subs;void 0!==e&&aH(e)}return void 0!==e&&a$(this,e),a}}function a6(){let e=this.deps;for(;void 0!==e;)e=aK(e,this);let a=this.subs;void 0!==a&&aK(a),this.flags=0}function a7(e){let{pageSize:a,initialPage:t,...r}=e||{},i=a??10;return new URLSearchParams({...Object.entries(r).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),limit:i+"",offset:((t??1)-1)*i+""})}class te{static #en="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${te.#en}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aF._fetch({path:`${te.#en}/plans`,method:"GET",search:a7(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tw(e))}})};getPlan=async e=>new tw(await aF._fetch({path:`${te.#en}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aF._fetch({path:te.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new t_(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/statements",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};getStatement=async e=>new tv((await aF._fetch({path:te.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/payment_attempts",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tm(e))}})};getPaymentAttempt=async e=>new tm(await aF._fetch({path:te.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tu((await aF._fetch({path:te.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let ta=a1({resource:null}),tt=a1({error:null}),tr=a1({status:"idle"}),ti=a2(()=>{let e=ta().resource,a=tt().error,t=tr().status;return{errors:tc(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tn=a1({resource:null}),ts=a1({error:null}),to=a1({status:"idle"}),tl=a2(()=>{let e=tn().resource,a=ts().error,t=to().status;return{errors:tc(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function tc(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!E(e))return t.raw=[e],t.global=[N(e)],t;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(t.raw?t.raw.push(e):t.raw=[e],r(e)){let a=X(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[N(e)]),t}class td extends aF{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=aD(e.created_at)),e.updated_at&&(this.updatedAt=aD(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class tu extends aF{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new ty(e.payment_method):void 0,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ad(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aD(e.free_trial_ends_at)),this.payer=new td(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>an(()=>this._basePatch({path:te.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!E(e)||a>=4)return!1;let t=e?.status,r=409===t&&e.errors?.[0]?.code==="checkout_already_in_progress";return t>=500||r}})}class th{resource=new tu(null);config;signals;pendingOperations=new Map;constructor(e,a){this.config=a,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await tu.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tu(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:a}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await tu.clerk.setActive({session:tu.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tu.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,i=this.signals,n=this.pendingOperations,async(e,a,t)=>{if(n.get(e))return n.get(e);let s=(async()=>{++aQ,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aQ||a8(),++aQ;try{return await a(),i.resourceSignal({resource:r}),{error:null}}catch(e){return i.errorSignal({error:e}),{error:e}}finally{n.delete(e),i.fetchSignal({status:"idle"}),--aQ||a8()}})();return n.set(e,s),s})(e,a,t)}}class tm extends aF{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=ac(e.amount),this.paidAt=e.paid_at?aD(e.paid_at):null,this.failedAt=e.failed_at?aD(e.failed_at):null,this.updatedAt=aD(e.updated_at),this.paymentMethod=e.payment_method?new ty(e.payment_method):null,this.subscriptionItem=new tz(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tp="/payment_methods",tg=async e=>{let{orgId:a,...t}=e;return new tk((await aF._fetch({path:te.path(`${tp}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tb=async e=>{let{orgId:a,...t}=e;return new ty((await aF._fetch({path:te.path(tp,{orgId:a}),method:"POST",body:t}))?.response)},tf=async e=>{let{orgId:a,...t}=e??{};return await aF._fetch({path:te.path(tp,{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ty(e))}})};class ty extends aF{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:aD(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aD(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tO((await aF._fetch({path:te.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aF._fetch({path:te.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tk extends aF{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class tw extends aF{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=ac(e.fee),this.annualFee=e.annual_fee?ac(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ac(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new ra(e))),this}}class tv extends aF{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=aD(e.timestamp),this.totals=ad(e.totals),this.groups=e.groups.map(e=>new tj(e))),this}}class tj{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aD(e.timestamp),this.items=e.items.map(e=>new tm(e))),this}}class t_ extends aF{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=e.updated_at?aD(e.updated_at):null,this.activeAt=aD(e.active_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ac(e.next_payment.amount),date:aD(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tz(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tz extends aF{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aD(e.created_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,this.periodStart=aD(e.period_start),this.periodEnd=e.period_end?aD(e.period_end):null,this.canceledAt=e.canceled_at?aD(e.canceled_at):null,this.amount=e.amount?ac(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ac(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tO((await aF._fetch({path:te.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tx={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tx.extractTemplate(e,a,t);return{organizationId:t,sessionId:a,template:r}},extractTemplate:(e,a,t)=>{if(e===a||t&&e===`${a}-${t}`)return;let r=e.slice(a.length+1);return t&&r.endsWith(`-${t}`)&&(r=r.slice(0,-(t.length+1))),r||void 0}},tq="clerk",tS=10,tU={broadcast:!0};class tA{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tA(a,{audience:r,tokenId:t})}constructor(e,a){this.prefix=e,this.data=a,this.prefix=e,this.data=a}toKey(){let{tokenId:e,audience:a}=this.data;return[this.prefix,e,a||""].join("::")}}let tC=((e=tq)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null;return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:(t,r=tS)=>{let i=new tA(e,t),n=a.get(i.toKey());if(!n)return;let s=Math.floor(Date.now()/1e3)-n.createdAt;if(n.expiresIn-s<(r||1)+5){void 0!==n.timeoutId&&clearTimeout(n.timeoutId),a.delete(i.toKey());return}return n.entry},set:i=>{((i,n=tU)=>{let s=new tA(e,{audience:i.audience,tokenId:i.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:i.createdAt??o,entry:i,expiresIn:void 0},c=()=>{let e=a.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),a.delete(s))};i.tokenResolver.then(e=>{let a=e.jwt?.claims;if(!a||"number"!=typeof a.exp||"number"!=typeof a.iat)return c();let s=a.exp-a.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&n.broadcast){let r=e.getRawString();if(r&&a.sid){let e=a.sid,n=a.org_id||a.o?.id,s=tx.extractTemplate(i.tokenId,e,n),o=tx.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;aa.info("Broadcasting token update to other tabs",{organizationId:n,sessionId:e,tabId:t,template:s,tokenId:i.tokenId,traceId:a},"tokenCache");let o={organizationId:n,sessionId:e,template:s,tokenId:i.tokenId,tokenRaw:r,traceId:a};d.postMessage(o)}}}}).catch(()=>{c()}),a.set(s,l)})(i,tU)},size:()=>a.size}})();class tI extends aF{static instance;pathRoot="/client";sessions=[];signUp=new rR;signIn=new rT;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tI.instance||(tI.instance=new tI(e)),tI.instance}static clearInstance(){tI.instance=null}static isClientResource(e){return!!e&&e instanceof tI}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{tC.clear(),this.id="",this.sessions=[],this.signUp=new rR(null),this.signIn=new rT(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(tC.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aF.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rx(e)),this.signUp=new rR(e.sign_up),this.signIn=new rT(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aD(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aD(e.created_at||void 0),this.updatedAt=aD(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class tP extends aF{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class tO{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class tT extends aF{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";experimental__forceOauthFirst;faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var tE='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let tM=(e,a={})=>{if("undefined"==typeof Worker)return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(t);return new Worker(r,a)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},tR=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tM(tE,{name:"clerk-timers"});if(n?.addEventListener("message",i),!n)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e3};let s=()=>{n||(n=tM(tE,{name:"clerk-timers"}),n?.addEventListener("message",i))};return{setTimeout:(e,i)=>{s();let o=a();return t.set(o,()=>{e(),t.delete(o)}),r(n,{type:"setTimeout",id:o,ms:i}),o},setInterval:(e,i)=>{s();let o=a();return t.set(o,e),r(n,{type:"setInterval",id:o,ms:i}),o},clearTimeout:e=>{s(),t.delete(e),r(n,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),t.delete(e),r(n,{type:"clearInterval",id:e})},cleanup:()=>{n&&(n.terminate(),n=null,t.clear())}}};function tF({delayInMs:e}={delayInMs:1e3}){let a,t=tR(),r=!1,i=()=>{a&&(t.clearTimeout(a),t.cleanup()),r=!0},n=async s=>{r=!1,await s(i),r||(a=t.setTimeout(()=>{n(s)},e))};return{run:n,stop:i}}class tD extends aF{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({redirectUrl:t})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEnterpriseSSOLinkFlow:async({redirectUrl:t})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:t})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEnterpriseSSOLinkFlow:a}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new tQ(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rt(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var tN=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let a=atob(e.replace(/-/g,"+").replace(/_/g,"/")),t=a.length,r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=a.charCodeAt(e);return r.buffer}};async function tW(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new I("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"InvalidStateError"===(a=e).name?new I(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new I(a.message,{code:"passkey_registration_cancelled"}):tK(a),publicKeyCredential:null}}}let tL=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function t$({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tL.createAbortSignal()});if(!t)return{error:new I("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"NotAllowedError"===(t=e).name?new I(t.message,{code:"passkey_retrieval_cancelled"}):tK(t),publicKeyCredential:null}}}function tK(e){return"AbortError"===e.name?new I(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new I(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tB(e){let a=tH(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tH(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tJ(e){return{type:e.type,id:e.id,rawId:tG(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tV(e){let a=e.response;return{...tJ(e),response:{clientDataJSON:tG(a.clientDataJSON),authenticatorData:tG(a.authenticatorData),signature:tG(a.signature),userHandle:a.userHandle?tG(a.userHandle):null}}}let tG=tN.encode.bind(tN),tH=tN.decode.bind(tN);class tQ extends aF{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===aF.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=aD(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class tY extends tQ{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var a;let t,r,i;return super.fromJSON(e),e?.nonce&&(this.publicKey=(t=tH((a=JSON.parse(e.nonce)).user.id),r=tH(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tH(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new tX(e.email_address),this.phoneNumber=new tX(e.phone_number),this.web3Wallet=new tX(e.web3_wallet),this.externalAccount=new tQ(e.external_account)):(this.emailAddress=new tX(null),this.phoneNumber=new tX(null),this.web3Wallet=new tX(null),this.externalAccount=new tQ(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class tX extends tQ{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class t1 extends aF{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?aD(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tQ(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t2(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class t2 extends aF{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let t0="token:update",t9="user:signOut",t3="environment:update",t8="session:tokenResolved",t5=g();class t4 extends aF{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class t6 extends aF{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class t7 extends aF{static instance;authConfig=new aW;displayConfig=new tT;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rV;organizationSettings=new t6;commerceSettings=new tP;apiKeysSettings=new t4;protectConfig=new rf;static getInstance(){return t7.instance||(t7.instance=new t7),t7.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aW(e.auth_config),this.displayConfig=new tT(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new t6(e.organization_settings),this.userSettings=new rV(e.user_settings),this.commerceSettings=new tP(e.commerce_settings),this.apiKeysSettings=new t4(e.api_keys_settings),this.protectConfig=new rf(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t5.emit(t3,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}}class re extends aF{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:a,redirectUrl:t}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:a,redirect_url:t}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new tQ(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class ra extends aF{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class rt extends aF{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class rr extends aF{id;name=null;publicUrl=null;static async create(e,a={}){let t,r=a;return"string"==typeof a.file?(r=a.file,t=new Headers({"Content-Type":"application/octet-stream"})):a.file&&(r=new FormData).append("file",a.file),new rr((await aF._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new rr((await aF._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class ri extends aF{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new ri((await aF._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:a}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:aD(e.verification.expires_at)}:this.verification=null),this}}class rn extends aF{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.public_user_data&&(this.publicUserData=new ry(e.public_user_data))),this}}class rs extends aF{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class ro extends aF{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new rs(e)),this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rl extends aF{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rl((await aF._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rl((await aF._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aF._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ro(e))}});getDomains=async e=>await aF._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ri(e))}});getDomain=async({domainId:e})=>new ri((await aF._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aF._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});createDomain=async e=>ri.create(this.id,{name:e});getMemberships=async e=>await aF._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});getInvitations=async e=>await aF._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(e))}});addMember=async({userId:e,role:a})=>await aF._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rd(e?.response));inviteMember=async e=>rc.create(this.id,e);inviteMembers=async e=>rc.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aF._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rd(e?.response));removeMember=async e=>await aF._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rd(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aF._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rl(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aF._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rl(e?.response)))};initializePaymentMethod=e=>tg({...e,orgId:this.id});addPaymentMethod=e=>tb({...e,orgId:this.id});getPaymentMethods=e=>tf({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:a}=e||{},t=(await aF._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rc extends aF{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rc((await aF._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:a,role:t}}))?.response)}static async createBulk(e,a){let{emailAddresses:t,role:r}=a;return((await aF._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rc(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rd extends aF{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aF._fetch({path:"/me/organization_memberships",method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rl(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new ry(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${az} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class ru extends aF{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aF._fetch({path:"/me/organization_suggestions",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}function rh(){return c()&&"function"==typeof window.PublicKeyCredential}async function rm(){try{return rh()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rp(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rg extends aF{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aF._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rg(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tJ(a),response:{clientDataJSON:tG(t.clientDataJSON),attestationObject:tG(t.attestationObject),transports:t.getTransports()}});return aF._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rg(e?.response))}static async registerPasskey(){let e=rg.clerk.__internal_isWebAuthnSupported||rh,a=rg.clerk.__internal_createPublicCredentials||tW,t=rg.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rp;if(!e())throw new I("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aO("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new I("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await a(n);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new tO((await aF._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.verification&&(this.verification=new tY(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rb extends aF{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};setReservedForSecondFactor=e=>{let{reserved:a}=e||{};return this._basePatch({body:{reserved_for_second_factor:a}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new tQ(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rt(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rf extends aF{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class ry{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rk={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},rw=new Set(["first_factor","second_factor","multi_factor"]),rv=new Set(["strict_mfa","strict","moderate","lax"]),rj=(e,a)=>{let{org:t,user:r}=r_(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},r_=e=>{let a=e?e.split(",").map(e=>e.trim()):[];return{org:a.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:a.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rz extends aF{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tQ(null);secondFactorVerification=new tQ(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rx(e.session),this.level=e.level,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new tQ(e.first_factor_verification),this.secondFactorVerification=new tQ(e.second_factor_verification)),this}}class rx extends aF{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rx}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(tC.clear(),this._basePost({action:"end"}));remove=()=>(tC.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t5.emit(t0,{token:e.lastActiveToken}),e));clearCache=()=>tC.clear();getToken=async e=>an(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!O(e)&&a<=8});checkAuthorization=e=>{let a,t=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(a={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:t?.id,orgRole:t?.role,orgPermissions:t?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!a.userId)return!1;let t=((e,a)=>{let{features:t,plans:r}=a;return e.feature&&t?rj(t,e.feature):e.plan&&r?rj(r,e.plan):null})(e,a),r=((e,a)=>{let{orgId:t,orgRole:r,orgPermissions:i}=a;return(e.role||e.permission)&&t&&r&&i?e.permission?i.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,a),i=((e,{factorVerificationAge:a})=>{if(!e.reverification||!a)return null;let t=(e=>{let a,t;if(!e)return!1;let r="string"==typeof e&&rv.has(e),i="object"==typeof e&&(a=e.level,rw.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rk[e]:e).bind(null,e)})(e.reverification);if(!t)return null;let{level:r,afterMinutes:i}=t(),[n,s]=a,o=-1!==n?i>n:null,l=-1!==s?i>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,a);return[t||r,i].some(e=>null===e)?[t||r,i].some(e=>!0===e):[t||r,i].every(e=>!0===e)})(e)};#es=e=>{e&&tC.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tx.build(this.id,e,t)}startVerification=async({level:e})=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let a;switch(e.strategy){case"email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":a={};break;case"enterprise_sso":a={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:aA("Session.prepareFirstFactorVerification",e.strategy)}return new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let a;return a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tV(e.publicKeyCredential))}:{...e},new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,a=rx.clerk.__internal_isWebAuthnSupported||rh,t=rx.clerk.__internal_getPublicCredentials||t$;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tB(JSON.parse(e)):null;r||aO("get");let{publicKeyCredential:i,error:n}=await t({publicKeyOptions:r,conditionalUI:!1});if(!i)throw n;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:i})};prepareSecondFactorVerification=async e=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aD(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.user=new r$(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new ry(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rN(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:a,template:t,skipCache:r=!1}=e||{},i=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!t&&Number(a)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let n=this.#eo(t,i),s=r?void 0:tC.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){aa.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t5.emit(t0,{token:e}),e.getRawString()||null}aa.info("Fetching new token from API",{organizationId:i,template:t,tokenId:n},"session");let l=t?`${this.path()}/tokens/${t}`:`${this.path()}/tokens`,c=t?{}:{organizationId:i},d=rN.create(l,c,r);return tC.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t5.emit(t0,{token:e}),e.jwt&&(this.lastActiveToken=e,t5.emit(t8,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rq extends aF{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aF.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rq(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let a;return e?(this.id=e.id,this.status=e.status,this.expireAt=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.lastActiveAt=aD(e.last_active_at||void 0),this.latestActivity={id:(a=e.latest_activity??{}).id,deviceType:a.device_type,browserName:a.browser_name,browserVersion:a.browser_version,country:a.country,city:a.city,isMobile:a.is_mobile,ipAddress:a.ip_address},this.actor=e.actor,this):this}}let rS=(e,a,t)=>{let{onValidation:r=e3,onValidationComplexity:i=e3}=t||{},{show_zxcvbn:n,validatePassword:s}=a,o=e=>((e,a)=>{let{max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o}=a,l=(e=>{let a;if(e.allowed_special_characters){let t=e.allowed_special_characters.replace("[","\\[");t=t.replace("]","\\]"),a=RegExp(`[${t}]`)}else a=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:t,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=t,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:a.test(e)})})(a)(e,{maxLength:a.max_length,minLength:a.min_length}),c={max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o},d=new Map;for(let e in c)c[e]&&!l[e]&&d.set(e,!0);return Object.freeze(Object.fromEntries(d))})(e,a),l=(({min_zxcvbn_strength:e,onResult:a})=>t=>r=>{let i=t(r);return(a?.(i),i.score>=e&&i.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:i}:i.score>=e?{state:"excellent",result:i}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...i.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:i}})(a),c={};return(a,t)=>{let{onValidation:d=r,onValidationComplexity:u=i}=t||{};if(!s)return;let h=o(a);u(0===Object.keys(h).length),c={...c,complexity:h},n&&e().then(e=>{let t=l(e)(a);d({...c={...c,strength:t},strength:t})}),c.complexity&&0===Object.keys(c.complexity).length&&n||d(c)}};function rU(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rA(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rU(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",a);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${n}/popup-callback`),d=e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(l)}`),u=async a=>{if(a.origin!==n)return;let t=!1;if(a.data.session){if(!e.client?.sessions.find(e=>e.id===a.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:a.data.session,redirectUrl:r.redirectUrlComplete}),t=!0}else a.data.return_url&&(e.navigate(a.data.return_url),t=!0);t&&window.removeEventListener("message",u)};window.addEventListener("message",u),await t({...r,redirectUrlComplete:c,redirectUrl:d},i)}function rC(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rU(e.frontendApi),i=new URL(a);i.searchParams.set("sign_in_force_redirect_url",t),i.searchParams.set("sign_up_force_redirect_url",t);let n=e.buildUrlWithAuth(i.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(n)}`),redirectUrl:s}}function rI(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rU(e.frontendApi)&&(a.data.session||a.data.return_url?(window.removeEventListener("message",i),t()):r())};window.addEventListener("message",i),a.popup.location.href=a.externalVerificationRedirectURL.toString()})}async function rP(e,a){t5.emit("resource:error",{resource:e,error:null}),t5.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t5.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t5.emit("resource:fetch",{resource:e,status:"idle"})}}let rO=()=>{var e;return(e=new ao,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,a])=>{if(!e||!a)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:t,zxcvbn:r}=e,{dictionary:i,adjacencyGraphs:n}=a;return t.setOptions({dictionary:{...i},graphs:n}),r})}).loadZxcvbn};class rT extends aF{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tQ(null);secondFactorVerification=new tQ(null);identifier=null;createdSessionId=null;userData=new rK(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rE(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{aa.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ag();return this._basePost({path:this.pathRoot,body:a?{locale:a,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let a;switch(aa.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":a={};break;case"email_link":a={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":a={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":a={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":a={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:aA("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return aa.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tV(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aU("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status,s=n?"secondFactorVerification":"firstFactorVerification";return n?await this.prepareSecondFactor(i):await this.prepareFirstFactor(i),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEmailLinkFlow:a}};prepareSecondFactor=e=>(aa.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(aa.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,a)=>{let{strategy:t,redirectUrlComplete:r,identifier:i,oidcPrompt:n,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rT.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:t,identifier:i,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===t&&await this.prepareFirstFactor({strategy:t,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:n,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?a(d):aP(c,rT.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rA(rT.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e.toString()})};authenticateWithWeb3=async e=>{let a,{identifier:t,generateSignature:r,strategy:i="web3_metamask_signature"}=e||{},n=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aI("generateSignature"),await this.create({identifier:t});let s=this.supportedFirstFactors?.find(e=>e.strategy===i);s||aC("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||aC("SignIn");try{a=await r({identifier:t,nonce:o,provider:n})}catch(e){if("coinbase_wallet"===n&&4001===e.code)a=await r({identifier:t,nonce:o,provider:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rT.clerk.__internal_isWebAuthnSupported||rh,r=rT.clerk.__internal_getPublicCredentials||t$,i=rT.clerk.__internal_isWebAuthnAutofillSupported||rm;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===a||"discoverable"===a)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${az} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:n}=this.firstFactorVerification,s=n?tB(JSON.parse(n)):null;s||aO("get");let o=!1;"autofill"===a&&(o=await i());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,a)=>{if(rT.clerk.__unstable__environment?.userSettings.passwordSettings)return rS(rO(),{...rT.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new tQ(e.first_factor_verification),this.secondFactorVerification=new tQ(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rK(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t5.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:et(this.supportedFirstFactors),supported_second_factors:et(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rE{resource;emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eO("__clerk_status"),a=eO("__clerk_created_session");if(!e||!a)return null;let t="verified"===e&&void 0!==rT.clerk.client&&rT.clerk.client.sessions.some(e=>e.id===a);return{status:e,createdSessionId:a,verifiedFromTheSameClient:t}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rP(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new A("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.resource.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:a,signOutOfOtherSessions:t=!0}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ag();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rP(this.resource,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rP(this.resource,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.resource.identifier,r=ag();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.resource.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new A("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:a,verificationUrl:t,emailAddressId:r}=e;if(!this.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new A("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rP(this.resource,async()=>{let{run:e,stop:a}=tF();await new Promise((t,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(a(),t(e))}catch(e){a(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:a,phoneNumberId:t,channel:r="sms"}=e;if(!this.resource.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,popup:i,oidcPrompt:n,enterpriseConnectionId:s,identifier:o}=e;return rP(this.resource,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rT.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rC(rT.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=a.redirectCallbackUrl,l.actionCompleteRedirectUrl=a.redirectUrl}await this._create({strategy:a,...l,identifier:o}),"enterprise_sso"===a&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(i?(await rI(rT.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.resource.reload()):e$(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rP(this.resource,async()=>{let e,r,i;switch(t){case"metamask":e=await ak().getMetamaskIdentifier(),r=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),r=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),r=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),r=ak().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:e});let n=this.resource.supportedFirstFactors?.find(e=>e.strategy===a);if(!n)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:n.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await r({identifier:e,nonce:s})}catch(a){if("coinbase_wallet"===t&&4001===a.code)i=await r({identifier:e,nonce:s});else throw a}await this.resource.__internal_basePost({body:{signature:i,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rT.clerk.__internal_isWebAuthnSupported||rh,r=rT.clerk.__internal_getPublicCredentials||t$,i=rT.clerk.__internal_isWebAuthnAutofillSupported||rm;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rP(this.resource,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new A("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tB(JSON.parse(e)):null;if(!t)throw new A("Missing public key options",{code:"missing_public_key_options"});let n=!1;"autofill"===a&&(n=await i());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:t,conditionalUI:n});if(!s)throw new I(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tV(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rP(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.resource.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rP(this.resource,async()=>{rT.clerk.client&&!rT.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rT.clerk.client.reload(),this.#el=!0,await rT.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.resource.supportedFirstFactors)return null;if(a){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.resource.identifier);if(r)return r;let i=this.resource.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rM(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rR extends aF{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tZ(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rF(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{aa.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ag();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rR.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rM(a)})};prepareVerification=e=>(aa.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(aa.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aU("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:a,strategy:t="web3_metamask_signature"}=e;return this.attemptVerification({signature:a,strategy:t})};authenticateWithWeb3=async e=>{let a,{generateSignature:t,identifier:r,unsafeMetadata:i,strategy:n="web3_metamask_signature",legalAccepted:s}=e||{},o=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aI("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:c}=this.verifications.web3Wallet;c||aC("SignUp");try{a=await t({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)a=await t({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,a)=>{let{redirectUrl:t,redirectUrlComplete:r,strategy:i,continueSignUp:n=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,u=rR.clerk.buildUrlWithAuth(t),h=()=>{let e={strategy:i,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return n&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(E(e)&&P(e))return await rR.clerk.__unstable__environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aP(g,rR.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rA(rR.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rM(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rR.clerk.__unstable__environment?.userSettings.passwordSettings)return rS(rO(),{...rR.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new tZ(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),t5.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rR.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rR.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rR.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aF._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rD(e)))}class rF{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new aM(rR.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:t,captchaToken:r,captchaWidgetType:i}=a;return{captchaToken:r,captchaWidgetType:i,captchaError:t}}async _create(e){let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={transfer:e.transfer,captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0,locale:e.locale??ag()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})}async create(e){return rP(this.resource,async()=>{await this._create(e)})}async update(e){return rP(this.resource,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:a})})}async password(e){return rP(this.resource,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})})}async sendEmailCode(){return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rP(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:a},action:"attempt_verification"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rP(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:u}=await this.getCaptchaToken(),h=t;try{new URL(t)}catch{h=window.location.origin+t}let m={redirectUrl:rR.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rC(rR.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(E(e)&&P(e))return await rR.clerk.__unstable__environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.resource.verifications.externalAccount;"unverified"===g&&b&&(c?(await rI(rR.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.resource.reload()):e$(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rP(this.resource,async()=>{let e,n,s;switch(i){case"metamask":e=await ak().getMetamaskIdentifier(),n=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),n=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),n=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),n=ak().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||aC("SignUp");try{s=await n({identifier:e,nonce:l})}catch(a){if("coinbase_wallet"===i&&4001===a.code)s=await n({identifier:e,nonce:l});else throw a}await this.resource.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rP(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rR.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}}class rD extends aF{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rN extends aF{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rN(await aF._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ap(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ap(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rW extends aF{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class rL extends aF{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class r$ extends aF{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof r$}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tD:return this.primaryEmailAddressId===e.id;case rb:return this.primaryPhoneNumberId===e.id;case rH:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tD({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rg.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rb({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rH({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new re((await aF._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rW((await aF._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rW((await aF._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tO((await aF._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rL((await aF._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rM(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(t5.emit(t9,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rq.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?rr.delete(`${this.path()}/profile_image`):rr.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rB.retrieve(e);getOrganizationSuggestions=e=>ru.retrieve(e);getOrganizationMemberships=e=>rd.retrieve(e);leaveOrganization=async e=>new tO((await aF._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tg(e);addPaymentMethod=e=>tb(e);getPaymentMethods=e=>tf(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:a,name:t})=>t||[e,a].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new tD(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rb(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rH(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new re(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rg(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rd(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t1(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=aD(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aD(e.legal_accepted_at)),this.updatedAt=aD(e.updated_at||void 0),this.createdAt=aD(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rK{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rB extends aF{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aF._fetch({path:"/me/organization_invitations",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rB(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}let rJ={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class rV extends aF{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...rJ,name:"phone_number"},username:{...rJ,name:"username"},web3_wallet:{...rJ,name:"web3_wallet"},first_name:{...rJ,name:"first_name"},last_name:{...rJ,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...rJ,name:"authenticator_app"},backup_code:{...rJ,name:"backup_code"},passkey:{...rJ,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rG extends aF{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}static async join(e){return new rG((await aF._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rH extends aF{id;web3Wallet="";verification;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:a}=e;return this._basePost({action:"attempt_verification",body:{signature:a}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new tQ(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rQ(e,a){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||(t=a,r=e,t.organizationMemberships.length!==r.organizationMemberships.length||t.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function rY(e,a){return!function(e,a){if(!e&&a||e&&!a)return!0;if(!e&&e===a)return!1;if(!e||!a)return!0;try{if(tI.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rx.isSessionResource(e)){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==a.lastActiveToken?.jwt?.claims?.__raw||function(e,a){if(e.lastActiveOrganizationId!==a.lastActiveOrganizationId)return!0;let t=e.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId),r=a.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId);return t?.permissions?.length!==r?.permissions?.length}(e,a)||(t=e,r=a,!!t.user!=!!r.user||!!t.user&&!!r.user&&rQ(t.user,r.user))}if(r$.isUserResource(e))return rQ(e,a)}catch{}return!0}(e,a)?e:a}let rZ="__clerk_db_jwt";function rX(e,a){let t=new URL(e),r=t.searchParams.get(rZ);t.searchParams.delete(rZ);let i=r||a;return i&&t.searchParams.set(rZ,i),t}let r1=e=>{let a=new URL(e);return a.searchParams.delete(rZ),a},r2=e=>{let a=new URL(e);return a.searchParams.delete("__dev_session"),a.hash=decodeURI(a.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),a.href.endsWith("#")&&(a.hash=""),a};function r0(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)e[r]=t[r]}return e}var r9=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r0({},t,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var s in i)i[s]&&(n+="; "+s,!0!==i[s]&&(n+="="+i[s].split(";")[0]));return document.cookie=e+"="+a.write(r,e)+n}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],r={},i=0;i<t.length;i++){var n=t[i].split("="),s=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=a.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,a){r(e,"",r0({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r0({},this.attributes,a))},withConverter:function(a){return e(r0({},this.converter,a),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(a)}})}({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:"/"});function r3(e){return{get:()=>r9.get(e),set(a,t={}){r9.set(e,a,t)},remove(a){r9.remove(e,a)}}}let r8=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r5(e,a){let t=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return t.setFullYear(t.getFullYear()+a),t}let r4=r3("__clerk_test_etld"),r6="__client_uat",r7="__session",ie=()=>{let e=af()?"None":"Lax",a=r8(e);return{sameSite:e,secure:a,partitioned:!1}};async function ia(e){let a;try{a=await ep(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,H.has(t)||(console.log(t),H.add(t));let{default:r}=await Promise.resolve().then(i.t.bind(i,180,23)),{default:n}=await Promise.resolve().then(i.t.bind(i,413,23)),s=r(e);a=n.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return a}let it=()=>{let e=af()?"None":"Lax",a=r8(e);return{sameSite:e,secure:a}};var ir=i(945),ii=i.n(ir);class is{lock=(k="clerk.lock.refreshSessionToken",s=new(ii()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(k)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,t=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(k,{signal:a.signal},async()=>(clearTimeout(t),await e())).catch(()=>!1)}if(await s.acquireLock(k,5e3))try{return await e()}finally{await s.releaseLock(k)}}});workerTimers=tR();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let a=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(a,5e3)};a()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class io{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await ia(e.publishableKey),n=new io(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){let s,o,l,c,d,u,h;this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t5.on(t0,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t5.on(t9,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=r3(r6),o=r3(eg(r6,r)),{set:e=>{let a=r5(Date.now(),1),r=af()?"None":"Strict",i=r8(r),n=function(e=window.location.hostname,a=r4){if(t)return t;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),o.remove(),s.remove(),o.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i}),s.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=r3(r7),c=r3(eg(r7,r)),{set:e=>{let a=r5(Date.now(),1),{sameSite:t,secure:r,partitioned:i}=ie();i&&d(),l.set(e,{expires:a,sameSite:t,secure:r,partitioned:i}),c.set(e,{expires:a,sameSite:t,secure:r,partitioned:i})},remove:d=()=>{let e=ie();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(u=r3("clerk_active_context"),h={secure:r8("None")},{set:e=>{u.set(e,h)},get:()=>u.get(),remove:()=>u.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r3(rZ),i=r3(eg(rZ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r5(Date.now(),1),{sameSite:t,secure:n}=it();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=it();i.remove(e),r.remove(e)}});function s(){return n.get()}function o(e){n.set(e)}function l(){n.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ew(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=rX(e.url,a))}),t.onAfterResponse((e,a)=>{let t=a?.headers?.get("Clerk-Db-Jwt");t&&o(t)});let i=(r=(e=new URL(window.location.href)).searchParams.get(rZ)||"",r1(r2(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r1(r2(e))),r);if(i)return void o(i);if(n.get())return;let l=t.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await c.json()).errors);e[0]?aq(e[0].longMessage):aq()}let d=await c.json();o(d?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:a,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let a=this.devBrowser.getDevBrowserJWT();if(!a)throw Error(`${az} Missing dev browser jwt. Please contact support.`);return rX(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new is,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||u()||aa.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(E(e)||M(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(O(e))return void this.clerk.handleUnauthenticated().catch(e3);this.clerkEventBus.emit(b,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class il{clerk;captchaChallenge;timers;constructor(e,a=new aM(e),t=tR()){this.clerk=e,this.captchaChallenge=a,this.timers=t}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ic=["/client","/waitlist"];class id{async getBaseFapiProxyOptions(){let e=await aF.clerk.session?.getToken();if(!e)throw new A("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return aF._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a7({...e,subject:e?.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aN(e))}})}async create(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iu=new Map;class ih{#ec=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#ec){if(o())for(let e of(this.#ec=!0,a.loaders))try{this.applyLoader(e)}catch(e){Q(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let a=e.rollout;if("number"!=typeof a||a<0)return void Q(`[protect] loader rollout value is invalid: ${a}`);if(0===a||Math.random()>a)return}let a=e.type||"script",t=e.target||"body",r=document.createElement(a);if(e.attributes)for(let[a,t]of Object.entries(e.attributes))switch(typeof t){case"string":case"number":case"boolean":r.setAttribute(a,String(t));break;default:Q(`[protect] loader attribute is invalid type: ${a}=${t}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),t){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(t?.startsWith("#")){let e=document.getElementById(t.substring(1));if(!e)return void Q(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}Q(`[protect] loader target is invalid: ${t}`)}}}class im{signInResourceSignal=ta;signInErrorSignal=tt;signInFetchSignal=tr;signInSignal=ti;signUpResourceSignal=tn;signUpErrorSignal=ts;signUpFetchSignal=to;signUpSignal=tl;__internal_effect=a0;__internal_computed=a2;constructor(){t5.on("resource:update",this.onResourceUpdated),t5.on("resource:error",this.onResourceError),t5.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rT&&this.signInErrorSignal({error:e.error}),e.resource instanceof rR&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rT){if(ip(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rR){if(ip(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rT&&this.signInFetchSignal({status:e.status}),e.resource instanceof rR&&this.signUpFetchSignal({status:e.status})}}function ip(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ig="cannot_render_billing_disabled",ib="cannot_render_user_missing",iy="cannot_render_organizations_disabled",ik="cannot_render_organization_missing",iw="cannot_render_single_session_enabled",iv={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class ij{static version="6.0.0-canary-core3.v20251203181537";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary-core3.v20251203181537"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new im;internal_last_error=null;environment;#ed;#eu="";#eh;#em;#ep;#eg;#eb;#ef=null;#ey;#ek;#ew;#ev="loading";#ej=[];#e_=[];#ez={};#ex=null;#eq=0;#eS=g();get __internal_queryClient(){return this.#ed||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eS.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eu}get version(){return ij.version}set sdkMetadata(e){ij.sdkMetadata=e}get sdkMetadata(){return ij.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ev}get isSatellite(){return!!ab()&&e9(this.#ez.isSatellite,new URL(window.location.href),!1)}get domain(){if(ab()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e9(this.#eh,new URL(window.location.href)));if("production"===this.#ew){let a;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))a=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;a=/^(clerk\.)*/gi}return`clerk.${e.replace(a,"")}`}return e}return""}get proxyUrl(){if(ab()){let e=e9(this.#em,new URL(window.location.href));return!e||eK(e)||eB(e)||ah.throwInvalidProxyUrl({url:e}),e?eB(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eh(this.publishableKey);return e?e.frontendApi:ah.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ew}get isStandardBrowser(){return this.#ez.standardBrowser||!1}get billing(){return ij._billing||(ij._billing=new te),ij._billing}get apiKeys(){return ij._apiKeys||(ij._apiKeys=new id),ij._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,a){let t,r,i,n,{for:s,planId:o,planPeriod:l}=a;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:a,orgId:t,planId:r,planPeriod:i}=e;return`${a}-${t||"user"}-${r}-${i}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),d=iu.get(c);if(d)return d.signals.computedSignal();let u=(t=a1({resource:null}),r=a1({error:null}),i=a1({status:"idle"}),n=a2(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tc(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new th(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return iu.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#ez[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ah.throwMissingPublishableKeyError();let t=eh(e);if(!t)return ah.throwInvalidPublishableKeyError({key:e});this.#eh=a?.domain,this.#em=a?.proxyUrl,this.environment=t7.getInstance(),this.#ew=t.instanceType,this.#eu=e,this.#ek=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...a].filter(e=>e))if(await t(e)===!1)return!1;return!0}async function i(e,a){for await(let r of["undefined"!=typeof window&&window.__unstable__onAfterResponse,...t].filter(e=>e))if(await r(e,a)===!1)return!1;return!0}function n({method:a,path:t,sessionId:r,search:i,rotatingTokenNonce:n}){let s=new URLSearchParams(i);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-canary-core3.v20251203181537"),n&&s.append("rotating_token_nonce",n),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),a&&"GET"!==a&&"POST"!==a&&s.append("_method",a),t&&!ic.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),ef([...s.entries()].reduce((e,[a,t])=>(e[a]=t.includes(",")?t.split(","):t,e),{}))}function s(a){let{path:t,pathPrefix:r="v1"}=a;if(e.proxyUrl){let i=new URL(e.proxyUrl),s=i.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),e_({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return e_({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ef(c,{keyEncoder:ee}):c);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(d()?4:11);n=await an(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(a,t)=>"GET"===h&&t<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else n=new Response("{}",o)}catch(a){let e=m.toString();aa.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${az} Network error at "${e}" - ${a}. Please try again.`)}let g=204!==n.status?await n.json():null,b=Object.assign(n,{payload:g});return n.ok||aa.error("request failed",{method:l,path:o.path,status:n.status},"fapiClient"),await i(o,b),b}return{buildEmailAddress:function(a){return function({localPart:e,frontendApi:a}){return`${e}@${a?a.replace("clerk.",""):"clerk.com"}`}({localPart:a,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){t.push(e)},onBeforeRequest:function(e){a.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eS.emit(b,"loading"),this.#eS.prioritizedOn(b,e=>this.#ev=e),aF.clerk=this,this.#eg=new ih}getFapiClient=()=>this.#ek;load=async e=>{if(aa.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ew&&Q("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#ez=this.#eU(e),this.#ez.clerkUiCtor&&(this.#ey=Promise.resolve(this.#ez.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#ez,new ao))),"development"===this.#ew&&(this.#ez.routerPush||this.#ez.routerReplace)&&(!this.#ez.routerPush||!this.#ez.routerReplace)){let e=this.#ez.routerPush?"routerReplace":"routerPush";Q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t5.on(t8,()=>{this.#eA(this.session),this.#eC()}),this.#ez.sdkMetadata&&(ij.sdkMetadata=this.#ez.sdkMetadata),!1!==this.#ez.telemetry&&(this.telemetry=new eQ({clerkVersion:ij.version,samplingRate:1,perEventSampling:!this.#ez.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#ez.telemetry}),this.#ez.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme||e.baseTheme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e0(e);if(t){a=t;break}}else a=e0(t);return{themeName:a}}(this.#ez.appearance)}));try{this.#ez.standardBrowser?await this.#eI():await this.#eP();let e=this.#ez.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#ez.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,i=this.environment?.isProduction?.()??!1,n=r||t&&!i,s=t&&!r?"error":void 0;n&&function(e={}){if(e4)return;let{enabled:a=!1,...t}=e;a&&(e8=!0,e4=!0,ae(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),aa.info("load() complete",{},"clerk")}catch(e){throw this.#eS.emit(b,"error"),aa.error("load() failed",{error:e},"clerk"),e}}};#eO(){let e;return!!(!this.#ez.signUpUrl&&this.#ez.signInUrl&&(e=this.#ez.signInUrl,!eb.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e3,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();aa.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:n,sessionTarget:i?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=al(this.#ez.standardBrowser);t5.emit(t9,null),this.#eT(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eA(),this.#eC(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#ez.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),aa.info("signOut() complete",{redirectUrl:ez(n)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===i.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),aa.info("signOut() complete",{redirectUrl:ez(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e2("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(W(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotOpenSignInOrSignUp,{code:iw});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eO()};this.telemetry?.record(e2("SignIn",e,a))};closeSignIn=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("Checkout"),{code:ig});return}if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenCheckout,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("PlanDetails"),{code:ig});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e2("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenUserProfile,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e2("UserVerification",e))};__internal_closeReverification=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ew||Q(`Clerk: "${t}" requires an active user session. Ensure a user is signed in before executing ${t}.`),"organizations"===a){let a;return(a=this.environment,a?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ew&&this.__internal_openEnableOrganizationsPrompt({caller:t,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${a}".`)};__internal_openEnableOrganizationsPrompt=e=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(ax("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(W(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotOpenSignInOrSignUp,{code:iw});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e2("SignUp",e))};closeSignUp=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenUserProfile,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e2("UserProfile",e,a))};closeUserProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iy})}});if(a){if(!this.organization){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ik});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e2("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iy})}});a&&(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e2("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(e2("Waitlist",e))};closeWaitlist=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignIn";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eO()};this.telemetry?.record(e1(t,a,r))};unmountSignIn=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserAvatar";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountUserAvatar=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignUp";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountSignUp=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenUserDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey);let t="UserProfile";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userProfile",node:e,props:a}));let r=(a?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e1(t,a,r))};unmountUserProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationProfile=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iy})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ik});return}this.assertComponentsReady(this.#ey);let i="OrganizationProfile";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(e1(i,a))};unmountOrganizationProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountCreateOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="CreateOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountCreateOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationSwitcher";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationList";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserButton";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userButton",node:e,props:a}));let r={...a?.customMenuItems?.length||0?{customItems:!0}:void 0,...a?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e1(t,a,r))};unmountUserButton=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ey);let t="Waitlist";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountWaitlist=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("PricingTable"),{code:ig});return}this.assertComponentsReady(this.#ey);let t="PricingTable";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountPricingTable=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(Q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),$(this,t=this.environment)&&K(this,t)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&K(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if($(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ey);let r="APIKeys";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountAPIKeys=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="TaskChooseOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountTaskChooseOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};setActive=async e=>{let{organization:a,redirectUrl:t,navigate:r}=e,{session:i}=e;this.__internal_setActiveInProgress=!0,aa.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof i?i:i?.id??i??null,organizationTarget:"string"==typeof a?a:a?.id??a??null,redirectUrl:t??null},"clerk");try{var n;let s;if(!this.client)throw aa.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===i&&!this.session)throw aa.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof i&&(i=this.client.sessions.find(e=>e.id===i)||null);let o="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e3,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#ez,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||Q('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==a;if(c&&d){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ab()&&globalThis.document.hasFocus()||!this.#ez.standardBrowser)&&(await this.#eE(c),c=this.#eM(c?.id)),await c?.getToken()||(u()||aa.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t5.emit(t0,{token:null}));let h=al(this.#ez.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#ez.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eT(),m){let e=t?e_({base:m,hashSearchParams:{redirectUrl:t}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(t){if(this.client.isEligibleForTouch()){let e=new URL(t,window.location.href),a=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(a)}await this.navigate(t)}}}),h.isUnloading())return;this.#eA(c),this.#eC(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var a;let t;return a=e,e=e=>{var r;t||={...e},a(t={...{client:rY((r=t).client,e.client),session:rY(r.session,e.session),user:rY(r.user,e.user),organization:rY(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(a=>a!==e)}};on=(...e)=>{this.#eS.on(...e)};off=(...e)=>{this.#eS.off(...e)};__internal_addNavigationListener=e=>(this.#e_.push(e),()=>{this.#e_=this.#e_.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ab())return;setTimeout(()=>{this.#eR()},0);let t=new URL(e,window.location.href);this.#eF.includes(t.protocol)||(console.warn(`Clerk: "${t.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),t=new URL("/",window.location.href));let r=a?.replace&&this.#ez.routerReplace?this.#ez.routerReplace:this.#ez.routerPush;if(aa.info(`Clerk is navigating to: ${t}`),this.#ez.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void e$(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:e$};return await r(ez(t),i)};buildUrlWithAuth(e){if("production"===this.#ew)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ep?this.#ep.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#ez.afterSignOutUrl?this.buildUrlWithAuth(this.#ez.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#ez.newSubscriptionRedirectUrl?this.#ez.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e_({base:this.#ez.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#ez.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#ez.afterMultiSessionSingleSignOutUrl):this.#ez.signInUrl?this.buildUrlWithAuth(e_({base:this.#ez.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let a=this.session?.currentTask;if(!a)return"";let t=this.#ez.taskUrls?.[a.key];return t||e_({base:this.buildSignInUrl(e),hashPath:eR(a)},{stringify:!0})}#eN=async()=>{if(!ab())return;let e=new URLSearchParams({[B]:"true"}),a=eO(V);a&&eK(a)||function(){throw Error(`${az} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=e_({base:eO(V),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ab())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ab())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ab())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ab())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ab())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ab())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ab())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ab())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ab())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ab())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ab())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eO("__clerk_status");if("expired"===t)throw new q(U.Expired);if("client_mismatch"===t)throw new q(U.ClientMismatch);if("verified"!==t)throw new q(U.Failed);let r=eO("__clerk_created_session"),{signIn:i,signUp:n,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===i.status||"missing_requirements"===n.status,c=e=>a&&"function"==typeof a?a(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e3;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,a,t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:i}=this.client,n="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:i,o=e=>t&&"function"==typeof t?t(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(a,{signUp:s,signIn:n,navigate:o})};_handleRedirectCallback=async(e,{signIn:a,signUp:t,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await a.reload():"signUp"===e.reloadResource&&await t.reload()}catch{}let{displayConfig:i}=this.environment,{firstFactorVerification:n}=a,{externalAccount:s}=t.verifications,o={status:t.status,missingFields:t.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},l={status:a.status,firstFactorVerificationStatus:n.status,firstFactorVerificationErrorCode:n.error?.code,firstFactorVerificationSessionId:n.error?.meta?.sessionId,sessionId:a.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||i.signInUrl),u=c(e.signUpUrl||i.signUpUrl),h=c(e.firstFactorUrl||e_({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||e_({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||e_({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eC(this.#ez,e),b=c(e.continueSignUpUrl||e_({base:i.signUpUrl,hashPath:"/continue"},{stringify:!0})),f=({missingFields:a})=>a.length?b():(({signUp:e,verifyEmailPath:a,verifyPhonePath:t,continuePath:r,navigate:i,handleComplete:n,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return n&&n();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let n=eE();if(e.unverifiedFields?.includes("email_address")&&a)return i(a,{searchParams:n});if(e.unverifiedFields?.includes("phone_number")&&t)return i(t,{searchParams:n});if(r)return i(r,{searchParams:n})}})({signUp:t,verifyEmailPath:e.verifyEmailAddressUrl||e_({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||e_({base:i.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||i.signInUrl,k=e.signUpUrl||i.signUpUrl,w=async({session:e,baseUrl:a,redirectUrl:t})=>{e.currentTask?await eF(e,{baseUrl:a,navigate:this.navigate}):await this.navigate(t)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:g.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await a.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:aS("sign in")}}let v="user_locked"===o.externalAccountErrorCode,j="user_locked"===l.firstFactorVerificationErrorCode;if(v)return u();if(j)return d();if("needs_first_factor"===l.status&&!a.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let a=await t.create({transfer:!0});switch(a.status){case"complete":return this.setActive({session:a.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return f({missingFields:a.missingFields});default:aS("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let _=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,z="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(_||z){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:_?k:y,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:a}=e.verifications;return!!a.error})(t)?u():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?f({missingFields:t.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:t,signUp:r}=this.client,i=e=>a&&"function"==typeof a?a(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:t,navigate:i})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let a=await tI.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t5.emit(t9,null),this.setActive({session:null})}catch(e){if(E(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(ax("Google One Tap"),this.client.signIn);authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=i.replace("web3_","").replace("_signature",""),u=await ak().getWeb3Identifier({provider:d});switch(d){case"metamask":o=ak().generateSignatureWithMetamask;break;case"base":o=ak().generateSignatureWithBase;break;case"coinbase_wallet":o=ak().generateSignatureWithCoinbaseWallet;break;default:o=ak().generateSignatureWithOKXWallet}let h=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),m=h(s||e_({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(a||e_({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:o,strategy:i})}catch(e){if(au(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:o,unsafeMetadata:r,strategy:i,legalAccepted:n}),a&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let g=async({session:e,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:a})=>{await g({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rl.create({name:e,slug:a});getOrganization=async e=>rl.get(e);joinWaitlist=async({emailAddress:e})=>rG.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let a=this.#ez.selectInitialSession?this.#ez.selectInitialSession(e):this.#eW(e);this.#eA(a)}if(this.client=e,this.session){let e=this.#eM(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3)(),this.#eA(e),this.session?.lastActiveToken||u()||aa.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t5.emit(t0,{token:this.session?.lastActiveToken})}this.#eC()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new t7(e)};__unstable__onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__unstable__updateProps=e=>{let a={...e,options:this.#eU({...this.#ez,...e.options})};return this.#ey?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eL=()=>{let e=new URLSearchParams({[V]:window.location.href});return e_({base:this.#ez.signInUrl,searchParams:e},{stringify:!0})};#e$=()=>{let e;if(this.proxyUrl){let a=new URL(this.proxyUrl);e=new URL(`${a.pathname}/v1/client/sync`,a.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eK=()=>"true"!==eO(B)&&!!this.isSatellite&&!!this.#ep?.isSignedOut();#eB=()=>"production"!==this.#ew&&!this.isSatellite&&!!eO(V);#eJ=async()=>{"development"===this.instanceType?await this.navigate(this.#eL()):"production"===this.instanceType&&await this.navigate(this.#e$())};#eV=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${az} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${az} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eG=()=>{this.isSatellite&&("development"!==this.#ew||this.#ez.signInUrl||function(){throw Error(`${az} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${az} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#ez.signInUrl&&this.#eV(this.#ez.signInUrl,window.location.origin))};#eI=async()=>{if(this.#ep=await io.create(this,this.#ek,this.#ew,this.#eS),this.#eG(),this.#eK())return void await this.#eJ();if(this.#eB())return void await this.#eN();this.#ex=(()=>{if(!o())return{onPageFocus:e3};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ef=new BroadcastChannel("clerk")),this.#eH();let e=function(e=window.location.hostname){if(!e)return!1;let a=ev.get(e);void 0===a&&(a=es.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||eo.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ev.set(e,a));return a}(window?.location.hostname),a="development"===this.#ew&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=t7.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=a_.getItem(aw,null);e&&this.updateEnvironment(new t7(e))}),r=async()=>tI.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(O(e))throw e;++t;let a=this.#ep?.getSessionCookie(),r=function(e){let a;try{a=new rN({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tI.clearInstance(),!a?.jwt)return tI.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:t,userId:r,orgId:i,orgRole:n,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let a,t,r,i,n=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){a=e.o?.id,r=e.o?.slg,e.o?.rol&&(t=`org:${e.o?.rol}`);let{org:n}=r_(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:a})=>{if(!e||!a)return{permissions:[],featurePermissionMap:[]};let t=e.split(",").map(e=>e.trim());return{permissions:t,featurePermissionMap:a.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(t.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});i=function({features:e,permissions:a,featurePermissionMap:t}){if(!e||!a||!t)return[];let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(i>=t.length)continue;let s=t[i];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${n}:${a[e]}`)}return r}({features:n,featurePermissionMap:o,permissions:s})}}else a=e.org_id,t=e.org_role,r=e.org_slug,i=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:a,orgRole:t,orgSlug:r,orgPermissions:i,factorVerificationAge:n}})(a.jwt.claims),c={object:"client",last_active_session_id:t,id:"client_init",sessions:[{object:"session",id:t,status:"active",last_active_organization_id:i||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:i&&o&&n?[{object:"organization_membership",id:i,role:n,permissions:s||[],organization:{object:"organization",id:i,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return tI.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ep?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ep?.startPollingForToken()}),null}),[,n]=await (i=[e,r()],Promise.all(Array.from(i).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(au(e,"requires_captcha"))await r();else throw e}if(this.#ep?.setClientUatCookieForDevelopmentInstances(),await this.#eQ())return;break}catch(e){if(au(e,"dev_browser_unauthenticated"))await this.#ep.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${az} Something went wrong initializing Clerk.`)}()}this.#eb=new il(this),this.#eb.start(),this.#eY(),this.#eZ(),this.#eX(),this.#eS.emit(b,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eP=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([t7.getInstance().fetch({touch:!1,fetchMaxTries:t}),tI.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(M(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new t7(t?.environment),tI.clearInstance(),a=tI.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eS.emit(b,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([t7.getInstance().fetch({touch:!1,fetchMaxTries:1}),tI.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eC()};#eW=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#eH=()=>{o()&&(this.#ex?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eq>Date.now())&&(this.#eq=Date.now()+5e3,this.#ez.touchSession&&this.#eE(this.session))}),this.#ef?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t5.on(t9,()=>{this.#ef?.postMessage({type:"signout"})}),t5.on(t3,()=>{a_.setItem(aw,this.environment?.__internal_toSnapshot(),864e5)}))};#eE=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{O(e)&&this.handleUnauthenticated()})};#eC=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eR=()=>{for(let e of this.#e_)e()};#eT=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eC()};#e1=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eA=e=>{this.session=e||null,this.organization=this.#e1(),this.user=this.session?this.session.user:null};#eM=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#eZ=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ey?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eX=()=>{this.#ez.__internal_keyless_claimKeylessApplicationUrl&&this.#ey?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#ez.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#ez.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#ez.__internal_keyless_dismissPrompt}})})};#eD=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#ez[e]||this.environment.displayConfig[e];this.#eO()&&(r=this.#ez.signInUrl);let i=new eC(this.#ez,a).toSearchParams(),n=new URLSearchParams(t||{}),s=e_({base:r,hashPath:this.#eO()&&"signUpUrl"===e?"/create":"",hashSearchParams:[n,i]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eQ=async()=>{var e;let a,t,r,i,n=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==n&&(e=this.frontendApi,t=(a=new URL(n,ey)).pathname,r=eU.includes(t)||eA.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#ez.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#ez.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ey),(!eU.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eU=e=>({...iv,...e,allowedRedirectOrigins:function(e,a,t){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ej(a)}`),r.push(`https://*.${ej(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eY=()=>{try{eT(B),eT(eI),eT(J),eT("__clerk_handshake"),eT("__clerk_handshake_nonce"),eT("__clerk_help")}catch{}};get #eF(){let e=eL;return this.#ez.allowedRedirectProtocols&&(e=e.concat(this.#ez.allowedRedirectProtocols)),e}}})();var s=n.c2,o=n.LR,l=n.cR,c=n.NZ,d=n.Ys,u=n.kl,h=n.$R,m=n.Cm,p=n.hl,g=n.ux,b=n.si,f=n._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,d as EmailLinkErrorCode,u as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,g as isKnownError,b as isMetamaskError,f as isUserLockedError};
|
|
19
|
+
API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new _(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aF.clerk&&aF.clerk.updateClient(tI.getOrCreateInstance().fromJSON(a))}path(e){let a=this.pathRoot;if(this.isNew())return a;let t=a.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?t.replace(/[^/]$/,"$&/")+encodeURIComponent(e):t}withDefault(e,a){return e??a}async _baseGet(e={}){let a=await aF._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(a?.response||a)}async _baseMutate(e){let{action:a,body:t,method:r,path:i}=e,n=await aF._fetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _baseMutateBypass(e){let{action:a,body:t,method:r,path:i}=e,n=await aF._baseFetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=aF.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aD(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aN extends aF{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?aD(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class aW extends aF{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?aD(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=w||(w={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let aL=[],{link:a$,unlink:aK,propagate:aB,checkDirty:aJ,endTracking:aV,startTracking:aG,shallowPropagate:aH}=function({update:e,notify:a,unwatched:t}){let r=0;return{link:function(e,a){let t,i=a.depsTail;if(void 0!==i&&i.dep===e)return;if(4&a.flags&&void 0!==(t=void 0!==i?i.nextDep:a.deps)&&t.dep===e){t.version=r,a.depsTail=t;return}let n=e.subsTail;if(void 0!==n&&n.version===r&&n.sub===a)return;let s=a.depsTail=e.subsTail={version:r,dep:e,sub:a,prevDep:i,nextDep:t,prevSub:n,nextSub:void 0};void 0!==t&&(t.prevDep=s),void 0!==i?i.nextDep=s:a.deps=s,void 0!==n?n.nextSub=s:e.subs=s},unlink:i,propagate:function(e){let t,r=e.nextSub;e:for(;;){let i=e.sub,n=i.flags;if(3&n&&(60&n?12&n?4&n?!(48&n)&&function(e,a){let t=a.depsTail;if(void 0!==t){let r=a.deps;do{if(r===e)return!0;if(r===t)break;r=r.nextDep}while(void 0!==r)}return!1}(e,i)?(i.flags=40|n,n&=1):n=0:i.flags=-9&n|32:n=0:i.flags=32|n,2&n&&a(i),1&n)){let a=i.subs;if(void 0!==a){e=a,void 0!==a.nextSub&&(t={value:r,prev:t},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==t;)if(e=t.value,t=t.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(a,t){let r,i=0;e:for(;;){let s=a.dep,o=s.flags,l=!1;if(16&t.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&n(e),l=!0}}else if((33&o)==33){(void 0!==a.nextSub||void 0!==a.prevSub)&&(r={value:a,prev:r}),a=s.deps,t=s,++i;continue}if(!l&&void 0!==a.nextDep){a=a.nextDep;continue}for(;i;){--i;let s=t.subs,o=void 0!==s.nextSub;if(o?(a=r.value,r=r.prev):a=s,l){if(e(t)){o&&n(s),t=a.sub;continue}}else t.flags&=-33;if(t=a.sub,void 0!==a.nextDep){a=a.nextDep;continue e}l=!1}return l}},endTracking:function(e){let a=e.depsTail,t=void 0!==a?a.nextDep:e.deps;for(;void 0!==t;)t=i(t,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:n};function i(e,a=e.sub){let r=e.dep,n=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=n:a.depsTail=n,void 0!==n?n.nextDep=s:a.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&t(r),s}function n(e){do{let t=e.sub,r=e.nextSub,i=t.flags;(48&i)==32&&(t.flags=16|i,2&i&&a(t)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?a9(e):a3(e,e.value),notify:function e(a){let t=a.flags;if(!(64&t)){a.flags=64|t;let r=a.subs;void 0!==r?e(r.sub):aL[aZ++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aK(a,e);while(void 0!==a)}}else"previousValue"in e||a6.call(e)}}),aQ=0,aY=0,aZ=0;function aX(a){let t=e;return e=a,t}function a1(e){return a4.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a2(e){return a5.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a0(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?a$(r,e):void 0!==a&&a$(r,a);let i=aX(r);try{r.fn()}finally{aX(i)}return a6.bind(r)}function a9(e){let a=aX(e);aG(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aX(a),aV(e)}}function a3(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a8(){for(;aY<aZ;){let e=aL[aY];aL[aY++]=void 0,function e(a,t){if(16&t||32&t&&aJ(a.deps,a)){let e=aX(a);aG(a);try{a.fn()}finally{aX(e),aV(a)}return}32&t&&(a.flags=-33&t);let r=a.deps;for(;void 0!==r;){let a=r.dep,t=a.flags;64&t&&e(a,a.flags=-65&t),r=r.nextDep}}(e,e.flags&=-65)}aY=0,aZ=0}function a5(){let t=this.flags;if(16&t||32&t&&aJ(this.deps,this)){if(a9(this)){let e=this.subs;void 0!==e&&aH(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?a$(this,e):void 0!==a&&a$(this,a),this.value}function a4(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aB(e),aQ||a8())}}else{let a=this.value;if(16&this.flags&&a3(this,a)){let e=this.subs;void 0!==e&&aH(e)}return void 0!==e&&a$(this,e),a}}function a6(){let e=this.deps;for(;void 0!==e;)e=aK(e,this);let a=this.subs;void 0!==a&&aK(a),this.flags=0}function a7(e){let{pageSize:a,initialPage:t,...r}=e||{},i=a??10;return new URLSearchParams({...Object.entries(r).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),limit:i+"",offset:((t??1)-1)*i+""})}class te{static #en="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${te.#en}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aF._fetch({path:`${te.#en}/plans`,method:"GET",search:a7(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tw(e))}})};getPlan=async e=>new tw(await aF._fetch({path:`${te.#en}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aF._fetch({path:te.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new t_(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/statements",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};getStatement=async e=>new tv((await aF._fetch({path:te.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/payment_attempts",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tm(e))}})};getPaymentAttempt=async e=>new tm(await aF._fetch({path:te.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tu((await aF._fetch({path:te.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let ta=a1({resource:null}),tt=a1({error:null}),tr=a1({status:"idle"}),ti=a2(()=>{let e=ta().resource,a=tt().error,t=tr().status;return{errors:tc(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tn=a1({resource:null}),ts=a1({error:null}),to=a1({status:"idle"}),tl=a2(()=>{let e=tn().resource,a=ts().error,t=to().status;return{errors:tc(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function tc(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!E(e))return t.raw=[e],t.global=[N(e)],t;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(t.raw?t.raw.push(e):t.raw=[e],r(e)){let a=X(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[N(e)]),t}class td extends aF{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=aD(e.created_at)),e.updated_at&&(this.updatedAt=aD(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class tu extends aF{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new ty(e.payment_method):void 0,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ad(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aD(e.free_trial_ends_at)),this.payer=new td(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>an(()=>this._basePatch({path:te.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!E(e)||a>=4)return!1;let t=e?.status,r=409===t&&e.errors?.[0]?.code==="checkout_already_in_progress";return t>=500||r}})}class th{resource=new tu(null);config;signals;pendingOperations=new Map;constructor(e,a){this.config=a,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await tu.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tu(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:a}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await tu.clerk.setActive({session:tu.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tu.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,i=this.signals,n=this.pendingOperations,async(e,a,t)=>{if(n.get(e))return n.get(e);let s=(async()=>{++aQ,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aQ||a8(),++aQ;try{return await a(),i.resourceSignal({resource:r}),{error:null}}catch(e){return i.errorSignal({error:e}),{error:e}}finally{n.delete(e),i.fetchSignal({status:"idle"}),--aQ||a8()}})();return n.set(e,s),s})(e,a,t)}}class tm extends aF{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=ac(e.amount),this.paidAt=e.paid_at?aD(e.paid_at):null,this.failedAt=e.failed_at?aD(e.failed_at):null,this.updatedAt=aD(e.updated_at),this.paymentMethod=e.payment_method?new ty(e.payment_method):null,this.subscriptionItem=new tz(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tp="/payment_methods",tg=async e=>{let{orgId:a,...t}=e;return new tk((await aF._fetch({path:te.path(`${tp}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tb=async e=>{let{orgId:a,...t}=e;return new ty((await aF._fetch({path:te.path(tp,{orgId:a}),method:"POST",body:t}))?.response)},tf=async e=>{let{orgId:a,...t}=e??{};return await aF._fetch({path:te.path(tp,{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ty(e))}})};class ty extends aF{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:aD(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aD(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tO((await aF._fetch({path:te.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aF._fetch({path:te.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tk extends aF{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class tw extends aF{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=ac(e.fee),this.annualFee=e.annual_fee?ac(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ac(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new ra(e))),this}}class tv extends aF{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=aD(e.timestamp),this.totals=ad(e.totals),this.groups=e.groups.map(e=>new tj(e))),this}}class tj{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aD(e.timestamp),this.items=e.items.map(e=>new tm(e))),this}}class t_ extends aF{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=e.updated_at?aD(e.updated_at):null,this.activeAt=aD(e.active_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ac(e.next_payment.amount),date:aD(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tz(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tz extends aF{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aD(e.created_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,this.periodStart=aD(e.period_start),this.periodEnd=e.period_end?aD(e.period_end):null,this.canceledAt=e.canceled_at?aD(e.canceled_at):null,this.amount=e.amount?ac(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ac(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tO((await aF._fetch({path:te.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tx={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tx.extractTemplate(e,a,t);return{organizationId:t,sessionId:a,template:r}},extractTemplate:(e,a,t)=>{if(e===a||t&&e===`${a}-${t}`)return;let r=e.slice(a.length+1);return t&&r.endsWith(`-${t}`)&&(r=r.slice(0,-(t.length+1))),r||void 0}},tq="clerk",tS=10,tU={broadcast:!0};class tA{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tA(a,{audience:r,tokenId:t})}constructor(e,a){this.prefix=e,this.data=a,this.prefix=e,this.data=a}toKey(){let{tokenId:e,audience:a}=this.data;return[this.prefix,e,a||""].join("::")}}let tC=((e=tq)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null;return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:(t,r=tS)=>{let i=new tA(e,t),n=a.get(i.toKey());if(!n)return;let s=Math.floor(Date.now()/1e3)-n.createdAt;if(n.expiresIn-s<(r||1)+5){void 0!==n.timeoutId&&clearTimeout(n.timeoutId),a.delete(i.toKey());return}return n.entry},set:i=>{((i,n=tU)=>{let s=new tA(e,{audience:i.audience,tokenId:i.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:i.createdAt??o,entry:i,expiresIn:void 0},c=()=>{let e=a.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),a.delete(s))};i.tokenResolver.then(e=>{let a=e.jwt?.claims;if(!a||"number"!=typeof a.exp||"number"!=typeof a.iat)return c();let s=a.exp-a.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&n.broadcast){let r=e.getRawString();if(r&&a.sid){let e=a.sid,n=a.org_id||a.o?.id,s=tx.extractTemplate(i.tokenId,e,n),o=tx.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;aa.info("Broadcasting token update to other tabs",{organizationId:n,sessionId:e,tabId:t,template:s,tokenId:i.tokenId,traceId:a},"tokenCache");let o={organizationId:n,sessionId:e,template:s,tokenId:i.tokenId,tokenRaw:r,traceId:a};d.postMessage(o)}}}}).catch(()=>{c()}),a.set(s,l)})(i,tU)},size:()=>a.size}})();class tI extends aF{static instance;pathRoot="/client";sessions=[];signUp=new rR;signIn=new rT;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tI.instance||(tI.instance=new tI(e)),tI.instance}static clearInstance(){tI.instance=null}static isClientResource(e){return!!e&&e instanceof tI}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{tC.clear(),this.id="",this.sessions=[],this.signUp=new rR(null),this.signIn=new rT(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(tC.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aF.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rx(e)),this.signUp=new rR(e.sign_up),this.signIn=new rT(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aD(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aD(e.created_at||void 0),this.updatedAt=aD(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class tP extends aF{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class tO{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class tT extends aF{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";experimental__forceOauthFirst;faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var tE='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let tM=(e,a={})=>{if("undefined"==typeof Worker)return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(t);return new Worker(r,a)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},tR=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tM(tE,{name:"clerk-timers"});if(n?.addEventListener("message",i),!n)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e3};let s=()=>{n||(n=tM(tE,{name:"clerk-timers"}),n?.addEventListener("message",i))};return{setTimeout:(e,i)=>{s();let o=a();return t.set(o,()=>{e(),t.delete(o)}),r(n,{type:"setTimeout",id:o,ms:i}),o},setInterval:(e,i)=>{s();let o=a();return t.set(o,e),r(n,{type:"setInterval",id:o,ms:i}),o},clearTimeout:e=>{s(),t.delete(e),r(n,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),t.delete(e),r(n,{type:"clearInterval",id:e})},cleanup:()=>{n&&(n.terminate(),n=null,t.clear())}}};function tF({delayInMs:e}={delayInMs:1e3}){let a,t=tR(),r=!1,i=()=>{a&&(t.clearTimeout(a),t.cleanup()),r=!0},n=async s=>{r=!1,await s(i),r||(a=t.setTimeout(()=>{n(s)},e))};return{run:n,stop:i}}class tD extends aF{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({redirectUrl:t})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEnterpriseSSOLinkFlow:async({redirectUrl:t})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:t})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEnterpriseSSOLinkFlow:a}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new tQ(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rt(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var tN=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let a=atob(e.replace(/-/g,"+").replace(/_/g,"/")),t=a.length,r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=a.charCodeAt(e);return r.buffer}};async function tW(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new I("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"InvalidStateError"===(a=e).name?new I(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new I(a.message,{code:"passkey_registration_cancelled"}):tK(a),publicKeyCredential:null}}}let tL=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function t$({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tL.createAbortSignal()});if(!t)return{error:new I("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"NotAllowedError"===(t=e).name?new I(t.message,{code:"passkey_retrieval_cancelled"}):tK(t),publicKeyCredential:null}}}function tK(e){return"AbortError"===e.name?new I(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new I(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tB(e){let a=tH(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tH(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tJ(e){return{type:e.type,id:e.id,rawId:tG(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tV(e){let a=e.response;return{...tJ(e),response:{clientDataJSON:tG(a.clientDataJSON),authenticatorData:tG(a.authenticatorData),signature:tG(a.signature),userHandle:a.userHandle?tG(a.userHandle):null}}}let tG=tN.encode.bind(tN),tH=tN.decode.bind(tN);class tQ extends aF{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===aF.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=aD(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class tY extends tQ{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var a;let t,r,i;return super.fromJSON(e),e?.nonce&&(this.publicKey=(t=tH((a=JSON.parse(e.nonce)).user.id),r=tH(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tH(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new tX(e.email_address),this.phoneNumber=new tX(e.phone_number),this.web3Wallet=new tX(e.web3_wallet),this.externalAccount=new tQ(e.external_account)):(this.emailAddress=new tX(null),this.phoneNumber=new tX(null),this.web3Wallet=new tX(null),this.externalAccount=new tQ(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class tX extends tQ{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class t1 extends aF{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?aD(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tQ(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t2(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class t2 extends aF{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let t0="token:update",t9="user:signOut",t3="environment:update",t8="session:tokenResolved",t5=g();class t4 extends aF{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class t6 extends aF{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class t7 extends aF{static instance;authConfig=new aW;displayConfig=new tT;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rV;organizationSettings=new t6;commerceSettings=new tP;apiKeysSettings=new t4;protectConfig=new rf;static getInstance(){return t7.instance||(t7.instance=new t7),t7.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aW(e.auth_config),this.displayConfig=new tT(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new t6(e.organization_settings),this.userSettings=new rV(e.user_settings),this.commerceSettings=new tP(e.commerce_settings),this.apiKeysSettings=new t4(e.api_keys_settings),this.protectConfig=new rf(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t5.emit(t3,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}}class re extends aF{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:a,redirectUrl:t}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:a,redirect_url:t}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new tQ(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class ra extends aF{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class rt extends aF{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class rr extends aF{id;name=null;publicUrl=null;static async create(e,a={}){let t,r=a;return"string"==typeof a.file?(r=a.file,t=new Headers({"Content-Type":"application/octet-stream"})):a.file&&(r=new FormData).append("file",a.file),new rr((await aF._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new rr((await aF._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class ri extends aF{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new ri((await aF._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:a}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:aD(e.verification.expires_at)}:this.verification=null),this}}class rn extends aF{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.public_user_data&&(this.publicUserData=new ry(e.public_user_data))),this}}class rs extends aF{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class ro extends aF{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new rs(e)),this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rl extends aF{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rl((await aF._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rl((await aF._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aF._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ro(e))}});getDomains=async e=>await aF._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ri(e))}});getDomain=async({domainId:e})=>new ri((await aF._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aF._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});createDomain=async e=>ri.create(this.id,{name:e});getMemberships=async e=>await aF._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});getInvitations=async e=>await aF._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(e))}});addMember=async({userId:e,role:a})=>await aF._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rd(e?.response));inviteMember=async e=>rc.create(this.id,e);inviteMembers=async e=>rc.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aF._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rd(e?.response));removeMember=async e=>await aF._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rd(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aF._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rl(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aF._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rl(e?.response)))};initializePaymentMethod=e=>tg({...e,orgId:this.id});addPaymentMethod=e=>tb({...e,orgId:this.id});getPaymentMethods=e=>tf({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:a}=e||{},t=(await aF._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rc extends aF{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rc((await aF._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:a,role:t}}))?.response)}static async createBulk(e,a){let{emailAddresses:t,role:r}=a;return((await aF._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rc(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rd extends aF{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aF._fetch({path:"/me/organization_memberships",method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rl(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new ry(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${az} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class ru extends aF{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aF._fetch({path:"/me/organization_suggestions",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}function rh(){return c()&&"function"==typeof window.PublicKeyCredential}async function rm(){try{return rh()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rp(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rg extends aF{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aF._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rg(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tJ(a),response:{clientDataJSON:tG(t.clientDataJSON),attestationObject:tG(t.attestationObject),transports:t.getTransports()}});return aF._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rg(e?.response))}static async registerPasskey(){let e=rg.clerk.__internal_isWebAuthnSupported||rh,a=rg.clerk.__internal_createPublicCredentials||tW,t=rg.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rp;if(!e())throw new I("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aO("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new I("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await a(n);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new tO((await aF._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.verification&&(this.verification=new tY(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rb extends aF{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};setReservedForSecondFactor=e=>{let{reserved:a}=e||{};return this._basePatch({body:{reserved_for_second_factor:a}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new tQ(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rt(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rf extends aF{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class ry{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rk={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},rw=new Set(["first_factor","second_factor","multi_factor"]),rv=new Set(["strict_mfa","strict","moderate","lax"]),rj=(e,a)=>{let{org:t,user:r}=r_(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},r_=e=>{let a=e?e.split(",").map(e=>e.trim()):[];return{org:a.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:a.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rz extends aF{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tQ(null);secondFactorVerification=new tQ(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rx(e.session),this.level=e.level,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new tQ(e.first_factor_verification),this.secondFactorVerification=new tQ(e.second_factor_verification)),this}}class rx extends aF{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rx}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(tC.clear(),this._basePost({action:"end"}));remove=()=>(tC.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t5.emit(t0,{token:e.lastActiveToken}),e));clearCache=()=>tC.clear();getToken=async e=>an(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!O(e)&&a<=8});checkAuthorization=e=>{let a,t=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(a={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:t?.id,orgRole:t?.role,orgPermissions:t?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!a.userId)return!1;let t=((e,a)=>{let{features:t,plans:r}=a;return e.feature&&t?rj(t,e.feature):e.plan&&r?rj(r,e.plan):null})(e,a),r=((e,a)=>{let{orgId:t,orgRole:r,orgPermissions:i}=a;return(e.role||e.permission)&&t&&r&&i?e.permission?i.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,a),i=((e,{factorVerificationAge:a})=>{if(!e.reverification||!a)return null;let t=(e=>{let a,t;if(!e)return!1;let r="string"==typeof e&&rv.has(e),i="object"==typeof e&&(a=e.level,rw.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rk[e]:e).bind(null,e)})(e.reverification);if(!t)return null;let{level:r,afterMinutes:i}=t(),[n,s]=a,o=-1!==n?i>n:null,l=-1!==s?i>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,a);return[t||r,i].some(e=>null===e)?[t||r,i].some(e=>!0===e):[t||r,i].every(e=>!0===e)})(e)};#es=e=>{e&&tC.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tx.build(this.id,e,t)}startVerification=async({level:e})=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let a;switch(e.strategy){case"email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":a={};break;case"enterprise_sso":a={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:aA("Session.prepareFirstFactorVerification",e.strategy)}return new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let a;return a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tV(e.publicKeyCredential))}:{...e},new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,a=rx.clerk.__internal_isWebAuthnSupported||rh,t=rx.clerk.__internal_getPublicCredentials||t$;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tB(JSON.parse(e)):null;r||aO("get");let{publicKeyCredential:i,error:n}=await t({publicKeyOptions:r,conditionalUI:!1});if(!i)throw n;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:i})};prepareSecondFactorVerification=async e=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rz((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aD(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.user=new r$(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new ry(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rN(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:a,template:t,skipCache:r=!1}=e||{},i=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!t&&Number(a)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let n=this.#eo(t,i),s=r?void 0:tC.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){aa.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t5.emit(t0,{token:e}),e.getRawString()||null}aa.info("Fetching new token from API",{organizationId:i,template:t,tokenId:n},"session");let l=t?`${this.path()}/tokens/${t}`:`${this.path()}/tokens`,c=t?{}:{organizationId:i},d=rN.create(l,c,r);return tC.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t5.emit(t0,{token:e}),e.jwt&&(this.lastActiveToken=e,t5.emit(t8,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rq extends aF{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aF.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rq(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let a;return e?(this.id=e.id,this.status=e.status,this.expireAt=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.lastActiveAt=aD(e.last_active_at||void 0),this.latestActivity={id:(a=e.latest_activity??{}).id,deviceType:a.device_type,browserName:a.browser_name,browserVersion:a.browser_version,country:a.country,city:a.city,isMobile:a.is_mobile,ipAddress:a.ip_address},this.actor=e.actor,this):this}}let rS=(e,a,t)=>{let{onValidation:r=e3,onValidationComplexity:i=e3}=t||{},{show_zxcvbn:n,validatePassword:s}=a,o=e=>((e,a)=>{let{max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o}=a,l=(e=>{let a;if(e.allowed_special_characters){let t=e.allowed_special_characters.replace("[","\\[");t=t.replace("]","\\]"),a=RegExp(`[${t}]`)}else a=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:t,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=t,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:a.test(e)})})(a)(e,{maxLength:a.max_length,minLength:a.min_length}),c={max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o},d=new Map;for(let e in c)c[e]&&!l[e]&&d.set(e,!0);return Object.freeze(Object.fromEntries(d))})(e,a),l=(({min_zxcvbn_strength:e,onResult:a})=>t=>r=>{let i=t(r);return(a?.(i),i.score>=e&&i.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:i}:i.score>=e?{state:"excellent",result:i}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...i.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:i}})(a),c={};return(a,t)=>{let{onValidation:d=r,onValidationComplexity:u=i}=t||{};if(!s)return;let h=o(a);u(0===Object.keys(h).length),c={...c,complexity:h},n&&e().then(e=>{let t=l(e)(a);d({...c={...c,strength:t},strength:t})}),c.complexity&&0===Object.keys(c.complexity).length&&n||d(c)}};function rU(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rA(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rU(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",a);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${n}/popup-callback`),d=e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(l)}`),u=async a=>{if(a.origin!==n)return;let t=!1;if(a.data.session){if(!e.client?.sessions.find(e=>e.id===a.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:a.data.session,redirectUrl:r.redirectUrlComplete}),t=!0}else a.data.return_url&&(e.navigate(a.data.return_url),t=!0);t&&window.removeEventListener("message",u)};window.addEventListener("message",u),await t({...r,redirectUrlComplete:c,redirectUrl:d},i)}function rC(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rU(e.frontendApi),i=new URL(a);i.searchParams.set("sign_in_force_redirect_url",t),i.searchParams.set("sign_up_force_redirect_url",t);let n=e.buildUrlWithAuth(i.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(n)}`),redirectUrl:s}}function rI(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rU(e.frontendApi)&&(a.data.session||a.data.return_url?(window.removeEventListener("message",i),t()):r())};window.addEventListener("message",i),a.popup.location.href=a.externalVerificationRedirectURL.toString()})}async function rP(e,a){t5.emit("resource:error",{resource:e,error:null}),t5.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t5.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t5.emit("resource:fetch",{resource:e,status:"idle"})}}let rO=()=>{var e;return(e=new ao,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,a])=>{if(!e||!a)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:t,zxcvbn:r}=e,{dictionary:i,adjacencyGraphs:n}=a;return t.setOptions({dictionary:{...i},graphs:n}),r})}).loadZxcvbn};class rT extends aF{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tQ(null);secondFactorVerification=new tQ(null);identifier=null;createdSessionId=null;userData=new rK(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rE(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{aa.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ag();return this._basePost({path:this.pathRoot,body:a?{locale:a,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let a;switch(aa.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":a={};break;case"email_link":a={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":a={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":a={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":a={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:aA("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return aa.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tV(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aU("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status,s=n?"secondFactorVerification":"firstFactorVerification";return n?await this.prepareSecondFactor(i):await this.prepareFirstFactor(i),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEmailLinkFlow:a}};prepareSecondFactor=e=>(aa.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(aa.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,a)=>{let{strategy:t,redirectUrlComplete:r,identifier:i,oidcPrompt:n,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rT.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:t,identifier:i,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===t&&await this.prepareFirstFactor({strategy:t,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:n,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?a(d):aP(c,rT.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rA(rT.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e.toString()})};authenticateWithWeb3=async e=>{let a,{identifier:t,generateSignature:r,strategy:i="web3_metamask_signature"}=e||{},n=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aI("generateSignature"),await this.create({identifier:t});let s=this.supportedFirstFactors?.find(e=>e.strategy===i);s||aC("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||aC("SignIn");try{a=await r({identifier:t,nonce:o,provider:n})}catch(e){if("coinbase_wallet"===n&&4001===e.code)a=await r({identifier:t,nonce:o,provider:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rT.clerk.__internal_isWebAuthnSupported||rh,r=rT.clerk.__internal_getPublicCredentials||t$,i=rT.clerk.__internal_isWebAuthnAutofillSupported||rm;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===a||"discoverable"===a)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${az} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:n}=this.firstFactorVerification,s=n?tB(JSON.parse(n)):null;s||aO("get");let o=!1;"autofill"===a&&(o=await i());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,a)=>{if(rT.clerk.__unstable__environment?.userSettings.passwordSettings)return rS(rO(),{...rT.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new tQ(e.first_factor_verification),this.secondFactorVerification=new tQ(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rK(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t5.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:et(this.supportedFirstFactors),supported_second_factors:et(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rE{resource;emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eO("__clerk_status"),a=eO("__clerk_created_session");if(!e||!a)return null;let t="verified"===e&&void 0!==rT.clerk.client&&rT.clerk.client.sessions.some(e=>e.id===a);return{status:e,createdSessionId:a,verifiedFromTheSameClient:t}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rP(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new A("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.resource.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:a,signOutOfOtherSessions:t=!0}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ag();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rP(this.resource,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rP(this.resource,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.resource.identifier,r=ag();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.resource.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new A("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:a,verificationUrl:t,emailAddressId:r}=e;if(!this.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new A("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rP(this.resource,async()=>{let{run:e,stop:a}=tF();await new Promise((t,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(a(),t(e))}catch(e){a(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:a,phoneNumberId:t,channel:r="sms"}=e;if(!this.resource.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rP(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,popup:i,oidcPrompt:n,enterpriseConnectionId:s,identifier:o}=e;return rP(this.resource,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rT.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rC(rT.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=a.redirectCallbackUrl,l.actionCompleteRedirectUrl=a.redirectUrl}await this._create({strategy:a,...l,identifier:o}),"enterprise_sso"===a&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(i?(await rI(rT.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.resource.reload()):e$(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rP(this.resource,async()=>{let e,r,i;switch(t){case"metamask":e=await ak().getMetamaskIdentifier(),r=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),r=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),r=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),r=ak().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:e});let n=this.resource.supportedFirstFactors?.find(e=>e.strategy===a);if(!n)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:n.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await r({identifier:e,nonce:s})}catch(a){if("coinbase_wallet"===t&&4001===a.code)i=await r({identifier:e,nonce:s});else throw a}await this.resource.__internal_basePost({body:{signature:i,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rT.clerk.__internal_isWebAuthnSupported||rh,r=rT.clerk.__internal_getPublicCredentials||t$,i=rT.clerk.__internal_isWebAuthnAutofillSupported||rm;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rP(this.resource,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new A("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tB(JSON.parse(e)):null;if(!t)throw new A("Missing public key options",{code:"missing_public_key_options"});let n=!1;"autofill"===a&&(n=await i());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:t,conditionalUI:n});if(!s)throw new I(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tV(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rP(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.resource.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rP(this.resource,async()=>{rT.clerk.client&&!rT.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rT.clerk.client.reload(),this.#el=!0,await rT.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.resource.supportedFirstFactors)return null;if(a){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.resource.identifier);if(r)return r;let i=this.resource.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rM(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rR extends aF{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tZ(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rF(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{aa.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ag();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rR.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rM(a)})};prepareVerification=e=>(aa.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(aa.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:a}=tF();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aU("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:a,strategy:t="web3_metamask_signature"}=e;return this.attemptVerification({signature:a,strategy:t})};authenticateWithWeb3=async e=>{let a,{generateSignature:t,identifier:r,unsafeMetadata:i,strategy:n="web3_metamask_signature",legalAccepted:s}=e||{},o=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aI("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:c}=this.verifications.web3Wallet;c||aC("SignUp");try{a=await t({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)a=await t({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,a)=>{let{redirectUrl:t,redirectUrlComplete:r,strategy:i,continueSignUp:n=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,u=rR.clerk.buildUrlWithAuth(t),h=()=>{let e={strategy:i,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return n&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(E(e)&&P(e))return await rR.clerk.__unstable__environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aP(g,rR.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rA(rR.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rM(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rR.clerk.__unstable__environment?.userSettings.passwordSettings)return rS(rO(),{...rR.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new tZ(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),t5.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rR.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rR.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rR.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aF._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rD(e)))}class rF{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new aM(rR.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:t,captchaToken:r,captchaWidgetType:i}=a;return{captchaToken:r,captchaWidgetType:i,captchaError:t}}async _create(e){let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={transfer:e.transfer,captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0,locale:e.locale??ag()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})}async create(e){return rP(this.resource,async()=>{await this._create(e)})}async update(e){return rP(this.resource,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:a})})}async password(e){return rP(this.resource,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rM(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})})}async sendEmailCode(){return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rP(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rP(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:a},action:"attempt_verification"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rP(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:u}=await this.getCaptchaToken(),h=t;try{new URL(t)}catch{h=window.location.origin+t}let m={redirectUrl:rR.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rC(rR.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(E(e)&&P(e))return await rR.clerk.__unstable__environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.resource.verifications.externalAccount;"unverified"===g&&b&&(c?(await rI(rR.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.resource.reload()):e$(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rP(this.resource,async()=>{let e,n,s;switch(i){case"metamask":e=await ak().getMetamaskIdentifier(),n=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),n=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),n=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),n=ak().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||aC("SignUp");try{s=await n({identifier:e,nonce:l})}catch(a){if("coinbase_wallet"===i&&4001===a.code)s=await n({identifier:e,nonce:l});else throw a}await this.resource.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rP(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rR.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}}class rD extends aF{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rN extends aF{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rN(await aF._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ap(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ap(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rW extends aF{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class rL extends aF{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class r$ extends aF{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof r$}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tD:return this.primaryEmailAddressId===e.id;case rb:return this.primaryPhoneNumberId===e.id;case rH:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tD({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rg.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rb({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rH({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new re((await aF._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rW((await aF._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rW((await aF._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tO((await aF._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rL((await aF._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rM(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(t5.emit(t9,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rq.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?rr.delete(`${this.path()}/profile_image`):rr.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rB.retrieve(e);getOrganizationSuggestions=e=>ru.retrieve(e);getOrganizationMemberships=e=>rd.retrieve(e);leaveOrganization=async e=>new tO((await aF._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tg(e);addPaymentMethod=e=>tb(e);getPaymentMethods=e=>tf(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:a,name:t})=>t||[e,a].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new tD(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rb(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rH(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new re(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rg(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rd(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t1(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=aD(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aD(e.legal_accepted_at)),this.updatedAt=aD(e.updated_at||void 0),this.createdAt=aD(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rK{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rB extends aF{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aF._fetch({path:"/me/organization_invitations",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rB(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}let rJ={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class rV extends aF{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...rJ,name:"phone_number"},username:{...rJ,name:"username"},web3_wallet:{...rJ,name:"web3_wallet"},first_name:{...rJ,name:"first_name"},last_name:{...rJ,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...rJ,name:"authenticator_app"},backup_code:{...rJ,name:"backup_code"},passkey:{...rJ,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rG extends aF{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}static async join(e){return new rG((await aF._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rH extends aF{id;web3Wallet="";verification;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:a}=e;return this._basePost({action:"attempt_verification",body:{signature:a}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new tQ(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rQ(e,a){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||(t=a,r=e,t.organizationMemberships.length!==r.organizationMemberships.length||t.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function rY(e,a){return!function(e,a){if(!e&&a||e&&!a)return!0;if(!e&&e===a)return!1;if(!e||!a)return!0;try{if(tI.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rx.isSessionResource(e)){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==a.lastActiveToken?.jwt?.claims?.__raw||function(e,a){if(e.lastActiveOrganizationId!==a.lastActiveOrganizationId)return!0;let t=e.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId),r=a.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId);return t?.permissions?.length!==r?.permissions?.length}(e,a)||(t=e,r=a,!!t.user!=!!r.user||!!t.user&&!!r.user&&rQ(t.user,r.user))}if(r$.isUserResource(e))return rQ(e,a)}catch{}return!0}(e,a)?e:a}let rZ="__clerk_db_jwt";function rX(e,a){let t=new URL(e),r=t.searchParams.get(rZ);t.searchParams.delete(rZ);let i=r||a;return i&&t.searchParams.set(rZ,i),t}let r1=e=>{let a=new URL(e);return a.searchParams.delete(rZ),a},r2=e=>{let a=new URL(e);return a.searchParams.delete("__dev_session"),a.hash=decodeURI(a.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),a.href.endsWith("#")&&(a.hash=""),a};function r0(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)e[r]=t[r]}return e}var r9=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r0({},t,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var s in i)i[s]&&(n+="; "+s,!0!==i[s]&&(n+="="+i[s].split(";")[0]));return document.cookie=e+"="+a.write(r,e)+n}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],r={},i=0;i<t.length;i++){var n=t[i].split("="),s=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=a.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,a){r(e,"",r0({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r0({},this.attributes,a))},withConverter:function(a){return e(r0({},this.converter,a),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(a)}})}({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:"/"});function r3(e){return{get:()=>r9.get(e),set(a,t={}){r9.set(e,a,t)},remove(a){r9.remove(e,a)}}}let r8=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r5(e,a){let t=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return t.setFullYear(t.getFullYear()+a),t}let r4=r3("__clerk_test_etld"),r6="__client_uat",r7="__session",ie=()=>{let e=af()?"None":"Lax",a=r8(e);return{sameSite:e,secure:a,partitioned:!1}};async function ia(e){let a;try{a=await ep(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,H.has(t)||(console.log(t),H.add(t));let{default:r}=await Promise.resolve().then(i.t.bind(i,180,23)),{default:n}=await Promise.resolve().then(i.t.bind(i,413,23)),s=r(e);a=n.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return a}let it=()=>{let e=af()?"None":"Lax",a=r8(e);return{sameSite:e,secure:a}};var ir=i(945),ii=i.n(ir);class is{lock=(k="clerk.lock.refreshSessionToken",s=new(ii()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(k)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,t=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(k,{signal:a.signal},async()=>(clearTimeout(t),await e())).catch(()=>!1)}if(await s.acquireLock(k,5e3))try{return await e()}finally{await s.releaseLock(k)}}});workerTimers=tR();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let a=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(a,5e3)};a()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class io{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await ia(e.publishableKey),n=new io(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){let s,o,l,c,d,u,h;this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t5.on(t0,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t5.on(t9,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=r3(r6),o=r3(eg(r6,r)),{set:e=>{let a=r5(Date.now(),1),r=af()?"None":"Strict",i=r8(r),n=function(e=window.location.hostname,a=r4){if(t)return t;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),o.remove(),s.remove(),o.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i}),s.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=r3(r7),c=r3(eg(r7,r)),{set:e=>{let a=r5(Date.now(),1),{sameSite:t,secure:r,partitioned:i}=ie();i&&d(),l.set(e,{expires:a,sameSite:t,secure:r,partitioned:i}),c.set(e,{expires:a,sameSite:t,secure:r,partitioned:i})},remove:d=()=>{let e=ie();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(u=r3("clerk_active_context"),h={secure:r8("None")},{set:e=>{u.set(e,h)},get:()=>u.get(),remove:()=>u.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r3(rZ),i=r3(eg(rZ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r5(Date.now(),1),{sameSite:t,secure:n}=it();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=it();i.remove(e),r.remove(e)}});function s(){return n.get()}function o(e){n.set(e)}function l(){n.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ew(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=rX(e.url,a))}),t.onAfterResponse((e,a)=>{let t=a?.headers?.get("Clerk-Db-Jwt");t&&o(t)});let i=(r=(e=new URL(window.location.href)).searchParams.get(rZ)||"",r1(r2(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r1(r2(e))),r);if(i)return void o(i);if(n.get())return;let l=t.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await c.json()).errors);e[0]?aq(e[0].longMessage):aq()}let d=await c.json();o(d?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:a,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let a=this.devBrowser.getDevBrowserJWT();if(!a)throw Error(`${az} Missing dev browser jwt. Please contact support.`);return rX(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new is,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||u()||aa.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(E(e)||M(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(O(e))return void this.clerk.handleUnauthenticated().catch(e3);this.clerkEventBus.emit(b,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class il{clerk;captchaChallenge;timers;constructor(e,a=new aM(e),t=tR()){this.clerk=e,this.captchaChallenge=a,this.timers=t}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ic=["/client","/waitlist"];class id{async getBaseFapiProxyOptions(){let e=await aF.clerk.session?.getToken();if(!e)throw new A("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return aF._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a7({...e,subject:e?.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aN(e))}})}async create(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iu=new Map;class ih{#ec=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#ec){if(o())for(let e of(this.#ec=!0,a.loaders))try{this.applyLoader(e)}catch(e){Q(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let a=e.rollout;if("number"!=typeof a||a<0)return void Q(`[protect] loader rollout value is invalid: ${a}`);if(0===a||Math.random()>a)return}let a=e.type||"script",t=e.target||"body",r=document.createElement(a);if(e.attributes)for(let[a,t]of Object.entries(e.attributes))switch(typeof t){case"string":case"number":case"boolean":r.setAttribute(a,String(t));break;default:Q(`[protect] loader attribute is invalid type: ${a}=${t}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),t){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(t?.startsWith("#")){let e=document.getElementById(t.substring(1));if(!e)return void Q(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}Q(`[protect] loader target is invalid: ${t}`)}}}class im{signInResourceSignal=ta;signInErrorSignal=tt;signInFetchSignal=tr;signInSignal=ti;signUpResourceSignal=tn;signUpErrorSignal=ts;signUpFetchSignal=to;signUpSignal=tl;__internal_effect=a0;__internal_computed=a2;constructor(){t5.on("resource:update",this.onResourceUpdated),t5.on("resource:error",this.onResourceError),t5.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rT&&this.signInErrorSignal({error:e.error}),e.resource instanceof rR&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rT){if(ip(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rR){if(ip(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rT&&this.signInFetchSignal({status:e.status}),e.resource instanceof rR&&this.signUpFetchSignal({status:e.status})}}function ip(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ig="cannot_render_billing_disabled",ib="cannot_render_user_missing",iy="cannot_render_organizations_disabled",ik="cannot_render_organization_missing",iw="cannot_render_single_session_enabled",iv={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class ij{static version="6.0.0-snapshot.v20251203203405";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251203203405"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new im;internal_last_error=null;environment;#ed;#eu="";#eh;#em;#ep;#eg;#eb;#ef=null;#ey;#ek;#ew;#ev="loading";#ej=[];#e_=[];#ez={};#ex=null;#eq=0;#eS=g();get __internal_queryClient(){return this.#ed||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eS.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eu}get version(){return ij.version}set sdkMetadata(e){ij.sdkMetadata=e}get sdkMetadata(){return ij.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ev}get isSatellite(){return!!ab()&&e9(this.#ez.isSatellite,new URL(window.location.href),!1)}get domain(){if(ab()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e9(this.#eh,new URL(window.location.href)));if("production"===this.#ew){let a;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))a=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;a=/^(clerk\.)*/gi}return`clerk.${e.replace(a,"")}`}return e}return""}get proxyUrl(){if(ab()){let e=e9(this.#em,new URL(window.location.href));return!e||eK(e)||eB(e)||ah.throwInvalidProxyUrl({url:e}),e?eB(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eh(this.publishableKey);return e?e.frontendApi:ah.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ew}get isStandardBrowser(){return this.#ez.standardBrowser||!1}get billing(){return ij._billing||(ij._billing=new te),ij._billing}get apiKeys(){return ij._apiKeys||(ij._apiKeys=new id),ij._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,a){let t,r,i,n,{for:s,planId:o,planPeriod:l}=a;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:a,orgId:t,planId:r,planPeriod:i}=e;return`${a}-${t||"user"}-${r}-${i}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),d=iu.get(c);if(d)return d.signals.computedSignal();let u=(t=a1({resource:null}),r=a1({error:null}),i=a1({status:"idle"}),n=a2(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tc(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new th(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return iu.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#ez[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ah.throwMissingPublishableKeyError();let t=eh(e);if(!t)return ah.throwInvalidPublishableKeyError({key:e});this.#eh=a?.domain,this.#em=a?.proxyUrl,this.environment=t7.getInstance(),this.#ew=t.instanceType,this.#eu=e,this.#ek=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...a].filter(e=>e))if(await t(e)===!1)return!1;return!0}async function i(e,a){for await(let r of["undefined"!=typeof window&&window.__unstable__onAfterResponse,...t].filter(e=>e))if(await r(e,a)===!1)return!1;return!0}function n({method:a,path:t,sessionId:r,search:i,rotatingTokenNonce:n}){let s=new URLSearchParams(i);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-snapshot.v20251203203405"),n&&s.append("rotating_token_nonce",n),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),a&&"GET"!==a&&"POST"!==a&&s.append("_method",a),t&&!ic.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),ef([...s.entries()].reduce((e,[a,t])=>(e[a]=t.includes(",")?t.split(","):t,e),{}))}function s(a){let{path:t,pathPrefix:r="v1"}=a;if(e.proxyUrl){let i=new URL(e.proxyUrl),s=i.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),e_({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return e_({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ef(c,{keyEncoder:ee}):c);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(d()?4:11);n=await an(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(a,t)=>"GET"===h&&t<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else n=new Response("{}",o)}catch(a){let e=m.toString();aa.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${az} Network error at "${e}" - ${a}. Please try again.`)}let g=204!==n.status?await n.json():null,b=Object.assign(n,{payload:g});return n.ok||aa.error("request failed",{method:l,path:o.path,status:n.status},"fapiClient"),await i(o,b),b}return{buildEmailAddress:function(a){return function({localPart:e,frontendApi:a}){return`${e}@${a?a.replace("clerk.",""):"clerk.com"}`}({localPart:a,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){t.push(e)},onBeforeRequest:function(e){a.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eS.emit(b,"loading"),this.#eS.prioritizedOn(b,e=>this.#ev=e),aF.clerk=this,this.#eg=new ih}getFapiClient=()=>this.#ek;load=async e=>{if(aa.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ew&&Q("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#ez=this.#eU(e),this.#ez.clerkUiCtor&&(this.#ey=Promise.resolve(this.#ez.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#ez,new ao))),"development"===this.#ew&&(this.#ez.routerPush||this.#ez.routerReplace)&&(!this.#ez.routerPush||!this.#ez.routerReplace)){let e=this.#ez.routerPush?"routerReplace":"routerPush";Q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t5.on(t8,()=>{this.#eA(this.session),this.#eC()}),this.#ez.sdkMetadata&&(ij.sdkMetadata=this.#ez.sdkMetadata),!1!==this.#ez.telemetry&&(this.telemetry=new eQ({clerkVersion:ij.version,samplingRate:1,perEventSampling:!this.#ez.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#ez.telemetry}),this.#ez.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme||e.baseTheme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e0(e);if(t){a=t;break}}else a=e0(t);return{themeName:a}}(this.#ez.appearance)}));try{this.#ez.standardBrowser?await this.#eI():await this.#eP();let e=this.#ez.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#ez.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,i=this.environment?.isProduction?.()??!1,n=r||t&&!i,s=t&&!r?"error":void 0;n&&function(e={}){if(e4)return;let{enabled:a=!1,...t}=e;a&&(e8=!0,e4=!0,ae(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),aa.info("load() complete",{},"clerk")}catch(e){throw this.#eS.emit(b,"error"),aa.error("load() failed",{error:e},"clerk"),e}}};#eO(){let e;return!!(!this.#ez.signUpUrl&&this.#ez.signInUrl&&(e=this.#ez.signInUrl,!eb.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e3,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();aa.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:n,sessionTarget:i?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=al(this.#ez.standardBrowser);t5.emit(t9,null),this.#eT(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eA(),this.#eC(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#ez.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),aa.info("signOut() complete",{redirectUrl:ez(n)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===i.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),aa.info("signOut() complete",{redirectUrl:ez(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e2("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(W(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotOpenSignInOrSignUp,{code:iw});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eO()};this.telemetry?.record(e2("SignIn",e,a))};closeSignIn=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("Checkout"),{code:ig});return}if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenCheckout,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("PlanDetails"),{code:ig});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e2("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenUserProfile,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e2("UserVerification",e))};__internal_closeReverification=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ew||Q(`Clerk: "${t}" requires an active user session. Ensure a user is signed in before executing ${t}.`),"organizations"===a){let a;return(a=this.environment,a?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ew&&this.__internal_openEnableOrganizationsPrompt({caller:t,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${a}".`)};__internal_openEnableOrganizationsPrompt=e=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(ax("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(W(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotOpenSignInOrSignUp,{code:iw});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e2("SignUp",e))};closeSignUp=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotOpenUserProfile,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e2("UserProfile",e,a))};closeUserProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iy})}});if(a){if(!this.organization){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ik});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e2("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iy})}});a&&(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e2("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(e2("Waitlist",e))};closeWaitlist=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignIn";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eO()};this.telemetry?.record(e1(t,a,r))};unmountSignIn=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserAvatar";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountUserAvatar=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignUp";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountSignUp=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenUserDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey);let t="UserProfile";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userProfile",node:e,props:a}));let r=(a?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e1(t,a,r))};unmountUserProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationProfile=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iy})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ew)throw new A(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ik});return}this.assertComponentsReady(this.#ey);let i="OrganizationProfile";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(e1(i,a))};unmountOrganizationProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountCreateOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="CreateOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountCreateOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationSwitcher";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationList";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserButton";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userButton",node:e,props:a}));let r={...a?.customMenuItems?.length||0?{customItems:!0}:void 0,...a?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e1(t,a,r))};unmountUserButton=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ey);let t="Waitlist";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountWaitlist=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(L(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAnyBillingComponent("PricingTable"),{code:ig});return}this.assertComponentsReady(this.#ey);let t="PricingTable";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountPricingTable=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(Q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),$(this,t=this.environment)&&K(this,t)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&K(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if($(this,this.environment)){if("development"===this.#ew)throw new A(eN.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ey);let r="APIKeys";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountAPIKeys=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new A(eN.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:iy})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="TaskChooseOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountTaskChooseOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};setActive=async e=>{let{organization:a,redirectUrl:t,navigate:r}=e,{session:i}=e;this.__internal_setActiveInProgress=!0,aa.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof i?i:i?.id??i??null,organizationTarget:"string"==typeof a?a:a?.id??a??null,redirectUrl:t??null},"clerk");try{var n;let s;if(!this.client)throw aa.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===i&&!this.session)throw aa.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof i&&(i=this.client.sessions.find(e=>e.id===i)||null);let o="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e3,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#ez,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||Q('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==a;if(c&&d){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ab()&&globalThis.document.hasFocus()||!this.#ez.standardBrowser)&&(await this.#eE(c),c=this.#eM(c?.id)),await c?.getToken()||(u()||aa.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t5.emit(t0,{token:null}));let h=al(this.#ez.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#ez.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eT(),m){let e=t?e_({base:m,hashSearchParams:{redirectUrl:t}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(t){if(this.client.isEligibleForTouch()){let e=new URL(t,window.location.href),a=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(a)}await this.navigate(t)}}}),h.isUnloading())return;this.#eA(c),this.#eC(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var a;let t;return a=e,e=e=>{var r;t||={...e},a(t={...{client:rY((r=t).client,e.client),session:rY(r.session,e.session),user:rY(r.user,e.user),organization:rY(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(a=>a!==e)}};on=(...e)=>{this.#eS.on(...e)};off=(...e)=>{this.#eS.off(...e)};__internal_addNavigationListener=e=>(this.#e_.push(e),()=>{this.#e_=this.#e_.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ab())return;setTimeout(()=>{this.#eR()},0);let t=new URL(e,window.location.href);this.#eF.includes(t.protocol)||(console.warn(`Clerk: "${t.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),t=new URL("/",window.location.href));let r=a?.replace&&this.#ez.routerReplace?this.#ez.routerReplace:this.#ez.routerPush;if(aa.info(`Clerk is navigating to: ${t}`),this.#ez.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void e$(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:e$};return await r(ez(t),i)};buildUrlWithAuth(e){if("production"===this.#ew)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ep?this.#ep.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#ez,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#ez.afterSignOutUrl?this.buildUrlWithAuth(this.#ez.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#ez.newSubscriptionRedirectUrl?this.#ez.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e_({base:this.#ez.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#ez.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#ez.afterMultiSessionSingleSignOutUrl):this.#ez.signInUrl?this.buildUrlWithAuth(e_({base:this.#ez.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let a=this.session?.currentTask;if(!a)return"";let t=this.#ez.taskUrls?.[a.key];return t||e_({base:this.buildSignInUrl(e),hashPath:eR(a)},{stringify:!0})}#eN=async()=>{if(!ab())return;let e=new URLSearchParams({[B]:"true"}),a=eO(V);a&&eK(a)||function(){throw Error(`${az} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=e_({base:eO(V),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ab())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ab())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ab())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ab())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ab())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ab())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ab())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ab())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ab())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ab())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ab())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eO("__clerk_status");if("expired"===t)throw new q(U.Expired);if("client_mismatch"===t)throw new q(U.ClientMismatch);if("verified"!==t)throw new q(U.Failed);let r=eO("__clerk_created_session"),{signIn:i,signUp:n,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===i.status||"missing_requirements"===n.status,c=e=>a&&"function"==typeof a?a(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e3;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,a,t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:i}=this.client,n="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:i,o=e=>t&&"function"==typeof t?t(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(a,{signUp:s,signIn:n,navigate:o})};_handleRedirectCallback=async(e,{signIn:a,signUp:t,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await a.reload():"signUp"===e.reloadResource&&await t.reload()}catch{}let{displayConfig:i}=this.environment,{firstFactorVerification:n}=a,{externalAccount:s}=t.verifications,o={status:t.status,missingFields:t.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},l={status:a.status,firstFactorVerificationStatus:n.status,firstFactorVerificationErrorCode:n.error?.code,firstFactorVerificationSessionId:n.error?.meta?.sessionId,sessionId:a.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||i.signInUrl),u=c(e.signUpUrl||i.signUpUrl),h=c(e.firstFactorUrl||e_({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||e_({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||e_({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eC(this.#ez,e),b=c(e.continueSignUpUrl||e_({base:i.signUpUrl,hashPath:"/continue"},{stringify:!0})),f=({missingFields:a})=>a.length?b():(({signUp:e,verifyEmailPath:a,verifyPhonePath:t,continuePath:r,navigate:i,handleComplete:n,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return n&&n();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let n=eE();if(e.unverifiedFields?.includes("email_address")&&a)return i(a,{searchParams:n});if(e.unverifiedFields?.includes("phone_number")&&t)return i(t,{searchParams:n});if(r)return i(r,{searchParams:n})}})({signUp:t,verifyEmailPath:e.verifyEmailAddressUrl||e_({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||e_({base:i.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||i.signInUrl,k=e.signUpUrl||i.signUpUrl,w=async({session:e,baseUrl:a,redirectUrl:t})=>{e.currentTask?await eF(e,{baseUrl:a,navigate:this.navigate}):await this.navigate(t)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:g.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await a.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:aS("sign in")}}let v="user_locked"===o.externalAccountErrorCode,j="user_locked"===l.firstFactorVerificationErrorCode;if(v)return u();if(j)return d();if("needs_first_factor"===l.status&&!a.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let a=await t.create({transfer:!0});switch(a.status){case"complete":return this.setActive({session:a.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return f({missingFields:a.missingFields});default:aS("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let _=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,z="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(_||z){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:_?k:y,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:a}=e.verifications;return!!a.error})(t)?u():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?f({missingFields:t.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:t,signUp:r}=this.client,i=e=>a&&"function"==typeof a?a(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:t,navigate:i})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let a=await tI.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t5.emit(t9,null),this.setActive({session:null})}catch(e){if(E(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(ax("Google One Tap"),this.client.signIn);authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=i.replace("web3_","").replace("_signature",""),u=await ak().getWeb3Identifier({provider:d});switch(d){case"metamask":o=ak().generateSignatureWithMetamask;break;case"base":o=ak().generateSignatureWithBase;break;case"coinbase_wallet":o=ak().generateSignatureWithCoinbaseWallet;break;default:o=ak().generateSignatureWithOKXWallet}let h=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),m=h(s||e_({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(a||e_({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:o,strategy:i})}catch(e){if(au(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:o,unsafeMetadata:r,strategy:i,legalAccepted:n}),a&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let g=async({session:e,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:a})=>{await g({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rl.create({name:e,slug:a});getOrganization=async e=>rl.get(e);joinWaitlist=async({emailAddress:e})=>rG.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let a=this.#ez.selectInitialSession?this.#ez.selectInitialSession(e):this.#eW(e);this.#eA(a)}if(this.client=e,this.session){let e=this.#eM(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e3)(),this.#eA(e),this.session?.lastActiveToken||u()||aa.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t5.emit(t0,{token:this.session?.lastActiveToken})}this.#eC()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new t7(e)};__unstable__onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__unstable__updateProps=e=>{let a={...e,options:this.#eU({...this.#ez,...e.options})};return this.#ey?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eL=()=>{let e=new URLSearchParams({[V]:window.location.href});return e_({base:this.#ez.signInUrl,searchParams:e},{stringify:!0})};#e$=()=>{let e;if(this.proxyUrl){let a=new URL(this.proxyUrl);e=new URL(`${a.pathname}/v1/client/sync`,a.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eK=()=>"true"!==eO(B)&&!!this.isSatellite&&!!this.#ep?.isSignedOut();#eB=()=>"production"!==this.#ew&&!this.isSatellite&&!!eO(V);#eJ=async()=>{"development"===this.instanceType?await this.navigate(this.#eL()):"production"===this.instanceType&&await this.navigate(this.#e$())};#eV=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${az} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${az} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eG=()=>{this.isSatellite&&("development"!==this.#ew||this.#ez.signInUrl||function(){throw Error(`${az} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${az} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#ez.signInUrl&&this.#eV(this.#ez.signInUrl,window.location.origin))};#eI=async()=>{if(this.#ep=await io.create(this,this.#ek,this.#ew,this.#eS),this.#eG(),this.#eK())return void await this.#eJ();if(this.#eB())return void await this.#eN();this.#ex=(()=>{if(!o())return{onPageFocus:e3};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ef=new BroadcastChannel("clerk")),this.#eH();let e=function(e=window.location.hostname){if(!e)return!1;let a=ev.get(e);void 0===a&&(a=es.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||eo.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ev.set(e,a));return a}(window?.location.hostname),a="development"===this.#ew&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=t7.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=a_.getItem(aw,null);e&&this.updateEnvironment(new t7(e))}),r=async()=>tI.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(O(e))throw e;++t;let a=this.#ep?.getSessionCookie(),r=function(e){let a;try{a=new rN({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tI.clearInstance(),!a?.jwt)return tI.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:t,userId:r,orgId:i,orgRole:n,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let a,t,r,i,n=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){a=e.o?.id,r=e.o?.slg,e.o?.rol&&(t=`org:${e.o?.rol}`);let{org:n}=r_(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:a})=>{if(!e||!a)return{permissions:[],featurePermissionMap:[]};let t=e.split(",").map(e=>e.trim());return{permissions:t,featurePermissionMap:a.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(t.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});i=function({features:e,permissions:a,featurePermissionMap:t}){if(!e||!a||!t)return[];let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(i>=t.length)continue;let s=t[i];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${n}:${a[e]}`)}return r}({features:n,featurePermissionMap:o,permissions:s})}}else a=e.org_id,t=e.org_role,r=e.org_slug,i=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:a,orgRole:t,orgSlug:r,orgPermissions:i,factorVerificationAge:n}})(a.jwt.claims),c={object:"client",last_active_session_id:t,id:"client_init",sessions:[{object:"session",id:t,status:"active",last_active_organization_id:i||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:i&&o&&n?[{object:"organization_membership",id:i,role:n,permissions:s||[],organization:{object:"organization",id:i,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return tI.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ep?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ep?.startPollingForToken()}),null}),[,n]=await (i=[e,r()],Promise.all(Array.from(i).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(au(e,"requires_captcha"))await r();else throw e}if(this.#ep?.setClientUatCookieForDevelopmentInstances(),await this.#eQ())return;break}catch(e){if(au(e,"dev_browser_unauthenticated"))await this.#ep.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${az} Something went wrong initializing Clerk.`)}()}this.#eb=new il(this),this.#eb.start(),this.#eY(),this.#eZ(),this.#eX(),this.#eS.emit(b,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eP=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([t7.getInstance().fetch({touch:!1,fetchMaxTries:t}),tI.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(M(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new t7(t?.environment),tI.clearInstance(),a=tI.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eS.emit(b,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([t7.getInstance().fetch({touch:!1,fetchMaxTries:1}),tI.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eC()};#eW=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#eH=()=>{o()&&(this.#ex?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eq>Date.now())&&(this.#eq=Date.now()+5e3,this.#ez.touchSession&&this.#eE(this.session))}),this.#ef?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t5.on(t9,()=>{this.#ef?.postMessage({type:"signout"})}),t5.on(t3,()=>{a_.setItem(aw,this.environment?.__internal_toSnapshot(),864e5)}))};#eE=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{O(e)&&this.handleUnauthenticated()})};#eC=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eR=()=>{for(let e of this.#e_)e()};#eT=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eC()};#e1=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eA=e=>{this.session=e||null,this.organization=this.#e1(),this.user=this.session?this.session.user:null};#eM=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#eZ=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ey?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eX=()=>{this.#ez.__internal_keyless_claimKeylessApplicationUrl&&this.#ey?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#ez.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#ez.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#ez.__internal_keyless_dismissPrompt}})})};#eD=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#ez[e]||this.environment.displayConfig[e];this.#eO()&&(r=this.#ez.signInUrl);let i=new eC(this.#ez,a).toSearchParams(),n=new URLSearchParams(t||{}),s=e_({base:r,hashPath:this.#eO()&&"signUpUrl"===e?"/create":"",hashSearchParams:[n,i]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eQ=async()=>{var e;let a,t,r,i,n=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==n&&(e=this.frontendApi,t=(a=new URL(n,ey)).pathname,r=eU.includes(t)||eA.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#ez.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#ez.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ey),(!eU.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eU=e=>({...iv,...e,allowedRedirectOrigins:function(e,a,t){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ej(a)}`),r.push(`https://*.${ej(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eY=()=>{try{eT(B),eT(eI),eT(J),eT("__clerk_handshake"),eT("__clerk_handshake_nonce"),eT("__clerk_help")}catch{}};get #eF(){let e=eL;return this.#ez.allowedRedirectProtocols&&(e=e.concat(this.#ez.allowedRedirectProtocols)),e}}})();var s=n.c2,o=n.LR,l=n.cR,c=n.NZ,d=n.Ys,u=n.kl,h=n.$R,m=n.Cm,p=n.hl,g=n.ux,b=n.si,f=n._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,d as EmailLinkErrorCode,u as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,g as isKnownError,b as isMetamaskError,f as isUserLockedError};
|