@clerk/clerk-js 6.0.0-canary.v20260108210350 → 6.0.0-canary.v20260109111147

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.
Files changed (64) hide show
  1. package/dist/clerk.browser.js +4 -4
  2. package/dist/clerk.chips.browser.js +4 -4
  3. package/dist/clerk.headless.browser.js +4 -4
  4. package/dist/clerk.headless.js +2 -2
  5. package/dist/clerk.js +1 -1
  6. package/dist/clerk.legacy.browser.js +1 -1
  7. package/dist/clerk.mjs +1 -1
  8. package/dist/clerk.no-rhc.js +1 -1
  9. package/dist/clerk.no-rhc.mjs +1 -1
  10. package/package.json +4 -4
  11. /package/dist/{197_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → 197_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  12. /package/dist/{197_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → 197_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  13. /package/dist/{197_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → 197_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  14. /package/dist/{197_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 197_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  15. /package/dist/{197_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → 197_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  16. /package/dist/{308_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 308_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  17. /package/dist/{507_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → 507_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  18. /package/dist/{507_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → 507_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  19. /package/dist/{507_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → 507_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  20. /package/dist/{507_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 507_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  21. /package/dist/{507_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → 507_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  22. /package/dist/{521_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 521_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  23. /package/dist/{527_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → 527_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  24. /package/dist/{527_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → 527_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  25. /package/dist/{527_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → 527_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  26. /package/dist/{527_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → 527_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  27. /package/dist/{537_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 537_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  28. /package/dist/{604_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 604_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  29. /package/dist/{783_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 783_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  30. /package/dist/{896_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 896_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  31. /package/dist/{973_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → 973_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  32. /package/dist/{base-account-sdk_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → base-account-sdk_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  33. /package/dist/{base-account-sdk_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → base-account-sdk_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  34. /package/dist/{base-account-sdk_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → base-account-sdk_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  35. /package/dist/{base-account-sdk_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → base-account-sdk_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  36. /package/dist/{coinbase-wallet-sdk_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → coinbase-wallet-sdk_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  37. /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → coinbase-wallet-sdk_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  38. /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → coinbase-wallet-sdk_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  39. /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → coinbase-wallet-sdk_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  40. /package/dist/{cookieSuffix_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → cookieSuffix_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  41. /package/dist/{cookieSuffix_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → cookieSuffix_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  42. /package/dist/{cookieSuffix_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → cookieSuffix_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  43. /package/dist/{cookieSuffix_clerk.headless_47ca54_6.0.0-canary.v20260108210350.js → cookieSuffix_clerk.headless_a13eca_6.0.0-canary.v20260109111147.js} +0 -0
  44. /package/dist/{cookieSuffix_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → cookieSuffix_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  45. /package/dist/{query-core-vendors_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → query-core-vendors_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  46. /package/dist/{query-core-vendors_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → query-core-vendors_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  47. /package/dist/{query-core-vendors_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → query-core-vendors_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  48. /package/dist/{query-core-vendors_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → query-core-vendors_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  49. /package/dist/{stripe-vendors_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → stripe-vendors_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  50. /package/dist/{stripe-vendors_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → stripe-vendors_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  51. /package/dist/{stripe-vendors_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → stripe-vendors_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  52. /package/dist/{stripe-vendors_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → stripe-vendors_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  53. /package/dist/{vendors_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → vendors_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  54. /package/dist/{vendors_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → vendors_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  55. /package/dist/{vendors_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → vendors_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  56. /package/dist/{vendors_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → vendors_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  57. /package/dist/{zxcvbn-common_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → zxcvbn-common_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  58. /package/dist/{zxcvbn-common_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → zxcvbn-common_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  59. /package/dist/{zxcvbn-common_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → zxcvbn-common_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  60. /package/dist/{zxcvbn-common_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → zxcvbn-common_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
  61. /package/dist/{zxcvbn-ts-core_clerk.browser_f3f758_6.0.0-canary.v20260108210350.js → zxcvbn-ts-core_clerk.browser_aa1c21_6.0.0-canary.v20260109111147.js} +0 -0
  62. /package/dist/{zxcvbn-ts-core_clerk.chips.browser_b39d59_6.0.0-canary.v20260108210350.js → zxcvbn-ts-core_clerk.chips.browser_8f5deb_6.0.0-canary.v20260109111147.js} +0 -0
  63. /package/dist/{zxcvbn-ts-core_clerk.headless.browser_1dae90_6.0.0-canary.v20260108210350.js → zxcvbn-ts-core_clerk.headless.browser_02c265_6.0.0-canary.v20260109111147.js} +0 -0
  64. /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_5ac83f_6.0.0-canary.v20260108210350.js → zxcvbn-ts-core_clerk.legacy.browser_c38973_6.0.0-canary.v20260109111147.js} +0 -0
@@ -16,4 +16,4 @@ ${a.message}`)}})(ez(e)):e).some(e=>e.test(ez(r.origin))));return n||G(`Clerk: R
16
16
  ${e.trim()}
17
17
  (This notice only appears in development)`,eF={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=>eR(`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=>eR(`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(eF)){let a=eF[e];"function"!=typeof a&&(eF[e]=eR(a))}let eD="clerk:beforeunload",eN=["http:","https:","wails:","chrome-extension:"];function eW(e){let a=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eD)),window.location.href=a.href}function eL(e){return/^http(s)?:\/\//.test(e||"")}function e$(e){return e.startsWith("/")}var eK=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]))}},eB=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}},eJ=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 eV=new Set(["error","warn","info","debug","trace"]);var eG=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??"";const a=ed(e.publishableKey);a&&(this.#L.instanceType=a.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#W=new eK(eB.isSupported()?new eB:new eJ)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#N.disabled||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#N.debug||"undefined"!=typeof process&&process.env&&et(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&&eV.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.#X(e,a)}#H(e){return!0}#X(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.#Z();if(this.#$.length>=this.#N.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#Z();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#Z(),this.#K=null}):this.#K=setTimeout(()=>{this.#Z(),this.#K=null},0))}#Z(){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 eH="COMPONENT_MOUNTED",eQ=new Set(["SignIn","SignUp"]);function eY(e){return function(a,t,r){return{event:e,eventSamplingRate:e===eH?eQ.has(a)?1:.1:.1,payload:{component:a,appearanceProp:!!t?.appearance,theme:!!t?.appearance?.theme,elements:!!t?.appearance?.elements,variables:!!t?.appearance?.variables,...r}}}}function eX(e,a,t){return eY(eH)(e,a,t)}function eZ(e,a,t){return eY("COMPONENT_OPENED")(e,a,t)}function e1(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e2(e,a,t){return"function"==typeof e?e(a):void 0!==e?e:void 0!==t?t:void 0}let e0=(...e)=>{},e9=!1,e3=null,e8=!1,e5=[];function e4(e,a,t,r){e9&&(e5.push({level:e,message:a,context:t,source:r,ts:Date.now()}),e5.length>200&&e5.shift())}async function e6(e){try{if(!e9||e3)return;let{getDebugLogger:a}=await Promise.resolve().then(i.bind(i,854)),t=await a({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(t&&(e3=t)&&0!==e5.length){for(let e of e5){let a={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e3.error(e.message,a,e.source);break;case"warn":e3.warn(e.message,a,e.source);break;case"info":e3.info(e.message,a,e.source);break;case"debug":e3.debug(e.message,a,e.source)}}e5.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e7={debug(e,a,t){e3?e3.debug(e,a,t):e4("debug",e,a,t)},error(e,a,t){e3?e3.error(e,a,t):e4("error",e,a,t)},info(e,a,t){e3?e3.info(e,a,t):e4("info",e,a,t)},warn(e,a,t){e3?e3.warn(e,a,t):e4("warn",e,a,t)}},ae={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,a)=>a<5,retryImmediately:!1,jitter:!0},aa=async e=>new Promise(a=>setTimeout(a,e)),at=(e,a)=>a?e*(1+Math.random()):e,ar=async(e,a={})=>{var t;let r,i=0,{shouldRetry:n,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:u}={...ae,...a},h=(t={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await aa((e=at(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 aa(at(100,d)):await h()}},ai=async e=>ar(e,{initialDelay:100,shouldRetry:(e,a)=>a<=3,retryImmediately:!0,factor:2});class an{#ee={"@zxcvbn-ts/core":()=>ai(()=>Promise.resolve().then(i.bind(i,10))),"@zxcvbn-ts/language-common":()=>ai(()=>Promise.resolve().then(i.bind(i,655))),"@base-org/account":()=>ai(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@base-org/account'");throw e.code="MODULE_NOT_FOUND",e})),"@coinbase/wallet-sdk":()=>ai(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@coinbase/wallet-sdk'");throw e.code="MODULE_NOT_FOUND",e})),"@stripe/stripe-js":()=>ai(()=>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 as=(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(eD,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eD,t)},isUnloading:()=>a});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ao=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),al=e=>{let a={grandTotal:ao(e.grand_total),subtotal:ao(e.subtotal),taxTotal:ao(e.tax_total)};return"past_due"in e&&(a.pastDue=e.past_due?ao(e.past_due):null),"credit"in e&&(a.credit=e.credit?ao(e.credit):null),"total_due_now"in e&&(a.totalDueNow=ao(e.total_due_now)),"total_due_after_free_trial"in e&&(a.totalDueAfterFreeTrial=e.total_due_after_free_trial?ao(e.total_due_after_free_trial):null),a};function ac(e,a=""){return e.errors&&!!e.errors.find(e=>e.code===a)}let ad=x({packageName:"@clerk/clerk-js"});function au(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function ah(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(au(r)),s={__raw:e};return Object.keys(n).forEach(e=>{s[e]=n[e]}),{encoded:{header:t,payload:r,signature:i},header:JSON.parse(au(t)),claims:s}}function am(){if(!s())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function ap(){return void 0!==globalThis.document}function ag(){if(!function(){if(!ap())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var ab=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)}},af=class e{#en=void 0;#es=!1;static #er=null;constructor(){}async #eo(){if(this.#es)return;this.#es=!0;let e=await Promise.resolve().then(i.bind(i,76)).then(e=>e.getWallets());this.#en=e.get(),e.on("register",()=>{this.#en=e.get()}),e.on("unregister",()=>{this.#en=e.get()})}#el(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#ec(e){return"solana:signMessage"in e.features}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=async e=>{await this.#eo();let a=(this.#en||[]).find(a=>a.name===e&&this.#el(a)&&this.#ec(a));if(a&&this.#el(a))return a;if("undefined"==typeof window)return;let t=window.solana;if(t&&"function"==typeof t.connect&&"function"==typeof t.signMessage)return t}};let ay=()=>(function(e){let a=x({packageName:"@clerk/shared"});async function t(e){let{provider:a,walletName:t}=e,r=await p(a,t);if(!r)return"";if("solana"===a){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let i=await r.request({method:"eth_requestAccounts"});return i&&i[0]||""}let r=async e=>{let{identifier:a,nonce:t,provider:r,walletName:i=""}=e,n=await p(r,i);if(!n)return"";if("solana"===r)try{let e=n.accounts.find(e=>e.address===a);if(!e)return console.warn(`Wallet account with address ${a} not found`),"";let r=await n.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(t)});return r?.[0]?.signature?btoa(String.fromCharCode(...r[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new A("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new A("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await n.request({method:"personal_sign",params:[`0x${t.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,a]})};async function i(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function s(){return await t({provider:"okx_wallet"})}async function o(){return await t({provider:"base"})}async function l(e){return await t({provider:"solana",walletName:e})}async function c(e){return await r({...e,provider:"metamask"})}async function d(e){return await r({...e,provider:"coinbase_wallet"})}async function u(e){return await r({...e,provider:"okx_wallet"})}async function h(e){return await r({...e,provider:"base"})}async function m(e){return await r({...e,provider:"solana"})}async function p(t,r){if("coinbase_wallet"===t){let a=await e.import("@coinbase/wallet-sdk");return a?a.createCoinbaseWalletSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application",preference:{options:"all"}}).getProvider():null}if("base"===t)try{let a=await e.import("@base-org/account");if(!a)return null;return a.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===t?r&&0!==r.length?await af.getInstance().get(r):void a.throw("Wallet name must be provided to get Solana wallet provider"):ab.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:r,getMetamaskIdentifier:i,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:s,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:u,generateSignatureWithBase:h,generateSignatureWithSolana:m}})(new an),ak="environment",aw=JSON.stringify,av=JSON.parse;class aj{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),aw(r))}catch{}}static getItem(e,a){try{let t=window.localStorage.getItem(this._key(e));if(!t)return a;let r=av(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 a_(e){console.warn(`${az} ${e} is not supported in this environment.`)}function ax(e=""){throw Error(`${az} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function aq(e){throw Error(`${az} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function aS(e){throw Error(`${az} You need to start a ${e} flow by calling ${e}.create() first.`)}function aU(e,a){throw Error(`${az} Strategy "${a}" is not a valid strategy for ${e}.`)}function aA(e){throw Error(`${az} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function aC(e=""){throw Error(`${az} Missing '${e}' option`)}function aI(e,a){throw Error(`${az} Response: ${e||0} not supported yet.
18
18
  For more information contact us at ${a}`)}function aP(e){throw Error(`${az} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}let aO=e=>Promise.reject(Error("Captcha not supported in this environment")),aT=e=>{let a=e.__internal_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 aE{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaPublicKeyInvisible:r,nonce:i}=aT(this.clerk);return t&&a&&r?{...await aO({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}=aT(this.clerk);if(t&&a&&n){let t=await aO({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 aM{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return aM.instance||(aM.instance=new aM(tE,aE)),aM.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(!j(r)||C(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 aR{static clerk;id;pathRoot="";static get fapiClient(){return aR.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 aM.getInstance().execute(this.clerk,()=>this._baseFetch(e,a))}static async _baseFetch(e,a={}){let t;aR.fapiClient||function(){throw Error(`${az} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=a;try{t=await aR.fapiClient.request(e,{fetchMaxTries:r})}catch(a){if(this.shouldRethrowOfflineNetworkErrors())throw new A(a?.message||a,{code:"network_error"});if(!d())return e7.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 aR.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=aR.clerk.publishableKey).startsWith("live_")||t.startsWith("pk_live_"))){let t=aR.clerk.frontendApi.replace("clerk.","");throw new v(`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 v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aR.clerk&&aR.clerk.updateClient(tE.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 aR._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 aR._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 aR._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=aR.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aF(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aD extends aR{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?aF(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aF(e.last_used_at):null,this.updatedAt=aF(e.updated_at),this.createdAt=aF(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 aN extends aR{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?aF(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}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aW=[],{link:aL,unlink:a$,propagate:aK,checkDirty:aB,endTracking:aJ,startTracking:aV,shallowPropagate:aG}=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?a0(e):a9(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):aW[aY++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=a$(a,e);while(void 0!==a)}}else"previousValue"in e||a4.call(e)}}),aH=0,aQ=0,aY=0;function aX(a){let t=e;return e=a,t}function aZ(e){return a5.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a1(e){return a8.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a2(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aL(r,e):void 0!==a&&aL(r,a);let i=aX(r);try{r.fn()}finally{aX(i)}return a4.bind(r)}function a0(e){let a=aX(e);aV(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aX(a),aJ(e)}}function a9(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a3(){for(;aQ<aY;){let e=aW[aQ];aW[aQ++]=void 0,function e(a,t){if(16&t||32&t&&aB(a.deps,a)){let e=aX(a);aV(a);try{a.fn()}finally{aX(e),aJ(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)}aQ=0,aY=0}function a8(){let t=this.flags;if(16&t||32&t&&aB(this.deps,this)){if(a0(this)){let e=this.subs;void 0!==e&&aG(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aL(this,e):void 0!==a&&aL(this,a),this.value}function a5(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aK(e),aH||a3())}}else{let a=this.value;if(16&this.flags&&a9(this,a)){let e=this.subs;void 0!==e&&aG(e)}return void 0!==e&&aL(this,e),a}}function a4(){let e=this.deps;for(;void 0!==e;)e=a$(e,this);let a=this.subs;void 0!==a&&a$(a),this.flags=0}function a6(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 a7{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${a7.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aR._fetch({path:`${a7.#ed}/plans`,method:"GET",search:a6(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tz(e))}})};getPlan=async e=>new tz(await aR._fetch({path:`${a7.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aR._fetch({path:a7.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tq(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aR._fetch({path:a7.path("/statements",{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new t_(e))}})};getStatement=async e=>new t_((await aR._fetch({path:a7.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aR._fetch({path:a7.path("/payment_attempts",{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tb(e))}})};getPaymentAttempt=async e=>new tb(await aR._fetch({path:a7.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tp((await aR._fetch({path:a7.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let te=aZ({resource:null}),ta=aZ({error:null}),tt=aZ({status:"idle"}),tr=a1(()=>{let e=te().resource,a=ta().error,t=tt().status;return{errors:th(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),ti=aZ({resource:null}),tn=aZ({error:null}),ts=aZ({status:"idle"}),to=a1(()=>{let e=ti().resource,a=tn().error,t=ts().status;return{errors:th(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}}),tl=aZ({resource:null}),tc=aZ({error:null}),td=aZ({status:"idle"}),tu=a1(()=>{let e=tl().resource,a=tc().error,t=td().status;return{errors:th(a,{emailAddress:null}),fetchStatus:t,waitlist:e}});function th(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!j(e))return t.raw=[e],t.global=[F(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=Y(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[F(e)]),t}class tm extends aR{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=aF(e.created_at)),e.updated_at&&(this.updatedAt=aF(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 tp extends aR{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 tv(e.payment_method):void 0,this.plan=new tz(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=al(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aF(e.free_trial_ends_at)),this.payer=new tm(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ar(()=>this._basePatch({path:a7.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!j(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 tg{resource=new tp(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 tp.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tp(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 tp.clerk.setActive({session:tp.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tp.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()=>{++aH,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aH||a3(),++aH;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"}),--aH||a3()}})();return n.set(e,s),s})(e,a,t)}}class tb extends aR{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=ao(e.amount),this.paidAt=e.paid_at?aF(e.paid_at):null,this.failedAt=e.failed_at?aF(e.failed_at):null,this.updatedAt=aF(e.updated_at),this.paymentMethod=e.payment_method?new tv(e.payment_method):null,this.subscriptionItem=new tS(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tf="/payment_methods",ty=async e=>{let{orgId:a,...t}=e;return new tj((await aR._fetch({path:a7.path(`${tf}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tk=async e=>{let{orgId:a,...t}=e;return new tv((await aR._fetch({path:a7.path(tf,{orgId:a}),method:"POST",body:t}))?.response)},tw=async e=>{let{orgId:a,...t}=e??{};return await aR._fetch({path:a7.path(tf,{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};class tv extends aR{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:aF(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aF(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tR((await aR._fetch({path:a7.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aR._fetch({path:a7.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tj extends aR{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 tz extends aR{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=ao(e.fee),this.annualFee=e.annual_fee?ao(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ao(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 rn(e))),this}}class t_ extends aR{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=aF(e.timestamp),this.totals=al(e.totals),this.groups=e.groups.map(e=>new tx(e))),this}}class tx{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aF(e.timestamp),this.items=e.items.map(e=>new tb(e))),this}}class tq extends aR{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=aF(e.created_at),this.updatedAt=e.updated_at?aF(e.updated_at):null,this.activeAt=aF(e.active_at),this.pastDueAt=e.past_due_at?aF(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ao(e.next_payment.amount),date:aF(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tS(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tS extends aR{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 tz(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aF(e.created_at),this.pastDueAt=e.past_due_at?aF(e.past_due_at):null,this.periodStart=aF(e.period_start),this.periodEnd=e.period_end?aF(e.period_end):null,this.canceledAt=e.canceled_at?aF(e.canceled_at):null,this.amount=e.amount?ao(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ao(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tR((await aR._fetch({path:a7.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tU={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tU.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}},tA="clerk",tC=10,tI={broadcast:!0},tP={broadcast:!1};class tO{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tO(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 tT=((e=tA)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null,i=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));i();let n=(t,r=tC)=>{i();let n=new tO(e,t),s=a.get(n.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),a.delete(n.toKey());return}return s.entry},s=async({data:e})=>{let a,r=tU.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void e7.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:t,template:e.template,traceId:e.traceId},"tokenCache");try{a=new rK({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){e7.warn("Failed to parse token from broadcast, skipping cache update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let i=a.jwt?.claims?.iat,s=a.jwt?.claims?.exp;if(!i||!s)return void e7.warn("Token missing iat/exp claim, skipping cache update",{tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=n({tokenId:e.tokenId});if(a){let r=await a.tokenResolver,n=r.jwt?.claims?.iat;if(n&&n>=i)return void e7.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){e7.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e7.info("Updating token cache from broadcast",{iat:i,organizationId:e.organizationId,tabId:t,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:i,tokenId:e.tokenId,tokenResolver:Promise.resolve(a)},tP)},o=(i,n=tI)=>{let s=new tO(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=tU.extractTemplate(i.tokenId,e,n),o=tU.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e7.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)};return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:n,set:e=>{i(),o(e,tI)},size:()=>a.size}})();class tE extends aR{static instance;pathRoot="/client";sessions=[];signUp=new rW;signIn=new rF;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tE.instance||(tE.instance=new tE(e)),tE.instance}static clearInstance(){tE.instance=null}static isClientResource(e){return!!e&&e instanceof tE}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(()=>{tT.clear(),this.id="",this.sessions=[],this.signUp=new rW(null),this.signIn=new rF(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=>(tT.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aR.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 rA(e)),this.signUp=new rW(e.sign_up),this.signIn=new rF(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aF(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aF(e.created_at||void 0),this.updatedAt=aF(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 tM extends aR{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 tR{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 tF extends aR{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="";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 tD='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 tN=(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}},tW=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tN(tD,{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:e0};let s=()=>{n||(n=tN(tD,{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 tL({delayInMs:e}={delayInMs:1e3}){let a,t=tW(),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 t$ extends aR{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}=tL();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}=tL();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 t1(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rs(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 tK=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 tB(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"}):tG(a),publicKeyCredential:null}}}let tJ=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 tV({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tJ.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"}):tG(t),publicKeyCredential:null}}}function tG(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 tH(e){let a=tZ(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tZ(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tQ(e){return{type:e.type,id:e.id,rawId:tX(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tY(e){let a=e.response;return{...tQ(e),response:{clientDataJSON:tX(a.clientDataJSON),authenticatorData:tX(a.authenticatorData),signature:tX(a.signature),userHandle:a.userHandle?tX(a.userHandle):null}}}let tX=tK.encode.bind(tK),tZ=tK.decode.bind(tK);class t1 extends aR{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===aR.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=aF(e.expire_at||void 0),this.error=e.error?new k(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 t2 extends t1{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=tZ((a=JSON.parse(e.nonce)).user.id),r=tZ(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tZ(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class t0{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t9(e.email_address),this.phoneNumber=new t9(e.phone_number),this.web3Wallet=new t9(e.web3_wallet),this.externalAccount=new t1(e.external_account)):(this.emailAddress=new t9(null),this.phoneNumber=new t9(null),this.web3Wallet=new t9(null),this.externalAccount=new t1(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 t9 extends t1{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 t3 extends aR{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?aF(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new t1(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t8(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 t8 extends aR{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=aF(e.created_at),this.updatedAt=aF(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 t5="token:update",t4="user:signOut",t6="environment:update",t7="session:tokenResolved",re=p();class ra extends aR{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 rt extends aR{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 rr extends aR{static instance;authConfig=new aN;displayConfig=new tF;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rY;organizationSettings=new rt;commerceSettings=new tM;apiKeysSettings=new ra;protectConfig=new rv;static getInstance(){return rr.instance||(rr.instance=new rr),rr.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aN(e.auth_config),this.displayConfig=new tF(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 rt(e.organization_settings),this.userSettings=new rY(e.user_settings),this.commerceSettings=new tM(e.commerce_settings),this.apiKeysSettings=new ra(e.api_keys_settings),this.protectConfig=new rv(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(re.emit(t6,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()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class ri extends aR{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 t1(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 rn extends aR{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 rs extends aR{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 ro extends aR{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 ro((await aR._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ro((await aR._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 rl extends aR{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rl((await aR._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:aF(e.verification.expires_at)}:this.verification=null),this}}class rc extends aR{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=aF(e.created_at),this.updatedAt=aF(e.updated_at),e.public_user_data&&(this.publicUserData=new rj(e.public_user_data))),this}}class rd extends aR{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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class ru extends aR{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 rd(e)),this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class rh extends aR{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 rh((await aR._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rh((await aR._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aR._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t,has_role_set_migration:r}=e?.response;return{data:a.map(e=>new ru(e)),total_count:t,has_role_set_migration:r}});getDomains=async e=>await aR._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getDomain=async({domainId:e})=>new rl((await aR._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aR._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(e))}});createDomain=async e=>rl.create(this.id,{name:e});getMemberships=async e=>await aR._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a6({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rp(e))}});getInvitations=async e=>await aR._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rm(e))}});addMember=async({userId:e,role:a})=>await aR._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rp(e?.response));inviteMember=async e=>rm.create(this.id,e);inviteMembers=async e=>rm.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aR._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rp(e?.response));removeMember=async e=>await aR._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rp(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aR._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rh(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aR._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rh(e?.response)))};initializePaymentMethod=e=>ty({...e,orgId:this.id});addPaymentMethod=e=>tk({...e,orgId:this.id});getPaymentMethods=e=>tw({...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=aF(e.created_at),this.updatedAt=aF(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 aR._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rm extends aR{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rm((await aR._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 aR._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rm(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class rp extends aR{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aR._fetch({path:"/me/organization_memberships",method:"GET",search:a6({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rp(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 rh(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aF(e.created_at),this.updatedAt=aF(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 rg extends aR{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aR._fetch({path:"/me/organization_suggestions",method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rg(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}function rb(){return l()&&"function"==typeof window.PublicKeyCredential}async function rf(){try{return rb()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ry(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rk extends aR{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aR._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rk(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tQ(a),response:{clientDataJSON:tX(t.clientDataJSON),attestationObject:tX(t.attestationObject),transports:t.getTransports()}});return aR._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rk(e?.response))}static async registerPasskey(){let e=rk.clerk.__internal_isWebAuthnSupported||rb,a=rk.clerk.__internal_createPublicCredentials||tB,t=rk.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||ry;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||aP("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 tR((await aR._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?aF(e.last_used_at):null,this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at),e.verification&&(this.verification=new t2(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 rw extends aR{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 t1(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rs(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 rv extends aR{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 rj{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 rz={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"}},r_=new Set(["first_factor","second_factor","multi_factor"]),rx=new Set(["strict_mfa","strict","moderate","lax"]),rq=(e,a)=>{let{org:t,user:r}=rS(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rS=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 rU extends aR{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new t1(null);secondFactorVerification=new t1(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rA(e.session),this.level=e.level,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new t1(e.first_factor_verification),this.secondFactorVerification=new t1(e.second_factor_verification)),this}}class rA extends aR{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 rA}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tT.clear(),this._basePost({action:"end"}));remove=()=>(tT.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&re.emit(t5,{token:e.lastActiveToken}),e));clearCache=()=>tT.clear();getToken=async e=>ar(()=>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?rq(t,e.feature):e.plan&&r?rq(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&&rx.has(e),i="object"==typeof e&&(a=e.level,r_.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rz[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)};#eu=e=>{e&&tT.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tU.build(this.id,e,t)}startVerification=async({level:e})=>new rU((await aR._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:aU("Session.prepareFirstFactorVerification",e.strategy)}return new rU((await aR._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(tY(e.publicKeyCredential))}:{...e},new rU((await aR._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=rA.clerk.__internal_isWebAuthnSupported||rb,t=rA.clerk.__internal_getPublicCredentials||tV;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tH(JSON.parse(e)):null;r||aP("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 rU((await aR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rU((await aR._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=aF(e.expire_at),this.abandonAt=aF(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aF(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at),this.user=new rV(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rK(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.#eh(t,i),s=r?void 0:tT.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){e7.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&re.emit(t5,{token:e}),e.getRawString()||null}e7.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=this.lastActiveToken?.getRawString(),u=rK.create(l,c,r?{debug:"skip_cache"}:void 0).catch(e=>{if(z.is(e)&&d)return rK.create(l,{...c},{expired_token:d});throw e});return tT.set({tokenId:n,tokenResolver:u}),u.then(e=>(o&&(re.emit(t5,{token:e}),e.jwt&&(this.lastActiveToken=e,re.emit(t7,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rC extends aR{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aR.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rC(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=aF(e.expire_at),this.abandonAt=aF(e.abandon_at),this.lastActiveAt=aF(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 rI=(e,a,t)=>{let{onValidation:r=e0,onValidationComplexity:i=e0}=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 rP(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rO(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rP(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 rT(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rP(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 rE(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rP(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 rM(e,a){re.emit("resource:error",{resource:e,error:null}),re.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return re.emit("resource:error",{resource:e,error:a}),{error:a}}finally{re.emit("resource:fetch",{resource:e,status:"idle"})}}let rR=()=>{var e;return(e=new an,{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 rF extends aR{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new t1(null);secondFactorVerification=new t1(null);identifier=null;createdSessionId=null;userData=new rG(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&e7.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rD(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e7.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=am();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(e7.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":case"web3_solana_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:aU("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return e7.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tY(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tL();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aS("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status||"needs_client_trust"===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=>(e7.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e7.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=rF.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):aI(c,rF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aC("popup"),rO(rF.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",walletName:n}=e||{},s=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aC("generateSignature"),"solana"!==s||n||aC("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aA("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aA("SignIn");try{a=await r({identifier:t,nonce:l,walletName:n,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)a=await r({identifier:t,nonce:l,provider:s,walletName:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await ay().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ay().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ay().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ay().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await ay().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>ay().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rF.clerk.__internal_isWebAuthnSupported||rb,r=rF.clerk.__internal_getPublicCredentials||tV,i=rF.clerk.__internal_isWebAuthnAutofillSupported||rf;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?tH(JSON.parse(n)):null;s||aP("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(rF.clerk.__internal_environment?.userSettings.passwordSettings)return rI(rR(),{...rF.clerk.__internal_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=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new t1(e.first_factor_verification),this.secondFactorVerification=new t1(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rG(e.user_data),this.clientTrustState=e.client_trust_state??void 0),re.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:ee(this.supportedFirstFactors),supported_second_factors:ee(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 rD{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(!s())return null;const e=eI("__clerk_status"),a=eI("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rF.clerk.client&&rF.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)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rM(this.#ep,async()=>{let e=this.#ep.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.#ep.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=am();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rM(this.#ep,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 rM(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=am();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.#ep.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rM(this.#ep,async()=>{let{run:e,stop:a}=tL();await new Promise((t,r)=>{e(async()=>{try{let e=await this.#ep.__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.#ep.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rF.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rT(rF.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.#ep.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#ep.firstFactorVerification;"unverified"===c&&d&&(i?(await rE(rF.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):eW(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rM(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await ay().getMetamaskIdentifier(),i=ay().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await ay().getCoinbaseWalletIdentifier(),i=ay().generateSignatureWithCoinbaseWallet;break;case"base":r=await ay().getBaseIdentifier(),i=ay().generateSignatureWithBase;break;case"okx_wallet":r=await ay().getOKXWalletIdentifier(),i=ay().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await ay().getSolanaIdentifier(e.walletName),i=a=>ay().generateSignatureWithSolana({...a,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===a);if(!s)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await i({identifier:r,nonce:o,walletName:e?.walletName,provider:t})}catch(e){if("coinbase_wallet"===t&&4001===e.code)n=await i({identifier:r,nonce:o,provider:t});else throw e}await this.#ep.__internal_basePost({body:{signature:n,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rF.clerk.__internal_isWebAuthnSupported||rb,r=rF.clerk.__internal_getPublicCredentials||tV,i=rF.clerk.__internal_isWebAuthnAutofillSupported||rf;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rM(this.#ep,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.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tH(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.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tY(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rM(this.#ep,async()=>{let e=this.#ep.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.#ep.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rM(this.#ep,async()=>{rF.clerk.client&&!rF.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rF.clerk.client.reload(),this.#em=!0,await rF.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.#ep.supportedFirstFactors)return null;if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.#ep.identifier);if(r)return r;let i=this.#ep.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rN(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rW extends aR{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new t0(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&&e7.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rL(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e7.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=am();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rW.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rN(a)})};prepareVerification=e=>(e7.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e7.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}=tL();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aS("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,walletName:o}=e||{},l=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aC("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:d}=this.verifications.web3Wallet;d||aA("SignUp");try{a=await t({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)a=await t({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await ay().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ay().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ay().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ay().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await ay().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>ay().generateSignatureWithSolana({...a,walletName:e}),unsafeMetadata:a,strategy:"web3_solana_signature",legalAccepted:t,walletName:e})};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=rW.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(j(e)&&P(e))return await rW.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aI(g,rW.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aC("popup"),rO(rW.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rN(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rW.clerk.__internal_environment?.userSettings.passwordSettings)return rI(rR(),{...rW.clerk.__internal_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 t0(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),re.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 rW.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rW.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rW.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aR._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new r$(e)))}class rL{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new aE(rW.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?rN(e.unsafeMetadata):void 0,locale:e.locale??am()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rM(this.#ep,async()=>{await this._create(e)})}async update(e){return rM(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rN(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rM(this.#ep,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rN(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rM(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,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:rW.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rT(rW.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.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(j(e)&&P(e))return await rW.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rE(rW.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):eW(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rM(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await ay().getMetamaskIdentifier(),n=ay().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ay().getCoinbaseWalletIdentifier(),n=ay().generateSignatureWithCoinbaseWallet;break;case"base":e=await ay().getBaseIdentifier(),n=ay().generateSignatureWithBase;break;case"okx_wallet":e=await ay().getOKXWalletIdentifier(),n=ay().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||aA("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.#ep.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rM(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rW.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class r$ extends aR{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rK extends aR{pathRoot="tokens";jwt;static async create(e,a={},t={}){return new rK(await aR._fetch({method:"POST",path:e,body:a,search:t}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ah(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ah(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rB extends aR{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=aF(e.updated_at),this.createdAt=aF(e.created_at)),this}}class rJ extends aR{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=aF(e.updated_at),this.createdAt=aF(e.created_at)),this}}class rV extends aR{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 rV}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case t$:return this.primaryEmailAddressId===e.id;case rw:return this.primaryPhoneNumberId===e.id;case rX:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new t$({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rk.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rw({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rX({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new ri((await aR._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rB((await aR._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rB((await aR._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tR((await aR._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rJ((await aR._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rN(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=>(re.emit(t4,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rC.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ro.delete(`${this.path()}/profile_image`):ro.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rH.retrieve(e);getOrganizationSuggestions=e=>rg.retrieve(e);getOrganizationMemberships=e=>rp.retrieve(e);leaveOrganization=async e=>new tR((await aR._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ty(e);addPaymentMethod=e=>tk(e);getPaymentMethods=e=>tw(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 t$(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 rw(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 rX(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 ri(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rk(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rp(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t3(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=aF(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aF(e.legal_accepted_at)),this.updatedAt=aF(e.updated_at||void 0),this.createdAt=aF(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 rG{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 rH extends aR{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aR._fetch({path:"/me/organization_invitations",method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rH(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}let rQ={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 rY extends aR{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:{...rQ,name:"phone_number"},username:{...rQ,name:"username"},web3_wallet:{...rQ,name:"web3_wallet"},first_name:{...rQ,name:"first_name"},last_name:{...rQ,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:{...rQ,name:"authenticator_app"},backup_code:{...rQ,name:"backup_code"},passkey:{...rQ,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}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 rX extends aR{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 t1(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class rZ extends aR{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aF(e.updated_at),this.createdAt=aF(e.created_at),re.emit("resource:update",{resource:this})),this}async join(e){return rM(this,async()=>{await rZ.join(e)})}static async join(e){return new rZ(await aR._fetch({path:"/waitlist",method:"POST",body:e}))}}function r1(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 r2(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(tE.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rA.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&&r1(t.user,r.user))}if(rV.isUserResource(e))return r1(e,a)}catch{}return!0}(e,a)?e:a}let r0="__clerk_db_jwt";function r9(e,a){let t=new URL(e),r=t.searchParams.get(r0);t.searchParams.delete(r0);let i=r||a;return i&&t.searchParams.set(r0,i),t}let r3=e=>{let a=new URL(e);return a.searchParams.delete(r0),a},r8=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 r5(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 r4=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r5({},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,"",r5({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r5({},this.attributes,a))},withConverter:function(a){return e(r5({},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 r6(e){return{get:()=>r4.get(e),set(a,t={}){r4.set(e,a,t)},remove(a){r4.remove(e,a)}}}let r7=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ie(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 ia=r6("__clerk_test_etld"),it="__client_uat",ir="__session",ii=()=>{let e=ag()?"None":"Lax",a=r7(e);return{sameSite:e,secure:a,partitioned:!1}};async function is(e){let a;try{a=await eh(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(t)||(console.log(t),V.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 io=()=>{let e=ag()?"None":"Lax",a=r7(e);return{sameSite:e,secure:a}};var il=i(945),ic=i.n(il);class id{lock=(function(e){let a=new(ic());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tW();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 iu{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await is(e.publishableKey),n=new iu(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,re.on(t5,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),re.on(t4,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r6(it),r=r6(em(it,e));return{set:e=>{let i=ie(Date.now(),1),n=ag()?"None":"Strict",s=r7(n),o=function(e=window.location.hostname,a=ia){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()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r6(ir),t=r6(em(ir,e)),r=()=>{let e=ii();a.remove(e),t.remove(e)};return{set:e=>{let i=ie(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=ii();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r6("clerk_active_context"),a={secure:r7("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r6(r0),i=r6(em(r0,e)),{get:()=>i.get()||r.get(),set:e=>{let a=ie(Date.now(),1),{sameSite:t,secure:n}=io();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=io();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(!ey(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r9(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(r0)||"",r3(r8(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r3(r8(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 k(e)):[]}((await c.json()).errors);e[0]?ax(e[0].longMessage):ax()}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 r9(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new id,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||d()||e7.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(j(e)||C(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(O(e))return void this.clerk.handleUnauthenticated().catch(e0);this.clerkEventBus.emit(g,"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 ih{clerk;captchaChallenge;timers;constructor(e,a=new aE(e),t=tW()){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.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let im=["/client","/waitlist"];class ip{async getBaseFapiProxyOptions(){let e=await aR.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 aR._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a6({...e,subject:e?.subject??aR.clerk.organization?.id??aR.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aD(e))}})}async create(e){return new aD(await aR._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aR.clerk.organization?.id??aR.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aD(await aR._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ig=new Map;class ib{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(s())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){G(`[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 G(`[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:G(`[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 G(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}G(`[protect] loader target is invalid: ${t}`)}}}class iy{signInResourceSignal=te;signInErrorSignal=ta;signInFetchSignal=tt;signInSignal=tr;signUpResourceSignal=ti;signUpErrorSignal=tn;signUpFetchSignal=ts;signUpSignal=to;waitlistResourceSignal=tl;waitlistErrorSignal=tc;waitlistFetchSignal=td;waitlistSignal=tu;_waitlistInstance;__internal_effect=a2;__internal_computed=a1;constructor(){re.on("resource:update",this.onResourceUpdated),re.on("resource:error",this.onResourceError),re.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new rZ(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rF&&this.signInErrorSignal({error:e.error}),e.resource instanceof rW&&this.signUpErrorSignal({error:e.error}),e.resource instanceof rZ&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rF){if(ik(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rW){if(ik(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof rZ&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rF&&this.signInFetchSignal({status:e.status}),e.resource instanceof rW&&this.signUpFetchSignal({status:e.status}),e.resource instanceof rZ&&this.waitlistFetchSignal({status:e.status})}}function ik(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let iw="cannot_render_billing_disabled",iv="cannot_render_user_missing",ij="cannot_render_organizations_disabled",iz="cannot_render_organization_missing",i_="cannot_render_single_session_enabled",ix={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 iq{static version="6.0.0-canary.v20260108210350";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20260108210350"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iy;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eA={};#eC=null;#eI=0;#eP=p();get __internal_queryClient(){return this.#eg||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#eg||(this.#eg=new e,this.#eP.emit("queryClientStatus","ready"))}),this.#eg?{__tag:"clerk-rq-client",client:this.#eg}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eb}get version(){return iq.version}set sdkMetadata(e){iq.sdkMetadata=e}get sdkMetadata(){return iq.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ap()&&e2(this.#eA.isSatellite,new URL(window.location.href),!1)}get domain(){if(ap()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e2(this.#ef,new URL(window.location.href)));if("production"===this.#ex){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(ap()){let e=e2(this.#ey,new URL(window.location.href));return!e||eL(e)||e$(e)||ad.throwInvalidProxyUrl({url:e}),e?e$(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ed(this.publishableKey);return e?e.frontendApi:ad.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eA.standardBrowser||!1}get billing(){return iq._billing||(iq._billing=new a7),iq._billing}get apiKeys(){return iq._apiKeys||(iq._apiKeys=new ip),iq._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=ig.get(c);if(d)return d.signals.computedSignal();let u=(t=aZ({resource:null}),r=aZ({error:null}),i=aZ({status:"idle"}),n=a1(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:th(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new tg(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ig.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eA[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ad.throwMissingPublishableKeyError();const t=ed(e);if(!t)return ad.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=rr.getInstance(),this.#ex=t.instanceType,this.#eb=e,this.#e_=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__internal_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.__internal_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.v20260108210350"),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&&!im.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eg([...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)),ev({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ev({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:d}=o;!d||"object"!=typeof d||d 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}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d 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=d?eg(d,{keyEncoder:X}):d);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??(c()?4:11);n=await ar(()=>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();e7.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||e7.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.#eP.emit(g,"loading"),this.#eP.prioritizedOn(g,e=>this.#eq=e),aR.clerk=this,this.#ew=new ib}getFapiClient=()=>this.#e_;load=async e=>{if(e7.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||G("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.#eA=this.#eO(e),this.#eA.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eA.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eA,new an))),"development"===this.#ex&&(this.#eA.routerPush||this.#eA.routerReplace)&&(!this.#eA.routerPush||!this.#eA.routerReplace)){let e=this.#eA.routerPush?"routerReplace":"routerPush";G(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}re.on(t7,()=>{this.#eT(this.session),this.#eE()}),this.#eA.sdkMetadata&&(iq.sdkMetadata=this.#eA.sdkMetadata),!1!==this.#eA.telemetry&&(this.telemetry=new eG({clerkVersion:iq.version,samplingRate:1,perEventSampling:!this.#eA.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eA.telemetry}),this.#eA.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e1(e);if(t){a=t;break}}else a=e1(t);return{themeName:a}}(this.#eA.appearance)}));try{this.#eA.standardBrowser?await this.#eM():await this.#eR();let e=this.#eA.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eA.__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(e8)return;let{enabled:a=!1,...t}=e;a&&(e9=!0,e8=!0,e6(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),e7.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(g,"error"),e7.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eA.signUpUrl&&this.#eA.signInUrl&&(e=this.#eA.signInUrl,!ep.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();e7.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=as(this.#eA.standardBrowser);re.emit(t4,null),this.#eD(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eT(),this.#eE(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#eA.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e7.info("signOut() complete",{redirectUrl:ej(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(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(eZ("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(D(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotOpenSignInOrSignUp,{code:i_});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eF()};this.telemetry?.record(eZ("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("Checkout"),{code:iw});return}if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenCheckout,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("PlanDetails"),{code:iw});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(eZ("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenUserProfile,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(eZ("UserVerification",e))};__internal_closeReverification=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ex||G(`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.#ex&&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.#ez),this.#ez.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(a=>a.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eX("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ez),this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(a_("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(D(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotOpenSignInOrSignUp,{code:i_});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(eZ("SignUp",e))};closeSignUp=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenUserProfile,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eZ("UserProfile",e,a))};closeUserProfile=()=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ij})}});if(a){if(!this.organization){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(eZ("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ij})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(eZ("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(eZ("Waitlist",e))};closeWaitlist=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignIn";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eF()};this.telemetry?.record(eX(t,a,r))};unmountSignIn=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserAvatar";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountUserAvatar=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignUp";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountSignUp=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenUserDoesNotExist,{code:iv});return}this.assertComponentsReady(this.#ez);let t="UserProfile";this.#ez.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(eX(t,a,r))};unmountUserProfile=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ij})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez);let i="OrganizationProfile";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(eX(i,a))};unmountOrganizationProfile=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="CreateOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountCreateOrganization=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationSwitcher";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ez),this.#ez.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(eF.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationList";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserButton";this.#ez.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(eX(t,a,r))};unmountUserButton=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ez);let t="Waitlist";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("PricingTable"),{code:iw});return}this.assertComponentsReady(this.#ez);let t="PricingTable";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountPricingTable=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(G("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),W(this,t=this.environment)&&L(this,t)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&L(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(W(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ez);let r="APIKeys";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountAPIKeys=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="TaskChooseOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountTaskChooseOrganization=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskResetPassword=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:a})),this.telemetry?.record(eX("TaskResetPassword",a))};unmountTaskResetPassword=e=>{this.#ez?.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,e7.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 e7.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 e7.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.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eA,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||G('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 u=void 0!==a;if(c&&u){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),(ap()&&globalThis.document.hasFocus()||!this.#eA.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(d()||e7.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),re.emit(t5,{token:null}));let h=as(this.#eA.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eA.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eD(),m){let e=t?ev({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.#eT(c),this.#eE(),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:r2((r=t).client,e.client),session:r2(r.session,e.session),user:r2(r.user,e.user),organization:r2(r.organization,e.organization)}})},this.#eS.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eS=this.#eS.filter(a=>a!==e)}};on=(...e)=>{this.#eP.on(...e)};off=(...e)=>{this.#eP.off(...e)};__internal_addNavigationListener=e=>(this.#eU.push(e),()=>{this.#eU=this.#eU.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ap())return;setTimeout(()=>{this.#eL()},0);let t=new URL(e,window.location.href);this.#e$.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.#eA.routerReplace?this.#eA.routerReplace:this.#eA.routerPush;if(e7.info(`Clerk is navigating to: ${t}`),this.#eA.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eW(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eW};return await r(ej(t),i)};buildUrlWithAuth(e){if("production"===this.#ex)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ek?this.#ek.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("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 eU(this.#eA,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eU(this.#eA,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eA.afterSignOutUrl?this.buildUrlWithAuth(this.#eA.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eA.newSubscriptionRedirectUrl?this.#eA.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ev({base:this.#eA.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eA.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eA.afterMultiSessionSingleSignOutUrl):this.#eA.signInUrl?this.buildUrlWithAuth(ev({base:this.#eA.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.#eA.taskUrls?.[a.key];return t||ev({base:this.buildSignInUrl(e),hashPath:eE(a)},{stringify:!0})}#eB=async()=>{if(!ap())return;let e=new URLSearchParams({[$]:"true"}),a=eI(B);a&&eL(a)||function(){throw Error(`${az} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ev({base:eI(B),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ap())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ap())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ap())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ap())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ap())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ap())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ap())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ap())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ap())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ap())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ap())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eI("__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=eI("__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):e0;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||ev({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ev({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eU(this.#eA,e),b=c(e.continueSignUpUrl||ev({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=eO();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||ev({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ev({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 eM(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:aq("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:aq("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 z=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="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:z?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 tE.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&re.emit(t4,null),this.setActive({session:null})}catch(e){if(j(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(a_("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"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,u=i.replace("web3_","").replace("_signature",""),h=await ay().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=ay().generateSignatureWithMetamask;break;case"base":l=ay().generateSignatureWithBase;break;case"coinbase_wallet":l=ay().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>ay().generateSignatureWithSolana({...e,walletName:o});break;default:l=ay().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ev({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ev({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:i,walletName:o})}catch(e){if(ac(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:i,legalAccepted:n,walletName:o}),a&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await g();else throw e}let b=async({session:e,redirectUrl:a})=>{e.currentTask?await eM(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:a})=>{await b({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rh.create({name:e,slug:a});getOrganization=async e=>rh.get(e);joinWaitlist=async({emailAddress:e})=>rZ.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.#eA.selectInitialSession?this.#eA.selectInitialSession(e):this.#eJ(e);this.#eT(a)}if(this.client=e,this.session){let e=this.#eW(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0)(),this.#eT(e),this.session?.lastActiveToken||d()||e7.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),re.emit(t5,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rr(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let a={...e,options:this.#eO({...this.#eA,...e.options})};return this.#ez?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eV=()=>{let e=new URLSearchParams({[B]:window.location.href});return ev({base:this.#eA.signInUrl,searchParams:e},{stringify:!0})};#eG=()=>{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()||""};#eH=()=>"true"!==eI($)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eI(B);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eX=(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.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ex||this.#eA.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.#eA.signInUrl&&this.#eX(this.#eA.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await iu.create(this,this.#e_,this.#ex,this.#eP),this.#eZ(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eC=(()=>{if(!s())return{onPageFocus:e0};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ej=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let a=ek.get(e);void 0===a&&(a=ei.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||en.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ek.set(e,a));return a}(window?.location.hostname),a="development"===this.#ex&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=rr.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=aj.getItem(ak,null);e&&this.updateEnvironment(new rr(e))}),r=async()=>tE.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(O(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rK({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tE.clearInstance(),!a?.jwt)return tE.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}=rS(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 tE.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ek?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ek?.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(ac(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(ac(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${az} Something went wrong initializing Clerk.`)}()}this.#ev=new ih(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(g,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:t}),tE.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(C(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new rr(t?.environment),tE.clearInstance(),a=tE.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:1}),tE.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eE()};#eJ=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#e1=()=>{s()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eA.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),re.on(t4,()=>{this.#ej?.postMessage({type:"signout"})}),re.on(t6,()=>{aj.setItem(ak,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{O(e)&&this.handleUnauthenticated()})};#eE=()=>{if(this.client)for(let e of this.#eS)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eU)e()};#eD=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eE()};#e8=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e8(),this.user=this.session?this.session.user:null};#eW=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#e9=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ez?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e3=()=>{this.#eA.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eA.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eA.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eA.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eA[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eA.signInUrl);let i=new eU(this.#eA,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ev({base:r,hashPath:this.#eF()&&"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")}#e2=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,eb)).pathname,r=eq.includes(t)||eS.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eA.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eA.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,eb),(!eq.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...ix,...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://${ew(a)}`),r.push(`https://*.${ew(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eP($),eP(eA),eP(K),eP("__clerk_handshake"),eP("__clerk_handshake_nonce"),eP("__clerk_help")}catch{}};get #e$(){let e=eN;return this.#eA.allowedRedirectProtocols&&(e=e.concat(this.#eA.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
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 v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aR.clerk&&aR.clerk.updateClient(tE.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 aR._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 aR._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 aR._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=aR.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aF(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aD extends aR{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?aF(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aF(e.last_used_at):null,this.updatedAt=aF(e.updated_at),this.createdAt=aF(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 aN extends aR{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?aF(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}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aW=[],{link:aL,unlink:a$,propagate:aK,checkDirty:aB,endTracking:aJ,startTracking:aV,shallowPropagate:aG}=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?a0(e):a9(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):aW[aY++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=a$(a,e);while(void 0!==a)}}else"previousValue"in e||a4.call(e)}}),aH=0,aQ=0,aY=0;function aX(a){let t=e;return e=a,t}function aZ(e){return a5.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a1(e){return a8.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a2(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aL(r,e):void 0!==a&&aL(r,a);let i=aX(r);try{r.fn()}finally{aX(i)}return a4.bind(r)}function a0(e){let a=aX(e);aV(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aX(a),aJ(e)}}function a9(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a3(){for(;aQ<aY;){let e=aW[aQ];aW[aQ++]=void 0,function e(a,t){if(16&t||32&t&&aB(a.deps,a)){let e=aX(a);aV(a);try{a.fn()}finally{aX(e),aJ(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)}aQ=0,aY=0}function a8(){let t=this.flags;if(16&t||32&t&&aB(this.deps,this)){if(a0(this)){let e=this.subs;void 0!==e&&aG(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aL(this,e):void 0!==a&&aL(this,a),this.value}function a5(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aK(e),aH||a3())}}else{let a=this.value;if(16&this.flags&&a9(this,a)){let e=this.subs;void 0!==e&&aG(e)}return void 0!==e&&aL(this,e),a}}function a4(){let e=this.deps;for(;void 0!==e;)e=a$(e,this);let a=this.subs;void 0!==a&&a$(a),this.flags=0}function a6(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 a7{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${a7.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aR._fetch({path:`${a7.#ed}/plans`,method:"GET",search:a6(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tz(e))}})};getPlan=async e=>new tz(await aR._fetch({path:`${a7.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aR._fetch({path:a7.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tq(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aR._fetch({path:a7.path("/statements",{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new t_(e))}})};getStatement=async e=>new t_((await aR._fetch({path:a7.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aR._fetch({path:a7.path("/payment_attempts",{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tb(e))}})};getPaymentAttempt=async e=>new tb(await aR._fetch({path:a7.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tp((await aR._fetch({path:a7.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let te=aZ({resource:null}),ta=aZ({error:null}),tt=aZ({status:"idle"}),tr=a1(()=>{let e=te().resource,a=ta().error,t=tt().status;return{errors:th(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),ti=aZ({resource:null}),tn=aZ({error:null}),ts=aZ({status:"idle"}),to=a1(()=>{let e=ti().resource,a=tn().error,t=ts().status;return{errors:th(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}}),tl=aZ({resource:null}),tc=aZ({error:null}),td=aZ({status:"idle"}),tu=a1(()=>{let e=tl().resource,a=tc().error,t=td().status;return{errors:th(a,{emailAddress:null}),fetchStatus:t,waitlist:e}});function th(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!j(e))return t.raw=[e],t.global=[F(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=Y(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[F(e)]),t}class tm extends aR{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=aF(e.created_at)),e.updated_at&&(this.updatedAt=aF(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 tp extends aR{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 tv(e.payment_method):void 0,this.plan=new tz(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=al(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aF(e.free_trial_ends_at)),this.payer=new tm(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ar(()=>this._basePatch({path:a7.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!j(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 tg{resource=new tp(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 tp.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tp(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 tp.clerk.setActive({session:tp.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tp.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()=>{++aH,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aH||a3(),++aH;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"}),--aH||a3()}})();return n.set(e,s),s})(e,a,t)}}class tb extends aR{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=ao(e.amount),this.paidAt=e.paid_at?aF(e.paid_at):null,this.failedAt=e.failed_at?aF(e.failed_at):null,this.updatedAt=aF(e.updated_at),this.paymentMethod=e.payment_method?new tv(e.payment_method):null,this.subscriptionItem=new tS(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tf="/payment_methods",ty=async e=>{let{orgId:a,...t}=e;return new tj((await aR._fetch({path:a7.path(`${tf}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tk=async e=>{let{orgId:a,...t}=e;return new tv((await aR._fetch({path:a7.path(tf,{orgId:a}),method:"POST",body:t}))?.response)},tw=async e=>{let{orgId:a,...t}=e??{};return await aR._fetch({path:a7.path(tf,{orgId:a}),method:"GET",search:a6(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};class tv extends aR{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:aF(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aF(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tR((await aR._fetch({path:a7.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aR._fetch({path:a7.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tj extends aR{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 tz extends aR{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=ao(e.fee),this.annualFee=e.annual_fee?ao(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ao(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 rn(e))),this}}class t_ extends aR{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=aF(e.timestamp),this.totals=al(e.totals),this.groups=e.groups.map(e=>new tx(e))),this}}class tx{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aF(e.timestamp),this.items=e.items.map(e=>new tb(e))),this}}class tq extends aR{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=aF(e.created_at),this.updatedAt=e.updated_at?aF(e.updated_at):null,this.activeAt=aF(e.active_at),this.pastDueAt=e.past_due_at?aF(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ao(e.next_payment.amount),date:aF(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tS(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tS extends aR{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 tz(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aF(e.created_at),this.pastDueAt=e.past_due_at?aF(e.past_due_at):null,this.periodStart=aF(e.period_start),this.periodEnd=e.period_end?aF(e.period_end):null,this.canceledAt=e.canceled_at?aF(e.canceled_at):null,this.amount=e.amount?ao(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ao(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tR((await aR._fetch({path:a7.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tU={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tU.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}},tA="clerk",tC=10,tI={broadcast:!0},tP={broadcast:!1};class tO{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tO(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 tT=((e=tA)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null,i=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));i();let n=(t,r=tC)=>{i();let n=new tO(e,t),s=a.get(n.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),a.delete(n.toKey());return}return s.entry},s=async({data:e})=>{let a,r=tU.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void e7.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:t,template:e.template,traceId:e.traceId},"tokenCache");try{a=new rK({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){e7.warn("Failed to parse token from broadcast, skipping cache update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let i=a.jwt?.claims?.iat,s=a.jwt?.claims?.exp;if(!i||!s)return void e7.warn("Token missing iat/exp claim, skipping cache update",{tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=n({tokenId:e.tokenId});if(a){let r=await a.tokenResolver,n=r.jwt?.claims?.iat;if(n&&n>=i)return void e7.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){e7.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e7.info("Updating token cache from broadcast",{iat:i,organizationId:e.organizationId,tabId:t,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:i,tokenId:e.tokenId,tokenResolver:Promise.resolve(a)},tP)},o=(i,n=tI)=>{let s=new tO(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=tU.extractTemplate(i.tokenId,e,n),o=tU.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e7.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)};return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:n,set:e=>{i(),o(e,tI)},size:()=>a.size}})();class tE extends aR{static instance;pathRoot="/client";sessions=[];signUp=new rW;signIn=new rF;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tE.instance||(tE.instance=new tE(e)),tE.instance}static clearInstance(){tE.instance=null}static isClientResource(e){return!!e&&e instanceof tE}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(()=>{tT.clear(),this.id="",this.sessions=[],this.signUp=new rW(null),this.signIn=new rF(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=>(tT.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aR.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 rA(e)),this.signUp=new rW(e.sign_up),this.signIn=new rF(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aF(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aF(e.created_at||void 0),this.updatedAt=aF(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 tM extends aR{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 tR{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 tF extends aR{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="";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 tD='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 tN=(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}},tW=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tN(tD,{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:e0};let s=()=>{n||(n=tN(tD,{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 tL({delayInMs:e}={delayInMs:1e3}){let a,t=tW(),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 t$ extends aR{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}=tL();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}=tL();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 t1(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rs(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 tK=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 tB(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"}):tG(a),publicKeyCredential:null}}}let tJ=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 tV({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tJ.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"}):tG(t),publicKeyCredential:null}}}function tG(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 tH(e){let a=tZ(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tZ(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tQ(e){return{type:e.type,id:e.id,rawId:tX(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tY(e){let a=e.response;return{...tQ(e),response:{clientDataJSON:tX(a.clientDataJSON),authenticatorData:tX(a.authenticatorData),signature:tX(a.signature),userHandle:a.userHandle?tX(a.userHandle):null}}}let tX=tK.encode.bind(tK),tZ=tK.decode.bind(tK);class t1 extends aR{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===aR.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=aF(e.expire_at||void 0),this.error=e.error?new k(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 t2 extends t1{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=tZ((a=JSON.parse(e.nonce)).user.id),r=tZ(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tZ(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class t0{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t9(e.email_address),this.phoneNumber=new t9(e.phone_number),this.web3Wallet=new t9(e.web3_wallet),this.externalAccount=new t1(e.external_account)):(this.emailAddress=new t9(null),this.phoneNumber=new t9(null),this.web3Wallet=new t9(null),this.externalAccount=new t1(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 t9 extends t1{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 t3 extends aR{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?aF(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new t1(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t8(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 t8 extends aR{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=aF(e.created_at),this.updatedAt=aF(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 t5="token:update",t4="user:signOut",t6="environment:update",t7="session:tokenResolved",re=p();class ra extends aR{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 rt extends aR{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 rr extends aR{static instance;authConfig=new aN;displayConfig=new tF;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rY;organizationSettings=new rt;commerceSettings=new tM;apiKeysSettings=new ra;protectConfig=new rv;static getInstance(){return rr.instance||(rr.instance=new rr),rr.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aN(e.auth_config),this.displayConfig=new tF(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 rt(e.organization_settings),this.userSettings=new rY(e.user_settings),this.commerceSettings=new tM(e.commerce_settings),this.apiKeysSettings=new ra(e.api_keys_settings),this.protectConfig=new rv(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(re.emit(t6,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()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class ri extends aR{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 t1(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 rn extends aR{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 rs extends aR{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 ro extends aR{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 ro((await aR._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ro((await aR._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 rl extends aR{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rl((await aR._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:aF(e.verification.expires_at)}:this.verification=null),this}}class rc extends aR{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=aF(e.created_at),this.updatedAt=aF(e.updated_at),e.public_user_data&&(this.publicUserData=new rj(e.public_user_data))),this}}class rd extends aR{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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class ru extends aR{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 rd(e)),this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class rh extends aR{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 rh((await aR._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rh((await aR._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aR._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t,has_role_set_migration:r}=e?.response;return{data:a.map(e=>new ru(e)),total_count:t,has_role_set_migration:r}});getDomains=async e=>await aR._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getDomain=async({domainId:e})=>new rl((await aR._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aR._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(e))}});createDomain=async e=>rl.create(this.id,{name:e});getMemberships=async e=>await aR._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a6({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rp(e))}});getInvitations=async e=>await aR._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a6(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rm(e))}});addMember=async({userId:e,role:a})=>await aR._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rp(e?.response));inviteMember=async e=>rm.create(this.id,e);inviteMembers=async e=>rm.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aR._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rp(e?.response));removeMember=async e=>await aR._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rp(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aR._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rh(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aR._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rh(e?.response)))};initializePaymentMethod=e=>ty({...e,orgId:this.id});addPaymentMethod=e=>tk({...e,orgId:this.id});getPaymentMethods=e=>tw({...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=aF(e.created_at),this.updatedAt=aF(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 aR._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rm extends aR{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rm((await aR._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 aR._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rm(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}class rp extends aR{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aR._fetch({path:"/me/organization_memberships",method:"GET",search:a6({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rp(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 rh(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aF(e.created_at),this.updatedAt=aF(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 rg extends aR{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aR._fetch({path:"/me/organization_suggestions",method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rg(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}function rb(){return l()&&"function"==typeof window.PublicKeyCredential}async function rf(){try{return rb()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ry(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rk extends aR{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aR._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rk(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tQ(a),response:{clientDataJSON:tX(t.clientDataJSON),attestationObject:tX(t.attestationObject),transports:t.getTransports()}});return aR._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rk(e?.response))}static async registerPasskey(){let e=rk.clerk.__internal_isWebAuthnSupported||rb,a=rk.clerk.__internal_createPublicCredentials||tB,t=rk.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||ry;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||aP("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 tR((await aR._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?aF(e.last_used_at):null,this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at),e.verification&&(this.verification=new t2(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 rw extends aR{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 t1(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rs(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 rv extends aR{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 rj{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 rz={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"}},r_=new Set(["first_factor","second_factor","multi_factor"]),rx=new Set(["strict_mfa","strict","moderate","lax"]),rq=(e,a)=>{let{org:t,user:r}=rS(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rS=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 rU extends aR{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new t1(null);secondFactorVerification=new t1(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rA(e.session),this.level=e.level,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new t1(e.first_factor_verification),this.secondFactorVerification=new t1(e.second_factor_verification)),this}}class rA extends aR{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 rA}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tT.clear(),this._basePost({action:"end"}));remove=()=>(tT.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&re.emit(t5,{token:e.lastActiveToken}),e));clearCache=()=>tT.clear();getToken=async e=>ar(()=>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?rq(t,e.feature):e.plan&&r?rq(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&&rx.has(e),i="object"==typeof e&&(a=e.level,r_.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rz[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)};#eu=e=>{e&&tT.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tU.build(this.id,e,t)}startVerification=async({level:e})=>new rU((await aR._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:aU("Session.prepareFirstFactorVerification",e.strategy)}return new rU((await aR._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(tY(e.publicKeyCredential))}:{...e},new rU((await aR._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=rA.clerk.__internal_isWebAuthnSupported||rb,t=rA.clerk.__internal_getPublicCredentials||tV;if(!a())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tH(JSON.parse(e)):null;r||aP("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 rU((await aR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rU((await aR._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=aF(e.expire_at),this.abandonAt=aF(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aF(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aF(e.created_at),this.updatedAt=aF(e.updated_at),this.user=new rV(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rj(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rK(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.#eh(t,i),s=r?void 0:tT.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){e7.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&re.emit(t5,{token:e}),e.getRawString()||null}e7.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=this.lastActiveToken?.getRawString(),u=rK.create(l,c,r?{debug:"skip_cache"}:void 0).catch(e=>{if(z.is(e)&&d)return rK.create(l,{...c},{expired_token:d});throw e});return tT.set({tokenId:n,tokenResolver:u}),u.then(e=>(o&&(re.emit(t5,{token:e}),e.jwt&&(this.lastActiveToken=e,re.emit(t7,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rC extends aR{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aR.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rC(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=aF(e.expire_at),this.abandonAt=aF(e.abandon_at),this.lastActiveAt=aF(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 rI=(e,a,t)=>{let{onValidation:r=e0,onValidationComplexity:i=e0}=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 rP(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rO(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rP(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 rT(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rP(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 rE(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rP(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 rM(e,a){re.emit("resource:error",{resource:e,error:null}),re.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return re.emit("resource:error",{resource:e,error:a}),{error:a}}finally{re.emit("resource:fetch",{resource:e,status:"idle"})}}let rR=()=>{var e;return(e=new an,{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 rF extends aR{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new t1(null);secondFactorVerification=new t1(null);identifier=null;createdSessionId=null;userData=new rG(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&e7.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rD(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e7.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=am();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(e7.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":case"web3_solana_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:aU("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return e7.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tY(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tL();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aS("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status||"needs_client_trust"===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=>(e7.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e7.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=rF.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):aI(c,rF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aC("popup"),rO(rF.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",walletName:n}=e||{},s=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aC("generateSignature"),"solana"!==s||n||aC("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aA("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aA("SignIn");try{a=await r({identifier:t,nonce:l,walletName:n,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)a=await r({identifier:t,nonce:l,provider:s,walletName:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await ay().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ay().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ay().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ay().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ay().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await ay().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>ay().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rF.clerk.__internal_isWebAuthnSupported||rb,r=rF.clerk.__internal_getPublicCredentials||tV,i=rF.clerk.__internal_isWebAuthnAutofillSupported||rf;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?tH(JSON.parse(n)):null;s||aP("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(rF.clerk.__internal_environment?.userSettings.passwordSettings)return rI(rR(),{...rF.clerk.__internal_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=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new t1(e.first_factor_verification),this.secondFactorVerification=new t1(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rG(e.user_data),this.clientTrustState=e.client_trust_state??void 0),re.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:ee(this.supportedFirstFactors),supported_second_factors:ee(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 rD{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(!s())return null;const e=eI("__clerk_status"),a=eI("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rF.clerk.client&&rF.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)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rM(this.#ep,async()=>{let e=this.#ep.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.#ep.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=am();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rM(this.#ep,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 rM(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=am();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.#ep.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rM(this.#ep,async()=>{let{run:e,stop:a}=tL();await new Promise((t,r)=>{e(async()=>{try{let e=await this.#ep.__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.#ep.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rM(this.#ep,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.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rF.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rT(rF.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.#ep.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#ep.firstFactorVerification;"unverified"===c&&d&&(i?(await rE(rF.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):eW(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rM(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await ay().getMetamaskIdentifier(),i=ay().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await ay().getCoinbaseWalletIdentifier(),i=ay().generateSignatureWithCoinbaseWallet;break;case"base":r=await ay().getBaseIdentifier(),i=ay().generateSignatureWithBase;break;case"okx_wallet":r=await ay().getOKXWalletIdentifier(),i=ay().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await ay().getSolanaIdentifier(e.walletName),i=a=>ay().generateSignatureWithSolana({...a,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===a);if(!s)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await i({identifier:r,nonce:o,walletName:e?.walletName,provider:t})}catch(e){if("coinbase_wallet"===t&&4001===e.code)n=await i({identifier:r,nonce:o,provider:t});else throw e}await this.#ep.__internal_basePost({body:{signature:n,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rF.clerk.__internal_isWebAuthnSupported||rb,r=rF.clerk.__internal_getPublicCredentials||tV,i=rF.clerk.__internal_isWebAuthnAutofillSupported||rf;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rM(this.#ep,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.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tH(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.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tY(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rM(this.#ep,async()=>{let e=this.#ep.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.#ep.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rM(this.#ep,async()=>{rF.clerk.client&&!rF.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rF.clerk.client.reload(),this.#em=!0,await rF.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.#ep.supportedFirstFactors)return null;if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.#ep.identifier);if(r)return r;let i=this.#ep.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rN(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rW extends aR{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new t0(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&&e7.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rL(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e7.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=am();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rW.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rN(a)})};prepareVerification=e=>(e7.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e7.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}=tL();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aS("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,walletName:o}=e||{},l=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aC("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:d}=this.verifications.web3Wallet;d||aA("SignUp");try{a=await t({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)a=await t({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await ay().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ay().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ay().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ay().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ay().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await ay().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>ay().generateSignatureWithSolana({...a,walletName:e}),unsafeMetadata:a,strategy:"web3_solana_signature",legalAccepted:t,walletName:e})};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=rW.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(j(e)&&P(e))return await rW.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aI(g,rW.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aC("popup"),rO(rW.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rN(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rW.clerk.__internal_environment?.userSettings.passwordSettings)return rI(rR(),{...rW.clerk.__internal_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 t0(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),re.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 rW.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rW.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rW.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aR._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new r$(e)))}class rL{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new aE(rW.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?rN(e.unsafeMetadata):void 0,locale:e.locale??am()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rM(this.#ep,async()=>{await this._create(e)})}async update(e){return rM(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rN(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rM(this.#ep,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rN(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rM(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rM(this.#ep,async()=>{await this.#ep.__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 rM(this.#ep,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:rW.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rT(rW.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.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(j(e)&&P(e))return await rW.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rE(rW.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):eW(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rM(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await ay().getMetamaskIdentifier(),n=ay().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ay().getCoinbaseWalletIdentifier(),n=ay().generateSignatureWithCoinbaseWallet;break;case"base":e=await ay().getBaseIdentifier(),n=ay().generateSignatureWithBase;break;case"okx_wallet":e=await ay().getOKXWalletIdentifier(),n=ay().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||aA("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.#ep.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rM(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rW.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class r$ extends aR{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rK extends aR{pathRoot="tokens";jwt;static async create(e,a={},t={}){return new rK(await aR._fetch({method:"POST",path:e,body:a,search:t}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ah(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ah(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rB extends aR{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=aF(e.updated_at),this.createdAt=aF(e.created_at)),this}}class rJ extends aR{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=aF(e.updated_at),this.createdAt=aF(e.created_at)),this}}class rV extends aR{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 rV}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case t$:return this.primaryEmailAddressId===e.id;case rw:return this.primaryPhoneNumberId===e.id;case rX:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new t$({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rk.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rw({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rX({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new ri((await aR._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rB((await aR._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rB((await aR._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tR((await aR._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rJ((await aR._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rN(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=>(re.emit(t4,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rC.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ro.delete(`${this.path()}/profile_image`):ro.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rH.retrieve(e);getOrganizationSuggestions=e=>rg.retrieve(e);getOrganizationMemberships=e=>rp.retrieve(e);leaveOrganization=async e=>new tR((await aR._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ty(e);addPaymentMethod=e=>tk(e);getPaymentMethods=e=>tw(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 t$(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 rw(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 rX(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 ri(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rk(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rp(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t3(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=aF(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aF(e.legal_accepted_at)),this.updatedAt=aF(e.updated_at||void 0),this.createdAt=aF(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 rG{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 rH extends aR{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aR._fetch({path:"/me/organization_invitations",method:"GET",search:a6(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rH(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=aF(e.created_at),this.updatedAt=aF(e.updated_at)),this}}let rQ={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 rY extends aR{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:{...rQ,name:"phone_number"},username:{...rQ,name:"username"},web3_wallet:{...rQ,name:"web3_wallet"},first_name:{...rQ,name:"first_name"},last_name:{...rQ,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:{...rQ,name:"authenticator_app"},backup_code:{...rQ,name:"backup_code"},passkey:{...rQ,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}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 rX extends aR{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 t1(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class rZ extends aR{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aF(e.updated_at),this.createdAt=aF(e.created_at),re.emit("resource:update",{resource:this})),this}async join(e){return rM(this,async()=>{await rZ.join(e)})}static async join(e){return new rZ(await aR._fetch({path:"/waitlist",method:"POST",body:e}))}}function r1(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 r2(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(tE.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rA.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&&r1(t.user,r.user))}if(rV.isUserResource(e))return r1(e,a)}catch{}return!0}(e,a)?e:a}let r0="__clerk_db_jwt";function r9(e,a){let t=new URL(e),r=t.searchParams.get(r0);t.searchParams.delete(r0);let i=r||a;return i&&t.searchParams.set(r0,i),t}let r3=e=>{let a=new URL(e);return a.searchParams.delete(r0),a},r8=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 r5(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 r4=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r5({},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,"",r5({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r5({},this.attributes,a))},withConverter:function(a){return e(r5({},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 r6(e){return{get:()=>r4.get(e),set(a,t={}){r4.set(e,a,t)},remove(a){r4.remove(e,a)}}}let r7=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ie(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 ia=r6("__clerk_test_etld"),it="__client_uat",ir="__session",ii=()=>{let e=ag()?"None":"Lax",a=r7(e);return{sameSite:e,secure:a,partitioned:!1}};async function is(e){let a;try{a=await eh(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(t)||(console.log(t),V.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 io=()=>{let e=ag()?"None":"Lax",a=r7(e);return{sameSite:e,secure:a}};var il=i(945),ic=i.n(il);class id{lock=(function(e){let a=new(ic());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tW();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 iu{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await is(e.publishableKey),n=new iu(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,re.on(t5,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),re.on(t4,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r6(it),r=r6(em(it,e));return{set:e=>{let i=ie(Date.now(),1),n=ag()?"None":"Strict",s=r7(n),o=function(e=window.location.hostname,a=ia){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()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r6(ir),t=r6(em(ir,e)),r=()=>{let e=ii();a.remove(e),t.remove(e)};return{set:e=>{let i=ie(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=ii();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r6("clerk_active_context"),a={secure:r7("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r6(r0),i=r6(em(r0,e)),{get:()=>i.get()||r.get(),set:e=>{let a=ie(Date.now(),1),{sameSite:t,secure:n}=io();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=io();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(!ey(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r9(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(r0)||"",r3(r8(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r3(r8(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 k(e)):[]}((await c.json()).errors);e[0]?ax(e[0].longMessage):ax()}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 r9(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new id,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||d()||e7.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(j(e)||C(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(O(e))return void this.clerk.handleUnauthenticated().catch(e0);this.clerkEventBus.emit(g,"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 ih{clerk;captchaChallenge;timers;constructor(e,a=new aE(e),t=tW()){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.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let im=["/client","/waitlist"];class ip{async getBaseFapiProxyOptions(){let e=await aR.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 aR._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a6({...e,subject:e?.subject??aR.clerk.organization?.id??aR.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aD(e))}})}async create(e){return new aD(await aR._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aR.clerk.organization?.id??aR.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aD(await aR._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ig=new Map;class ib{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(s())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){G(`[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 G(`[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:G(`[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 G(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}G(`[protect] loader target is invalid: ${t}`)}}}class iy{signInResourceSignal=te;signInErrorSignal=ta;signInFetchSignal=tt;signInSignal=tr;signUpResourceSignal=ti;signUpErrorSignal=tn;signUpFetchSignal=ts;signUpSignal=to;waitlistResourceSignal=tl;waitlistErrorSignal=tc;waitlistFetchSignal=td;waitlistSignal=tu;_waitlistInstance;__internal_effect=a2;__internal_computed=a1;constructor(){re.on("resource:update",this.onResourceUpdated),re.on("resource:error",this.onResourceError),re.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new rZ(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rF&&this.signInErrorSignal({error:e.error}),e.resource instanceof rW&&this.signUpErrorSignal({error:e.error}),e.resource instanceof rZ&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rF){if(ik(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rW){if(ik(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof rZ&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rF&&this.signInFetchSignal({status:e.status}),e.resource instanceof rW&&this.signUpFetchSignal({status:e.status}),e.resource instanceof rZ&&this.waitlistFetchSignal({status:e.status})}}function ik(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let iw="cannot_render_billing_disabled",iv="cannot_render_user_missing",ij="cannot_render_organizations_disabled",iz="cannot_render_organization_missing",i_="cannot_render_single_session_enabled",ix={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 iq{static version="6.0.0-canary.v20260109111147";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20260109111147"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iy;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eA={};#eC=null;#eI=0;#eP=p();get __internal_queryClient(){return this.#eg||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#eg||(this.#eg=new e,this.#eP.emit("queryClientStatus","ready"))}),this.#eg?{__tag:"clerk-rq-client",client:this.#eg}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eb}get version(){return iq.version}set sdkMetadata(e){iq.sdkMetadata=e}get sdkMetadata(){return iq.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ap()&&e2(this.#eA.isSatellite,new URL(window.location.href),!1)}get domain(){if(ap()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e2(this.#ef,new URL(window.location.href)));if("production"===this.#ex){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(ap()){let e=e2(this.#ey,new URL(window.location.href));return!e||eL(e)||e$(e)||ad.throwInvalidProxyUrl({url:e}),e?e$(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ed(this.publishableKey);return e?e.frontendApi:ad.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eA.standardBrowser||!1}get billing(){return iq._billing||(iq._billing=new a7),iq._billing}get apiKeys(){return iq._apiKeys||(iq._apiKeys=new ip),iq._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=ig.get(c);if(d)return d.signals.computedSignal();let u=(t=aZ({resource:null}),r=aZ({error:null}),i=aZ({status:"idle"}),n=a1(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:th(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new tg(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ig.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eA[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ad.throwMissingPublishableKeyError();const t=ed(e);if(!t)return ad.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=rr.getInstance(),this.#ex=t.instanceType,this.#eb=e,this.#e_=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__internal_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.__internal_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.v20260109111147"),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&&!im.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eg([...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)),ev({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ev({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:d}=o;!d||"object"!=typeof d||d 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}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d 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=d?eg(d,{keyEncoder:X}):d);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??(c()?4:11);n=await ar(()=>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();e7.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||e7.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.#eP.emit(g,"loading"),this.#eP.prioritizedOn(g,e=>this.#eq=e),aR.clerk=this,this.#ew=new ib}getFapiClient=()=>this.#e_;load=async e=>{if(e7.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||G("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.#eA=this.#eO(e),this.#eA.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eA.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eA,new an))),"development"===this.#ex&&(this.#eA.routerPush||this.#eA.routerReplace)&&(!this.#eA.routerPush||!this.#eA.routerReplace)){let e=this.#eA.routerPush?"routerReplace":"routerPush";G(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}re.on(t7,()=>{this.#eT(this.session),this.#eE()}),this.#eA.sdkMetadata&&(iq.sdkMetadata=this.#eA.sdkMetadata),!1!==this.#eA.telemetry&&(this.telemetry=new eG({clerkVersion:iq.version,samplingRate:1,perEventSampling:!this.#eA.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eA.telemetry}),this.#eA.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e1(e);if(t){a=t;break}}else a=e1(t);return{themeName:a}}(this.#eA.appearance)}));try{this.#eA.standardBrowser?await this.#eM():await this.#eR();let e=this.#eA.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eA.__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(e8)return;let{enabled:a=!1,...t}=e;a&&(e9=!0,e8=!0,e6(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),e7.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(g,"error"),e7.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eA.signUpUrl&&this.#eA.signInUrl&&(e=this.#eA.signInUrl,!ep.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();e7.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=as(this.#eA.standardBrowser);re.emit(t4,null),this.#eD(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eT(),this.#eE(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#eA.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e7.info("signOut() complete",{redirectUrl:ej(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(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(eZ("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(D(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotOpenSignInOrSignUp,{code:i_});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eF()};this.telemetry?.record(eZ("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("Checkout"),{code:iw});return}if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenCheckout,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("PlanDetails"),{code:iw});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(eZ("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenUserProfile,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(eZ("UserVerification",e))};__internal_closeReverification=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ex||G(`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.#ex&&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.#ez),this.#ez.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(a=>a.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eX("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ez),this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(a_("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(D(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotOpenSignInOrSignUp,{code:i_});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(eZ("SignUp",e))};closeSignUp=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotOpenUserProfile,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eZ("UserProfile",e,a))};closeUserProfile=()=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ij})}});if(a){if(!this.organization){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(eZ("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ij})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(eZ("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(eZ("Waitlist",e))};closeWaitlist=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignIn";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eF()};this.telemetry?.record(eX(t,a,r))};unmountSignIn=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserAvatar";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountUserAvatar=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignUp";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountSignUp=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenUserDoesNotExist,{code:iv});return}this.assertComponentsReady(this.#ez);let t="UserProfile";this.#ez.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(eX(t,a,r))};unmountUserProfile=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ij})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new A(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez);let i="OrganizationProfile";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(eX(i,a))};unmountOrganizationProfile=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="CreateOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountCreateOrganization=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationSwitcher";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ez),this.#ez.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(eF.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationList";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserButton";this.#ez.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(eX(t,a,r))};unmountUserButton=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ez);let t="Waitlist";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(N(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAnyBillingComponent("PricingTable"),{code:iw});return}this.assertComponentsReady(this.#ez);let t="PricingTable";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountPricingTable=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(G("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),W(this,t=this.environment)&&L(this,t)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&L(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(W(this,this.environment)){if("development"===this.#ex)throw new A(eF.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ez);let r="APIKeys";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountAPIKeys=e=>{this.#ez?.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(eF.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ij})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="TaskChooseOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountTaskChooseOrganization=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskResetPassword=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:a})),this.telemetry?.record(eX("TaskResetPassword",a))};unmountTaskResetPassword=e=>{this.#ez?.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,e7.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 e7.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 e7.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.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eA,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||G('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 u=void 0!==a;if(c&&u){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),(ap()&&globalThis.document.hasFocus()||!this.#eA.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(d()||e7.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),re.emit(t5,{token:null}));let h=as(this.#eA.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eA.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eD(),m){let e=t?ev({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.#eT(c),this.#eE(),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:r2((r=t).client,e.client),session:r2(r.session,e.session),user:r2(r.user,e.user),organization:r2(r.organization,e.organization)}})},this.#eS.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eS=this.#eS.filter(a=>a!==e)}};on=(...e)=>{this.#eP.on(...e)};off=(...e)=>{this.#eP.off(...e)};__internal_addNavigationListener=e=>(this.#eU.push(e),()=>{this.#eU=this.#eU.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ap())return;setTimeout(()=>{this.#eL()},0);let t=new URL(e,window.location.href);this.#e$.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.#eA.routerReplace?this.#eA.routerReplace:this.#eA.routerPush;if(e7.info(`Clerk is navigating to: ${t}`),this.#eA.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eW(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eW};return await r(ej(t),i)};buildUrlWithAuth(e){if("production"===this.#ex)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ek?this.#ek.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("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 eU(this.#eA,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eU(this.#eA,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eA.afterSignOutUrl?this.buildUrlWithAuth(this.#eA.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eA.newSubscriptionRedirectUrl?this.#eA.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ev({base:this.#eA.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eA.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eA.afterMultiSessionSingleSignOutUrl):this.#eA.signInUrl?this.buildUrlWithAuth(ev({base:this.#eA.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.#eA.taskUrls?.[a.key];return t||ev({base:this.buildSignInUrl(e),hashPath:eE(a)},{stringify:!0})}#eB=async()=>{if(!ap())return;let e=new URLSearchParams({[$]:"true"}),a=eI(B);a&&eL(a)||function(){throw Error(`${az} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ev({base:eI(B),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ap())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ap())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ap())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ap())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ap())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ap())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ap())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ap())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ap())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ap())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ap())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eI("__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=eI("__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):e0;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||ev({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ev({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eU(this.#eA,e),b=c(e.continueSignUpUrl||ev({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=eO();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||ev({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ev({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 eM(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:aq("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:aq("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 z=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="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:z?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 tE.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&re.emit(t4,null),this.setActive({session:null})}catch(e){if(j(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(a_("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"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,u=i.replace("web3_","").replace("_signature",""),h=await ay().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=ay().generateSignatureWithMetamask;break;case"base":l=ay().generateSignatureWithBase;break;case"coinbase_wallet":l=ay().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>ay().generateSignatureWithSolana({...e,walletName:o});break;default:l=ay().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ev({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ev({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:i,walletName:o})}catch(e){if(ac(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:i,legalAccepted:n,walletName:o}),a&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await g();else throw e}let b=async({session:e,redirectUrl:a})=>{e.currentTask?await eM(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:a})=>{await b({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rh.create({name:e,slug:a});getOrganization=async e=>rh.get(e);joinWaitlist=async({emailAddress:e})=>rZ.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.#eA.selectInitialSession?this.#eA.selectInitialSession(e):this.#eJ(e);this.#eT(a)}if(this.client=e,this.session){let e=this.#eW(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0)(),this.#eT(e),this.session?.lastActiveToken||d()||e7.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),re.emit(t5,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rr(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let a={...e,options:this.#eO({...this.#eA,...e.options})};return this.#ez?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eV=()=>{let e=new URLSearchParams({[B]:window.location.href});return ev({base:this.#eA.signInUrl,searchParams:e},{stringify:!0})};#eG=()=>{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()||""};#eH=()=>"true"!==eI($)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eI(B);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eX=(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.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ex||this.#eA.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.#eA.signInUrl&&this.#eX(this.#eA.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await iu.create(this,this.#e_,this.#ex,this.#eP),this.#eZ(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eC=(()=>{if(!s())return{onPageFocus:e0};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ej=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let a=ek.get(e);void 0===a&&(a=ei.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||en.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ek.set(e,a));return a}(window?.location.hostname),a="development"===this.#ex&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=rr.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=aj.getItem(ak,null);e&&this.updateEnvironment(new rr(e))}),r=async()=>tE.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(O(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rK({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tE.clearInstance(),!a?.jwt)return tE.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}=rS(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 tE.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ek?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ek?.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(ac(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(ac(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${az} Something went wrong initializing Clerk.`)}()}this.#ev=new ih(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(g,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:t}),tE.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(C(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new rr(t?.environment),tE.clearInstance(),a=tE.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([rr.getInstance().fetch({touch:!1,fetchMaxTries:1}),tE.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eE()};#eJ=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#e1=()=>{s()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eA.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),re.on(t4,()=>{this.#ej?.postMessage({type:"signout"})}),re.on(t6,()=>{aj.setItem(ak,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{O(e)&&this.handleUnauthenticated()})};#eE=()=>{if(this.client)for(let e of this.#eS)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eU)e()};#eD=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eE()};#e8=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e8(),this.user=this.session?this.session.user:null};#eW=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#e9=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ez?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e3=()=>{this.#eA.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eA.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eA.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eA.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eA[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eA.signInUrl);let i=new eU(this.#eA,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ev({base:r,hashPath:this.#eF()&&"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")}#e2=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,eb)).pathname,r=eq.includes(t)||eS.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eA.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eA.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,eb),(!eq.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...ix,...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://${ew(a)}`),r.push(`https://*.${ew(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eP($),eP(eA),eP(K),eP("__clerk_handshake"),eP("__clerk_handshake_nonce"),eP("__clerk_help")}catch{}};get #e$(){let e=eN;return this.#eA.allowedRedirectProtocols&&(e=e.concat(this.#eA.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();