@clerk/clerk-js 6.3.1-snapshot.v20260311230607 → 6.3.1

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 (42) hide show
  1. package/dist/clerk.browser.js +6 -6
  2. package/dist/clerk.js +6 -6
  3. package/dist/clerk.legacy.browser.js +1 -1
  4. package/dist/clerk.mjs +6 -6
  5. package/dist/clerk.native.js +6 -6
  6. package/dist/clerk.no-rhc.js +6 -6
  7. package/dist/clerk.no-rhc.mjs +6 -6
  8. package/dist/types/utils/errorThrower.d.ts +1 -1
  9. package/dist/types/utils/web3.d.ts +2 -2
  10. package/package.json +4 -4
  11. /package/dist/{507_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → 507_clerk.browser_5873a4_6.3.1.js} +0 -0
  12. /package/dist/{507_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → 507_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  13. /package/dist/{507_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 507_clerk.native_730332_6.3.1.js} +0 -0
  14. /package/dist/{521_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 521_clerk.native_730332_6.3.1.js} +0 -0
  15. /package/dist/{527_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → 527_clerk.browser_5873a4_6.3.1.js} +0 -0
  16. /package/dist/{527_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → 527_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  17. /package/dist/{537_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 537_clerk.native_730332_6.3.1.js} +0 -0
  18. /package/dist/{604_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 604_clerk.native_730332_6.3.1.js} +0 -0
  19. /package/dist/{675_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 675_clerk.native_730332_6.3.1.js} +0 -0
  20. /package/dist/{783_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 783_clerk.native_730332_6.3.1.js} +0 -0
  21. /package/dist/{836_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → 836_clerk.browser_5873a4_6.3.1.js} +0 -0
  22. /package/dist/{836_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → 836_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  23. /package/dist/{836_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 836_clerk.native_730332_6.3.1.js} +0 -0
  24. /package/dist/{896_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 896_clerk.native_730332_6.3.1.js} +0 -0
  25. /package/dist/{973_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → 973_clerk.native_730332_6.3.1.js} +0 -0
  26. /package/dist/{base-account-sdk_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → base-account-sdk_clerk.browser_5873a4_6.3.1.js} +0 -0
  27. /package/dist/{base-account-sdk_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → base-account-sdk_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  28. /package/dist/{coinbase-wallet-sdk_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → coinbase-wallet-sdk_clerk.browser_5873a4_6.3.1.js} +0 -0
  29. /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → coinbase-wallet-sdk_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  30. /package/dist/{cookieSuffix_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → cookieSuffix_clerk.browser_5873a4_6.3.1.js} +0 -0
  31. /package/dist/{cookieSuffix_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → cookieSuffix_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  32. /package/dist/{cookieSuffix_clerk.native_afe64e_6.3.1-snapshot.v20260311230607.js → cookieSuffix_clerk.native_730332_6.3.1.js} +0 -0
  33. /package/dist/{query-core-vendors_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → query-core-vendors_clerk.browser_5873a4_6.3.1.js} +0 -0
  34. /package/dist/{query-core-vendors_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → query-core-vendors_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  35. /package/dist/{stripe-vendors_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → stripe-vendors_clerk.browser_5873a4_6.3.1.js} +0 -0
  36. /package/dist/{stripe-vendors_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → stripe-vendors_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  37. /package/dist/{vendors_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → vendors_clerk.browser_5873a4_6.3.1.js} +0 -0
  38. /package/dist/{vendors_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → vendors_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  39. /package/dist/{zxcvbn-common_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → zxcvbn-common_clerk.browser_5873a4_6.3.1.js} +0 -0
  40. /package/dist/{zxcvbn-common_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → zxcvbn-common_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
  41. /package/dist/{zxcvbn-ts-core_clerk.browser_5892b3_6.3.1-snapshot.v20260311230607.js → zxcvbn-ts-core_clerk.browser_5873a4_6.3.1.js} +0 -0
  42. /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_baa683_6.3.1-snapshot.v20260311230607.js → zxcvbn-ts-core_clerk.legacy.browser_ff8c85_6.3.1.js} +0 -0
@@ -1,4 +1,4 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(globalThis,()=>(()=>{var e,t,i,r={5945:function(e,t,i){"use strict";var r=this&&this.__awaiter||function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){e.done?n(e.value):new i(function(t){t(e.value)}).then(a,o)}l((r=r.apply(e,t||[])).next())})},n=this&&this.__generator||function(e,t){var i,r,n,s,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){var l=[s,o];if(i)throw TypeError("Generator is already executing.");for(;a;)try{if(i=1,r&&(n=2&l[0]?r.return:l[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,l[1])).done)return n;switch(r=0,n&&(l=[2&l[0],n.value]),l[0]){case 0:case 1:n=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,r=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!n||l[1]>n[0]&&l[1]<n[3])){a.label=l[1];break}if(6===l[0]&&a.label<n[1]){a.label=n[1],n=l;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(l);break}n[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],r=0}finally{i=n=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}},s=this;Object.defineProperty(t,"__esModule",{value:!0});var a=i(6599),o="browser-tabs-lock-key",l={key:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},clear:function(){return r(s,void 0,void 0,function(){return n(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function c(e){return new Promise(function(t){return setTimeout(t,e)})}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",i="",r=0;r<e;r++){var n=Math.floor(Math.random()*t.length);i+=t[n]}return i}t.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),r(this,void 0,void 0,function(){var r,s,a,h,u,p,f;return n(this,function(n){switch(n.label){case 0:r=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,n.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(n.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+r,[4,c(Math.floor(25*Math.random()))];case 3:return n.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(n.sent(),null!==(p=h.getItemSync(a))&&(f=JSON.parse(p)).id===this.id&&f.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:n.sent(),n.label=7;case 7:return r=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return r(this,void 0,void 0,function(){var i=this;return n(this,function(s){return setTimeout(function(){return r(i,void 0,void 0,function(){var i,r,s;return n(this,function(n){switch(n.label){case 0:return[4,a.default().lock(t)];case 1:if(n.sent(),!this.acquiredIatSet.has(t)||null===(r=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(r)).timeRefreshed=Date.now(),i.setItemSync(e,JSON.stringify(s)),a.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2]}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return r(this,void 0,void 0,function(){return n(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var r=!1,n=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!r){r=!0;var t=50-(Date.now()-n);t>0?setTimeout(i,t):i(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var o=setTimeout(a,Math.max(0,t-Date.now()))})];case 1:return i.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,function(){return n(this,function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}})})},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,function(){var i,r,s,c;return n(this,function(n){switch(n.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,r=o+"-"+t,null===(s=i.getItemSync(r)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:n.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(r),a.default().unlock(c.iat),e.notifyWaiters(),n.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,r=[],n=0;;){var s=t.keySync(n);if(null===s)break;r.push(s),n++}for(var a=!1,l=0;l<r.length;l++){var c=r[l];if(c.includes(o)){var d=t.getItemSync(c);if(null!==d){var h=JSON.parse(d);(void 0===h.timeRefreshed&&h.timeAcquired<i||void 0!==h.timeRefreshed&&h.timeRefreshed<i)&&(t.removeItemSync(c),a=!0)}}}a&&e.notifyWaiters()},e.waiters=void 0,e}()},6599:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,i){var r=e.locked.get(t);void 0===r?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(r.unshift(i),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,r){e.isLocked(t)?e.addToLocked(t,i):(e.addToLocked(t),i())})},this.unlock=function(t){var i=e.locked.get(t);if(void 0===i||0===i.length)return void e.locked.delete(t);var r=i.pop();e.locked.set(t,i),void 0!==r&&setTimeout(r,0)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return i.getInstance()}},1006:function(e){e.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");for(var i,r=String(e),n="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=r.length;c<d;c++)switch(i=r[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":n+="\\"+i;break;case"?":if(s){n+=".";break}case"[":case"]":if(s){n+=i;break}case"{":if(s){o=!0,n+="(";break}case"}":if(s){o=!1,n+=")";break}case",":if(o){n+="|";break}n+="\\"+i;break;case"*":for(var h=r[c-1],u=1;"*"===r[c+1];)u++,c++;var p=r[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(n+="((?:[^/]*(?:/|$))*)",c++):n+="([^/]*)":n+=".*";break;default:n+=i}return l&&~l.indexOf("g")||(n="^"+n+"$"),new RegExp(n,l)}},2105:function(e,t,i){"use strict";i.d(t,{t:()=>r});let r=(...e)=>{}},4821:function(e,t,i){"use strict";function r(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}i.d(t,{a:()=>r})},2044:function(e,t,i){"use strict";function r(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}i.d(t,{vd:()=>s.a,VK:()=>r,lQ:()=>n.t});var n=i(2105),s=i(4821)}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e].call(i.exports,i,i.exports,s),i.exports}s.m=r,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},o=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var i=Object.create(null);s.r(i);var r={};a=a||[null,o({}),o([]),o(o)];for(var n=2&t&&e;("object"==typeof n||"function"==typeof n)&&!~a.indexOf(n);n=o(n))Object.getOwnPropertyNames(n).forEach(t=>{r[t]=()=>e[t]});return r.default=()=>e,s.d(i,r),i},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>""+(({279:"stripe-vendors",545:"vendors",662:"query-core-vendors",729:"zxcvbn-ts-core",811:"cookieSuffix",873:"zxcvbn-common",929:"coinbase-wallet-sdk",994:"base-account-sdk"})[e]||e)+"_clerk.browser_"+s.h().slice(0,6)+"_6.3.1-snapshot.v20260311230607.js",s.h=()=>"5892b38a6c9c2d7e",s.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l={},s.l=function(e,t,i,r){if(l[e])return void l[e].push(t);if(void 0!==i)for(var n,a,o=document.getElementsByTagName("script"),c=0;c<o.length;c++){var d=o[c];if(d.getAttribute("src")==e||d.getAttribute("data-webpack")=="@clerk/clerk-js:"+i){n=d;break}}n||(a=!0,(n=document.createElement("script")).timeout=120,s.nc&&n.setAttribute("nonce",s.nc),n.setAttribute("data-webpack","@clerk/clerk-js:"+i),n.src=e),l[e]=[t];var h=function(t,i){n.onerror=n.onload=null,clearTimeout(u);var r=l[e];if(delete l[e],n.parentNode&&n.parentNode.removeChild(n),r&&r.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=h.bind(null,n.onerror),n.onload=h.bind(null,n.onload),a&&document.head.appendChild(n)},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.g.importScripts&&(c=s.g.location+"");var a,o,l,c,d=s.g.document;if(!c&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(c=d.currentScript.src),!c)){var h=d.getElementsByTagName("script");if(h.length)for(var u=h.length-1;u>-1&&(!c||!/^http(s?):/.test(c));)c=h[u--].src}if(!c)throw Error("Automatic publicPath is not supported in this browser");return s.p=c=c.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),e={349:0},s.f.j=function(t,i){var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)i.push(r[2]);else{var n=new Promise((i,n)=>r=e[t]=[i,n]);i.push(r[2]=n);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var n=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,r[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var r,n,a=i[0],o=i[1],l=i[2],c=0;if(a.some(t=>0!==e[t])){for(r in o)s.o(o,r)&&(s.m[r]=o[r]);l&&l(s)}for(t&&t(i);c<a.length;c++)n=a[c],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},(i=globalThis.webpackChunk_clerk_clerk_js=globalThis.webpackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),(()=>{"use strict";let e,t,i,r;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;s.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.3.1-snapshot.v20260311230607$3")}catch{}function n(){return"undefined"!=typeof window}let a=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i");function o(){var e;let t=n()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=n()?window?.navigator:null;return!!e&&!!e.onLine}function c(){return l()&&o()}let d=(e,t,i,r,n)=>{let{notify:s}=n||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(r),s&&t.has(i)&&r(t.get(i))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>d(e,t,...i),prioritizedOn:(...e)=>d(i,t,...e),emit:(r,n)=>{t.set(r,n),h(i,r,n),h(e,r,n)},off:(...t)=>u(e,...t),prioritizedOff:(...e)=>u(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function m(e){return function(t){let i=t??this;if(!i)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return!!e.kind&&"object"==typeof i&&null!==i&&"constructor"in i&&i.constructor?.kind===e.kind||i instanceof e}}var g,_,w=class e extends Error{static kind="ClerkError";clerkError=!0;code;longMessage;docsUrl;cause;get name(){return this.constructor.name}constructor(t){super(new.target.formatMessage(new.target.kind,t.message,t.code,t.docsUrl),{cause:t.cause}),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.docsUrl=t.docsUrl,this.longMessage=t.longMessage,this.cause=t.cause}toString(){return`[${this.name}]
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(globalThis,()=>(()=>{var e,t,i,r={5945:function(e,t,i){"use strict";var r=this&&this.__awaiter||function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){e.done?n(e.value):new i(function(t){t(e.value)}).then(a,o)}l((r=r.apply(e,t||[])).next())})},n=this&&this.__generator||function(e,t){var i,r,n,s,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){var l=[s,o];if(i)throw TypeError("Generator is already executing.");for(;a;)try{if(i=1,r&&(n=2&l[0]?r.return:l[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,l[1])).done)return n;switch(r=0,n&&(l=[2&l[0],n.value]),l[0]){case 0:case 1:n=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,r=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!n||l[1]>n[0]&&l[1]<n[3])){a.label=l[1];break}if(6===l[0]&&a.label<n[1]){a.label=n[1],n=l;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(l);break}n[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],r=0}finally{i=n=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}},s=this;Object.defineProperty(t,"__esModule",{value:!0});var a=i(6599),o="browser-tabs-lock-key",l={key:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},clear:function(){return r(s,void 0,void 0,function(){return n(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function c(e){return new Promise(function(t){return setTimeout(t,e)})}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",i="",r=0;r<e;r++){var n=Math.floor(Math.random()*t.length);i+=t[n]}return i}t.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),r(this,void 0,void 0,function(){var r,s,a,h,u,p,f;return n(this,function(n){switch(n.label){case 0:r=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,n.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(n.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+r,[4,c(Math.floor(25*Math.random()))];case 3:return n.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(n.sent(),null!==(p=h.getItemSync(a))&&(f=JSON.parse(p)).id===this.id&&f.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:n.sent(),n.label=7;case 7:return r=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return r(this,void 0,void 0,function(){var i=this;return n(this,function(s){return setTimeout(function(){return r(i,void 0,void 0,function(){var i,r,s;return n(this,function(n){switch(n.label){case 0:return[4,a.default().lock(t)];case 1:if(n.sent(),!this.acquiredIatSet.has(t)||null===(r=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(r)).timeRefreshed=Date.now(),i.setItemSync(e,JSON.stringify(s)),a.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2]}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return r(this,void 0,void 0,function(){return n(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var r=!1,n=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!r){r=!0;var t=50-(Date.now()-n);t>0?setTimeout(i,t):i(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var o=setTimeout(a,Math.max(0,t-Date.now()))})];case 1:return i.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,function(){return n(this,function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}})})},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,function(){var i,r,s,c;return n(this,function(n){switch(n.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,r=o+"-"+t,null===(s=i.getItemSync(r)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:n.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(r),a.default().unlock(c.iat),e.notifyWaiters(),n.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,r=[],n=0;;){var s=t.keySync(n);if(null===s)break;r.push(s),n++}for(var a=!1,l=0;l<r.length;l++){var c=r[l];if(c.includes(o)){var d=t.getItemSync(c);if(null!==d){var h=JSON.parse(d);(void 0===h.timeRefreshed&&h.timeAcquired<i||void 0!==h.timeRefreshed&&h.timeRefreshed<i)&&(t.removeItemSync(c),a=!0)}}}a&&e.notifyWaiters()},e.waiters=void 0,e}()},6599:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,i){var r=e.locked.get(t);void 0===r?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(r.unshift(i),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,r){e.isLocked(t)?e.addToLocked(t,i):(e.addToLocked(t),i())})},this.unlock=function(t){var i=e.locked.get(t);if(void 0===i||0===i.length)return void e.locked.delete(t);var r=i.pop();e.locked.set(t,i),void 0!==r&&setTimeout(r,0)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return i.getInstance()}},1006:function(e){e.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");for(var i,r=String(e),n="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=r.length;c<d;c++)switch(i=r[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":n+="\\"+i;break;case"?":if(s){n+=".";break}case"[":case"]":if(s){n+=i;break}case"{":if(s){o=!0,n+="(";break}case"}":if(s){o=!1,n+=")";break}case",":if(o){n+="|";break}n+="\\"+i;break;case"*":for(var h=r[c-1],u=1;"*"===r[c+1];)u++,c++;var p=r[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(n+="((?:[^/]*(?:/|$))*)",c++):n+="([^/]*)":n+=".*";break;default:n+=i}return l&&~l.indexOf("g")||(n="^"+n+"$"),new RegExp(n,l)}},2105:function(e,t,i){"use strict";i.d(t,{t:()=>r});let r=(...e)=>{}},4821:function(e,t,i){"use strict";function r(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}i.d(t,{a:()=>r})},2044:function(e,t,i){"use strict";function r(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}i.d(t,{vd:()=>s.a,VK:()=>r,lQ:()=>n.t});var n=i(2105),s=i(4821)}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e].call(i.exports,i,i.exports,s),i.exports}s.m=r,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},o=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var i=Object.create(null);s.r(i);var r={};a=a||[null,o({}),o([]),o(o)];for(var n=2&t&&e;("object"==typeof n||"function"==typeof n)&&!~a.indexOf(n);n=o(n))Object.getOwnPropertyNames(n).forEach(t=>{r[t]=()=>e[t]});return r.default=()=>e,s.d(i,r),i},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>""+(({279:"stripe-vendors",545:"vendors",662:"query-core-vendors",729:"zxcvbn-ts-core",811:"cookieSuffix",873:"zxcvbn-common",929:"coinbase-wallet-sdk",994:"base-account-sdk"})[e]||e)+"_clerk.browser_"+s.h().slice(0,6)+"_6.3.1.js",s.h=()=>"5873a4f6a796be73",s.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l={},s.l=function(e,t,i,r){if(l[e])return void l[e].push(t);if(void 0!==i)for(var n,a,o=document.getElementsByTagName("script"),c=0;c<o.length;c++){var d=o[c];if(d.getAttribute("src")==e||d.getAttribute("data-webpack")=="@clerk/clerk-js:"+i){n=d;break}}n||(a=!0,(n=document.createElement("script")).timeout=120,s.nc&&n.setAttribute("nonce",s.nc),n.setAttribute("data-webpack","@clerk/clerk-js:"+i),n.src=e),l[e]=[t];var h=function(t,i){n.onerror=n.onload=null,clearTimeout(u);var r=l[e];if(delete l[e],n.parentNode&&n.parentNode.removeChild(n),r&&r.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=h.bind(null,n.onerror),n.onload=h.bind(null,n.onload),a&&document.head.appendChild(n)},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.g.importScripts&&(c=s.g.location+"");var a,o,l,c,d=s.g.document;if(!c&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(c=d.currentScript.src),!c)){var h=d.getElementsByTagName("script");if(h.length)for(var u=h.length-1;u>-1&&(!c||!/^http(s?):/.test(c));)c=h[u--].src}if(!c)throw Error("Automatic publicPath is not supported in this browser");return s.p=c=c.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),e={349:0},s.f.j=function(t,i){var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)i.push(r[2]);else{var n=new Promise((i,n)=>r=e[t]=[i,n]);i.push(r[2]=n);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var n=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,r[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var r,n,[a,o,l]=i,c=0;if(a.some(t=>0!==e[t])){for(r in o)s.o(o,r)&&(s.m[r]=o[r]);l&&l(s)}for(t&&t(i);c<a.length;c++)n=a[c],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},(i=globalThis.webpackChunk_clerk_clerk_js=globalThis.webpackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),(()=>{"use strict";let e,t,i,r;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;s.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.3.1$3")}catch{}function n(){return"undefined"!=typeof window}let a=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i");function o(){var e;let t=n()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=n()?window?.navigator:null;return!!e&&!!e.onLine}function c(){return l()&&o()}let d=(e,t,i,r,n)=>{let{notify:s}=n||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(r),s&&t.has(i)&&r(t.get(i))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>d(e,t,...i),prioritizedOn:(...e)=>d(i,t,...e),emit:(r,n)=>{t.set(r,n),h(i,r,n),h(e,r,n)},off:(...t)=>u(e,...t),prioritizedOff:(...e)=>u(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function m(e){return function(t){let i=t??this;if(!i)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return!!e.kind&&"object"==typeof i&&null!==i&&"constructor"in i&&i.constructor?.kind===e.kind||i instanceof e}}var g,_,w=class e extends Error{static kind="ClerkError";clerkError=!0;code;longMessage;docsUrl;cause;get name(){return this.constructor.name}constructor(t){super(new.target.formatMessage(new.target.kind,t.message,t.code,t.docsUrl),{cause:t.cause}),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.docsUrl=t.docsUrl,this.longMessage=t.longMessage,this.cause=t.cause}toString(){return`[${this.name}]
2
2
  Message:${this.message}`}static formatMessage(e,t,i,r){let n="Clerk:",s=RegExp(n.replace(" ","\\s*"),"i");return t=t.replace(s,""),t=`${n} ${t.trim()}
3
3
 
4
4
  (code="${i}")
@@ -9,10 +9,10 @@ Docs: ${r}`),t}},y=class e extends w{static kind="ClerkRuntimeError";clerkRuntim
9
9
  Message:${this.message}
10
10
  Status:${this.status}
11
11
  Serialized errors: ${this.errors.map(e=>JSON.stringify(e))}`;return this.clerkTraceId&&(e+=`
12
- Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,i,r){return t}};let S=m(k);var I=class e extends k{static kind="MissingExpiredTokenError";static ERROR_CODE="missing_expired_token";static STATUS=422;static is(t){return S(t)&&t.status===e.STATUS&&t.errors.length>0&&t.errors[0].code===e.ERROR_CODE}},U=class e extends y{static kind="ClerkOfflineError";static ERROR_CODE="clerk_offline";constructor(t){super(t,{code:e.ERROR_CODE}),Object.setPrototypeOf(this,e.prototype)}static is(t){return null!=t&&(t instanceof e||b(t)&&t.code===e.ERROR_CODE)}};let A=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});function C({packageName:e,customMessages:t}){let i=e;function r(e,t){if(!t)return`${i}: ${e}`;let r=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();r=r.replace(`{{${i[1]}}}`,e)}return`${i}: ${r}`}let n={...A,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}var P=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}},T=class extends y{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function O(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function E(e){let t=e?.status;return!!t&&t>=400&&t<500}function x(e){let t=e?.status;return 401===t||422===t}function R(e){for(let[t,i]of Object.entries({isClerkAPIResponseError:S,isClerkRuntimeError:b}))Object.assign(e,{[t]:i});return e}let M=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),z=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,F=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,N=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,W="__clerk_synced",D="false",L="true",$="suffixed_cookies",j="__clerk_satellite_url",B="clerk-captcha",J="clerk-invisible-captcha";var K=s(1006);let V=new Set,q=e=>{V.has(e)||(V.add(e),console.warn(e))},H=(e,t)=>{let i={};for(let r in e)i[r]=t(e[r],r);return i},G=(e,t)=>{let i={};for(let r in e)e[r]&&t(e[r])&&(i[r]=e[r]);return i};function Q(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function X(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let Y=e=>{let t=i=>{if(!i)return i;if(Array.isArray(i))return i.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let r={...i};for(let i of Object.keys(r)){let n=e(i.toString());n!==i&&(r[n]=r[i],delete r[i]),"object"==typeof r[n]&&(r[n]=t(r[n]))}return r};return t},Z=Y(X),ee=Y(Q);function et(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let ei=RegExp("/{1,}","g"),er=[".lcl.dev",".lclstage.dev",".lclclerk.com"],en=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],es=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],ea=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):void 0!==globalThis.Buffer?globalThis.Buffer.from(e,"base64").toString():e,eo="pk_live_";function el(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function ec(e,t={}){let i;if(!(e=e||"")||!ed(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!ed(e))throw Error("Publishable key not valid.");return null}let r=e.startsWith(eo)?"production":"development";try{i=ea(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!el(i)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let n=i.slice(0,-1);return t.proxyUrl?n=t.proxyUrl:"development"!==r&&t.domain&&t.isSatellite&&(n=`clerk.${t.domain}`),{instanceType:r,frontendApi:n}}function ed(e=""){try{if(!(e.startsWith(eo)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let i=t[2];if(!i)return!1;return el(ea(i))}catch{return!1}}async function eh(e,t=globalThis.crypto.subtle){var i;let r=new TextEncoder().encode(e);return(i=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",r))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(i):void 0!==globalThis.Buffer?globalThis.Buffer.from(i).toString("base64"):i).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let eu=(e,t)=>`${e}_${t}`,ep=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,ef=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let i=new URLSearchParams;return Object.keys(e).forEach(r=>{let n=t.keyEncoder?t.keyEncoder(r):r,s=e[r];if(Array.isArray(s))s.forEach(e=>void 0!==e&&i.append(n,e||""));else{if(void 0===s)return;"object"==typeof s&&null!==s?i.append(n,JSON.stringify(s)):i.append(n,String(s??""))}}),i.toString()},em="http://clerk-dummy",eg=["javascript:"],{isDevOrStagingUrl:e_}=(r=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,i=r.get(t);return void 0===i&&(i=es.some(e=>t.endsWith(e)),r.set(t,i)),i}}),ew=new Map;function ey(e){return e.replace("clerk.","")}function eb(e,t={}){let{base:i,hashPath:r,hashSearch:n,searchParams:s,hashSearchParams:a,...o}=e,l=new URL(i||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(s instanceof URLSearchParams&&s.forEach((e,t)=>{null!=e&&l.searchParams.set(X(t),e)}),Object.assign(l,o),r||n||a){var c;let e,t=new URL(em+l.hash.substring(1));for(let[i,s]of(c=t.pathname,t.pathname=[c,r||""].filter(e=>e).join("/").replace(ei,"/"),Object.entries((e={},new URLSearchParams(n||"").forEach((t,i)=>{if(i in e){let r=e[i];Array.isArray(r)?r.push(t):e[i]=[r,t]}else e[i]=t}),e))))t.searchParams.append(i,s);if(a)for(let e of Array.isArray(a)?a:[a])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,i)=>{null!=e&&t.searchParams.set(X(i),e)});let i=t.href.replace(em,"");"/"!==i&&(l.hash=i)}let{stringify:d,skipOrigin:h}=t;return d?h?l.href.replace(l.origin,""):l.href:l}function ev(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let ek=e=>(e||"").replace(/\/+$/,"");function eS(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let eI=[/\0/,/^\/\//,/[\x00-\x1F]/],eU=["/oauth/authorize"],eA=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eC=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},i={},r){this.options=e,this.fromOptions=this.#e(e||{}),this.fromProps=this.#e(t||{}),this.fromSearchParams=this.#t(i||{}),this.mode=r}getAfterSignInUrl(){return this.#i("signIn")}getAfterSignUpUrl(){return this.#i("signUp")}getPreservedSearchParams(){return this.#r(this.#n())}toSearchParams(){return this.#r(this.#s())}#r(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[X(e),t]))).reduce((e,[t,i])=>(null!=i&&(e[t]=i),e),{}))}#n(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#s(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,i=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,r={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:i,redirectUrl:this.fromSearchParams.redirectUrl||this.fromProps.redirectUrl};return e&&delete r.signUpFallbackRedirectUrl,i&&delete r.signInFallbackRedirectUrl,r}#i(e){let t,i=`${e}ForceRedirectUrl`,r=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[i]||this.fromProps[i]||this.fromOptions[i],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[r]||this.fromProps[r]||this.fromOptions[r])||"modal"!==this.mode)?t||"/":window.location.href}#e(t){let i={};return e.keys.forEach(e=>{i[e]=t[e]}),H(this.#a(this.#o(G(i,Boolean))),e=>e.toString())}#t(t){let i={};return e.keys.forEach(e=>{t instanceof URLSearchParams?i[e]=t.get(X(e)):i[e]=t[X(e)]}),H(this.#a(this.#o(G(i,Boolean))),e=>e.toString())}#o(e){return H(e,e=>eS(e,window.location.origin))}#a=e=>{let t,i;return G(e,(t=this.options?.allowedRedirectOrigins,i=window.location.origin,e=>{let r=e;if("string"==typeof r&&(r=eS(r,i)),!t)return!0;let n=i===r.origin,s=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return eg.some(e=>e===t)}(e))return!0;for(let t of eI)if(t.test(e.pathname))return!0;return!1}(r)&&(n||t.map(e=>"string"==typeof e?(e=>{try{return K(e)}catch(t){throw Error(`Invalid pattern: ${e}.
12
+ Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,i,r){return t}};let S=m(k);var I=class e extends k{static kind="MissingExpiredTokenError";static ERROR_CODE="missing_expired_token";static STATUS=422;static is(t){return S(t)&&t.status===e.STATUS&&t.errors.length>0&&t.errors[0].code===e.ERROR_CODE}},U=class e extends y{static kind="ClerkOfflineError";static ERROR_CODE="clerk_offline";constructor(t){super(t,{code:e.ERROR_CODE}),Object.setPrototypeOf(this,e.prototype)}static is(t){return null!=t&&(t instanceof e||b(t)&&t.code===e.ERROR_CODE)}};let A=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});function C({packageName:e,customMessages:t}){let i=e;function r(e,t){if(!t)return`${i}: ${e}`;let r=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();r=r.replace(`{{${i[1]}}}`,e)}return`${i}: ${r}`}let n={...A,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}var P=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}},T=class extends y{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function O(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function E(e){let t=e?.status;return!!t&&t>=400&&t<500}function x(e){let t=e?.status;return 401===t||422===t}function R(e){for(let[t,i]of Object.entries({isClerkAPIResponseError:S,isClerkRuntimeError:b}))Object.assign(e,{[t]:i});return e}let F=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),M=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,z=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,N=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,W="__clerk_synced",D="false",L="true",$="suffixed_cookies",j="__clerk_satellite_url",B="clerk-captcha",J="clerk-invisible-captcha";var K=s(1006);let V=new Set,q=e=>{V.has(e)||(V.add(e),console.warn(e))},H=(e,t)=>{let i={};for(let r in e)i[r]=t(e[r],r);return i},G=(e,t)=>{let i={};for(let r in e)e[r]&&t(e[r])&&(i[r]=e[r]);return i};function Q(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function X(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let Y=e=>{let t=i=>{if(!i)return i;if(Array.isArray(i))return i.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let r={...i};for(let i of Object.keys(r)){let n=e(i.toString());n!==i&&(r[n]=r[i],delete r[i]),"object"==typeof r[n]&&(r[n]=t(r[n]))}return r};return t},Z=Y(X),ee=Y(Q);function et(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let ei=RegExp("/{1,}","g"),er=[".lcl.dev",".lclstage.dev",".lclclerk.com"],en=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],es=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],ea=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):void 0!==globalThis.Buffer?globalThis.Buffer.from(e,"base64").toString():e,eo="pk_live_";function el(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function ec(e,t={}){let i;if(!(e=e||"")||!ed(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!ed(e))throw Error("Publishable key not valid.");return null}let r=e.startsWith(eo)?"production":"development";try{i=ea(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!el(i)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let n=i.slice(0,-1);return t.proxyUrl?n=t.proxyUrl:"development"!==r&&t.domain&&t.isSatellite&&(n=`clerk.${t.domain}`),{instanceType:r,frontendApi:n}}function ed(e=""){try{if(!(e.startsWith(eo)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let i=t[2];if(!i)return!1;return el(ea(i))}catch{return!1}}async function eh(e,t=globalThis.crypto.subtle){var i;let r=new TextEncoder().encode(e);return(i=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",r))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(i):void 0!==globalThis.Buffer?globalThis.Buffer.from(i).toString("base64"):i).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let eu=(e,t)=>`${e}_${t}`;function ep(e=""){return(e||"").replace(/^.+:\/\//,"")}let ef=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,em=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let i=new URLSearchParams;return Object.keys(e).forEach(r=>{let n=t.keyEncoder?t.keyEncoder(r):r,s=e[r];if(Array.isArray(s))s.forEach(e=>void 0!==e&&i.append(n,e||""));else{if(void 0===s)return;"object"==typeof s&&null!==s?i.append(n,JSON.stringify(s)):i.append(n,String(s??""))}}),i.toString()},eg="http://clerk-dummy",e_=["javascript:"],{isDevOrStagingUrl:ew}=(r=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,i=r.get(t);return void 0===i&&(i=es.some(e=>t.endsWith(e)),r.set(t,i)),i}}),ey=new Map;function eb(e){return e.replace("clerk.","")}function ev(e,t={}){let{base:i,hashPath:r,hashSearch:n,searchParams:s,hashSearchParams:a,...o}=e,l=new URL(i||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(s instanceof URLSearchParams&&s.forEach((e,t)=>{null!=e&&l.searchParams.set(X(t),e)}),Object.assign(l,o),r||n||a){var c;let e,t=new URL(eg+l.hash.substring(1));for(let[i,s]of(c=t.pathname,t.pathname=[c,r||""].filter(e=>e).join("/").replace(ei,"/"),Object.entries((e={},new URLSearchParams(n||"").forEach((t,i)=>{if(i in e){let r=e[i];Array.isArray(r)?r.push(t):e[i]=[r,t]}else e[i]=t}),e))))t.searchParams.append(i,s);if(a)for(let e of Array.isArray(a)?a:[a])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,i)=>{null!=e&&t.searchParams.set(X(i),e)});let i=t.href.replace(eg,"");"/"!==i&&(l.hash=i)}let{stringify:d,skipOrigin:h}=t;return d?h?l.href.replace(l.origin,""):l.href:l}function ek(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let eS=e=>(e||"").replace(/\/+$/,"");function eI(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let eU=[/\0/,/^\/\//,/[\x00-\x1F]/],eA=["/oauth/authorize"],eC=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eP=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},i={},r){this.options=e,this.fromOptions=this.#e(e||{}),this.fromProps=this.#e(t||{}),this.fromSearchParams=this.#t(i||{}),this.mode=r}getAfterSignInUrl(){return this.#i("signIn")}getAfterSignUpUrl(){return this.#i("signUp")}getPreservedSearchParams(){return this.#r(this.#n())}toSearchParams(){return this.#r(this.#s())}#r(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[X(e),t]))).reduce((e,[t,i])=>(null!=i&&(e[t]=i),e),{}))}#n(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#s(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,i=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,r={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:i,redirectUrl:this.fromSearchParams.redirectUrl||this.fromProps.redirectUrl};return e&&delete r.signUpFallbackRedirectUrl,i&&delete r.signInFallbackRedirectUrl,r}#i(e){let t,i=`${e}ForceRedirectUrl`,r=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[i]||this.fromProps[i]||this.fromOptions[i],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[r]||this.fromProps[r]||this.fromOptions[r])||"modal"!==this.mode)?t||"/":window.location.href}#e(t){let i={};return e.keys.forEach(e=>{i[e]=t[e]}),H(this.#a(this.#o(G(i,Boolean))),e=>e.toString())}#t(t){let i={};return e.keys.forEach(e=>{t instanceof URLSearchParams?i[e]=t.get(X(e)):i[e]=t[X(e)]}),H(this.#a(this.#o(G(i,Boolean))),e=>e.toString())}#o(e){return H(e,e=>eI(e,window.location.origin))}#a=e=>{let t,i;return G(e,(t=this.options?.allowedRedirectOrigins,i=window.location.origin,e=>{let r=e;if("string"==typeof r&&(r=eI(r,i)),!t)return!0;let n=i===r.origin,s=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return e_.some(e=>e===t)}(e))return!0;for(let t of eU)if(t.test(e.pathname))return!0;return!1}(r)&&(n||t.map(e=>"string"==typeof e?(e=>{try{return K(e)}catch(t){throw Error(`Invalid pattern: ${e}.
13
13
  Consult the documentation of glob-to-regexp here: https://www.npmjs.com/package/glob-to-regexp.
14
- ${t.message}`)}})(ek(e)):e).some(e=>e.test(ek(r.origin))));return s||q(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),s}))}};let eP="__clerk_netlify_cache_bust",eT=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eP,W,j,$];function eO(e){return new URL(window.location.href).searchParams.get(e)||null}function eE(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function ex(e){let t=new URLSearchParams(window.location.search),i=e||new URLSearchParams;for(let e of eT){let r=t.get(e);r&&i.set(e,r)}return i}let eR={"choose-organization":"choose-organization","reset-password":"reset-password","setup-mfa":"setup-mfa"},eM=e=>`/tasks/${eR[e.key]}`;function ez(e,{navigate:t,baseUrl:i}){let r=e.currentTask;if(r){var n;let e;return t((n={base:i},e=ex(),eb({base:n.base,hashPath:eM(r),searchParams:e},{stringify:!0})))}}let eF=e=>`🔒 Clerk:
14
+ ${t.message}`)}})(eS(e)):e).some(e=>e.test(eS(r.origin))));return s||q(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),s}))}};let eT="__clerk_netlify_cache_bust",eO=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eT,W,j,$];function eE(e){return new URL(window.location.href).searchParams.get(e)||null}function ex(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function eR(e){let t=new URLSearchParams(window.location.search),i=e||new URLSearchParams;for(let e of eO){let r=t.get(e);r&&i.set(e,r)}return i}let eF={"choose-organization":"choose-organization","reset-password":"reset-password","setup-mfa":"setup-mfa"},eM=e=>`/tasks/${eF[e.key]}`;function ez(e,{navigate:t,baseUrl:i}){let r=e.currentTask;if(r){var n;let e;return t((n={base:i},e=eR(),ev({base:n.base,hashPath:eM(r),searchParams:e},{stringify:!0})))}}let eN=e=>`🔒 Clerk:
15
15
  ${e.trim()}
16
- (This notice only appears in development)`,eN={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>eF(`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=>eF(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eN)){let t=eN[e];"function"!=typeof t&&(eN[e]=eF(t))}let eW="clerk:beforeunload",eD=["http:","https:","wails:","chrome-extension:"];function eL(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eW)),window.location.href=t.href}function e$(e){return/^http(s)?:\/\//.test(e||"")}function ej(e){return e.startsWith("/")}var eB=class{#l;#c=864e5;constructor(e){this.#l=e}isEventThrottled(e){let t=Date.now(),i=this.#d(e),r=this.#l.getItem(i);return!!r&&!(t-r>this.#c)||(this.#l.setItem(i,t),!1)}#d(e){let{sk:t,pk:i,payload:r,...n}=e,s={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>s[e]))}},eJ=class{#h="clerk_telemetry_throttler";getItem(e){return this.#u()[e]}setItem(e,t){try{let i=this.#u();i[e]=t,localStorage.setItem(this.#h,JSON.stringify(i))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#h)}}removeItem(e){try{let t=this.#u();delete t[e],localStorage.setItem(this.#h,JSON.stringify(t))}catch{}}#u(){try{let e=localStorage.getItem(this.#h);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eK=class{#l=new Map;#p=1e4;getItem(e){return this.#l.size>this.#p?void this.#l.clear():this.#l.get(e)}setItem(e,t){this.#l.set(e,t)}removeItem(e){this.#l.delete(e)}};let eV=new Set(["error","warn","info","debug","trace"]);var eq=class{#f;#m;#g={};#_=[];#w=null;constructor(e){this.#f={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.#g.clerkVersion=e.clerkVersion??"":this.#g.clerkVersion="",this.#g.sdk=e.sdk,this.#g.sdkVersion=e.sdkVersion,this.#g.publishableKey=e.publishableKey??"";const t=ec(e.publishableKey);t&&(this.#g.instanceType=t.instanceType),e.secretKey&&(this.#g.secretKey=e.secretKey.substring(0,16)),this.#m=new eB(eJ.isSupported()?new eJ:new eK)}get isEnabled(){return!("development"!==this.#g.instanceType||this.#f.disabled||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#f.debug||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#y(e.event,e.payload);if(this.#b(t.event,t),!this.#v(t,e.eventSamplingRate))return;this.#_.push({kind:"event",value:t}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#S(e))return;let t="string"==typeof e?.level&&eV.has(e.level),i="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!i||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==r});return}let s=this.#I(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#g.publishableKey||null,payload:this.#U(e.context)};this.#_.push({kind:"log",value:a}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#v(e,t){return this.isEnabled&&!this.isDebug&&this.#A(e,t)}#S(e){return!0}#A(e,t){let i=Math.random();return!!(i<=this.#f.samplingRate&&(!1===this.#f.perEventSampling||void 0===t||i<=t))&&!this.#m.isEventThrottled(e)}#k(){if("undefined"==typeof window)return void this.#C();if(this.#_.length>=this.#f.maxBufferSize){this.#w&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#w)):clearTimeout(Number(this.#w))),this.#C();return}this.#w||("requestIdleCallback"in window?this.#w=requestIdleCallback(()=>{this.#C(),this.#w=null}):this.#w=setTimeout(()=>{this.#C(),this.#w=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#w=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),i=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),i.length>0&&fetch(new URL("/v1/logs",this.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:i})}).catch(()=>void 0)}#b(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#I(){let e={name:this.#g.sdk,version:this.#g.sdkVersion};if("undefined"!=typeof window){let t=window;if(t.Clerk){let i=t.Clerk;if("object"==typeof i&&null!==i&&"constructor"in i&&"function"==typeof i.constructor&&i.constructor.sdkMetadata){let{name:t,version:r}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#y(e,t){let i=this.#I();return{event:e,cv:this.#g.clerkVersion??"",it:this.#g.instanceType??"",sdk:i.name,sdkv:i.version,...this.#g.publishableKey?{pk:this.#g.publishableKey}:{},...this.#g.secretKey?{sk:this.#g.secretKey}:{},payload:t}}#U(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let eH="COMPONENT_MOUNTED",eG=new Set(["SignIn","SignUp"]);function eQ(e){return function(t,i,r){return{event:e,eventSamplingRate:e===eH?eG.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,theme:!!i?.appearance?.theme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...r}}}}function eX(e,t,i){return eQ(eH)(e,t,i)}function eY(e,t,i){return eQ("COMPONENT_OPENED")(e,t,i)}function eZ(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}var e0=s(2044);let e1=!1,e3=null,e2=!1,e4=[];function e6(e,t,i,r){e1&&(e4.push({level:e,message:t,context:i,source:r,ts:Date.now()}),e4.length>200&&e4.shift())}async function e5(e){try{if(!e1||e3)return;let{getDebugLogger:t}=await s.e("507").then(s.bind(s,9854)),i=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(i&&(e3=i)&&0!==e4.length){for(let e of e4){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e3.error(e.message,t,e.source);break;case"warn":e3.warn(e.message,t,e.source);break;case"info":e3.info(e.message,t,e.source);break;case"debug":e3.debug(e.message,t,e.source)}}e4.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e9={debug(e,t,i){e3?e3.debug(e,t,i):e6("debug",e,t,i)},error(e,t,i){e3?e3.error(e,t,i):e6("error",e,t,i)},info(e,t,i){e3?e3.info(e,t,i):e6("info",e,t,i)},warn(e,t,i){e3?e3.warn(e,t,i):e6("warn",e,t,i)}},e7={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},e8=async e=>new Promise(t=>setTimeout(t,e)),te=(e,t)=>t?e*(1+Math.random()):e,tt=async(e,t={})=>{var i;let r,n=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...e7,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await e8((e=te(e=i.initialDelay*Math.pow(i.factor,r),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!s(e,++n))throw e;h&&await h(n),c&&1===n?await e8(te(100,d)):await u()}},ti=async e=>tt(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tr{#P={"@zxcvbn-ts/core":()=>ti(()=>s.e("729").then(s.bind(s,7010))),"@zxcvbn-ts/language-common":()=>ti(()=>s.e("873").then(s.bind(s,655))),"@base-org/account":()=>ti(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,71))),"@coinbase/wallet-sdk":()=>ti(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,5537))),"@stripe/stripe-js":()=>ti(()=>s.e("279").then(s.bind(s,5608)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let tn=(e=!1)=>{let t,i;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,i=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",i),window.addEventListener(eW,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(eW,i)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ts=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),ta=e=>({proration:e.proration?{amount:ts(e.proration.amount),cycleDaysRemaining:e.proration.cycle_days_remaining,cycleDaysTotal:e.proration.cycle_days_total,cycleRemainingPercent:e.proration.cycle_remaining_percent}:null,payer:e.payer?{remainingBalance:ts(e.payer.remaining_balance),appliedAmount:ts(e.payer.applied_amount)}:null,total:ts(e.total)}),to=e=>{let t={grandTotal:ts(e.grand_total),subtotal:ts(e.subtotal),taxTotal:ts(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?ts(e.past_due):null),"credit"in e&&(t.credit=e.credit?ts(e.credit):null),"credits"in e&&(t.credits=e.credits?ta(e.credits):null),"total_due_now"in e&&(t.totalDueNow=ts(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?ts(e.total_due_after_free_trial):null),t};function tl(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let tc=C({packageName:"@clerk/clerk-js"});function td(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function th(e){let t=(e||"").split("."),[i,r,n]=t;if(3!==t.length||!i||!r||!n)throw Error("JWT could not be decoded");let s=JSON.parse(td(r)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:r,signature:n},header:JSON.parse(td(i)),claims:a}}function tu(){if(!n())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tp(){return void 0!==globalThis.document}function tf(){if(!function(){if(!tp())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var tm=class e{#T=[];#O={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #E=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#x),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=e=>{let t=this.#T.find(t=>t.info.name===this.#O[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#T.some(t=>t.info.uuid===e.detail.info.uuid)||this.#T.push(e.detail)}},tg=class e{#R=void 0;#M=!1;static #E=null;constructor(){}async #z(){if(this.#M)return;this.#M=!0;let e=await s.e("836").then(s.bind(s,5527)).then(e=>e.getWallets());this.#R=e.get(),e.on("register",()=>{this.#R=e.get()}),e.on("unregister",()=>{this.#R=e.get()})}#F(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#N(e){return"solana:signMessage"in e.features}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=async e=>{await this.#z();let t=(this.#R||[]).find(t=>t.name===e&&this.#F(t)&&this.#N(t));if(t&&this.#F(t))return t;if("undefined"==typeof window)return;let i=window.solana;if(i&&"function"==typeof i.connect&&"function"==typeof i.signMessage)return i}};let t_=()=>(function(e){let t=C({packageName:"@clerk/shared"});async function i(e){let{provider:t,walletName:i}=e,r=await f(t,i);if(!r)return"";if("solana"===t){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let n=await r.request({method:"eth_requestAccounts"});return n&&n[0]||""}let r=async e=>{let{identifier:t,nonce:i,provider:r,walletName:n=""}=e,s=await f(r,n);if(!s)return"";if("solana"===r)try{let e=s.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let r=await s.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(i)});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 y("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new y("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await s.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function n(){return await i({provider:"metamask"})}async function s(){return await i({provider:"coinbase_wallet"})}async function a(){return await i({provider:"okx_wallet"})}async function o(){return await i({provider:"base"})}async function l(e){return await i({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 h(e){return await r({...e,provider:"okx_wallet"})}async function u(e){return await r({...e,provider:"base"})}async function p(e){return await r({...e,provider:"solana"})}async function f(i,r){if("coinbase_wallet"===i){let t=await e.import("@coinbase/wallet-sdk");return t?t.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"===i)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===i?r&&0!==r.length?await tg.getInstance().get(r):void t.throw("Wallet name must be provided to get Solana wallet provider"):tm.getInstance().get(i)}return{getWeb3Identifier:i,generateWeb3Signature:r,getMetamaskIdentifier:n,getCoinbaseWalletIdentifier:s,getOKXWalletIdentifier:a,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:h,generateSignatureWithBase:u,generateSignatureWithSolana:p}})(new tr),tw="environment",ty=JSON.stringify,tb=JSON.parse;class tv{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let r={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),ty(r))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let r=tb(i);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let tk="ClerkJS:";function tS(e=""){throw Error(`${tk} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tI(e){throw Error(`${tk} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tU(e){throw Error(`${tk} You need to start a ${e} flow by calling ${e}.create() first.`)}function tA(e,t){throw Error(`${tk} Strategy "${t}" is not a valid strategy for ${e}.`)}function tC(e){throw Error(`${tk} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tP(e=""){throw Error(`${tk} Missing '${e}' option`)}function tT(e,t){throw Error(`${tk} Response: ${e||0} not supported yet.
17
- For more information contact us at ${t}`)}function tO(e){throw Error(`${tk} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tE(e="",t){let{async:i,defer:r,beforeLoad:n,crossOrigin:s,nonce:a}=t||{};return tt(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");s&&l.setAttribute("crossorigin",s),l.async=i||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=a,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tx(e){return window.turnstile||await tR(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tR(e){try{return await tE("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function tM(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tz=async e=>{let t,i,r,n,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:d,closeModal:h,openModal:u}=e,p=await tx(l),f=[],m="",g="",_=s,w=0,y=null,b="invisible";if(c&&d){y=a,n=c,b="modal";try{await u?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:s,size:a}=tM(e);t=n,r=s,i=a}}if(!n&&"smart"===a){let e=document.getElementById(B);if(e){b="smart",y="smart",n=`#${B}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tM(e);t=s,r=a,i=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){b="invisible",_=o,y="invisible",n=`.${J}`;let e=document.createElement("div");e.classList.add(J),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(n,{sitekey:_,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){h?.(),s([e,o])},"before-interactive-callback":()=>{if(d){let e=document.querySelector(d);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(B);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===i?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(f.push(e),w<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{n&&!document.querySelector(n)?a([f.join(","),o]):(p.reset(o),w++)},250):a([f.join(","),o])},"unsupported-callback":function(){return a(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){a([e,void 0])}});try{[m,g]=await v(),p.remove(g)}catch([e,t]){throw t&&p.remove(t),{captchaError:e}}finally{if("modal"===b&&h?.(),"invisible"===b){let e=document.querySelector(`.${J}`);e&&document.body.removeChild(e)}if("smart"===b){let e=document.getElementById(B);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:m,captchaWidgetType:y}},tF=e=>{let t=e.__internal_environment,i=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:i,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class tN{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:r,nonce:n}=tF(this.clerk);return i&&t&&r?{...await tz({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||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:t,canUseCaptcha:i,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:s,nonce:a}=tF(this.clerk);if(i&&t&&s){let i=await tz({captchaProvider:n,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...i,captchaAction:"verify"}:i}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){if("undefined"==typeof document)throw new y("Captcha is not supported in non-browser environments",{code:"captcha_unavailable"});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 tW{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tW.instance||(tW.instance=new tW(iX,tN)),tW.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new y("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 t()}catch(r){let i;if(!S(r)||b(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>i=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{i(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tD{static clerk;id;pathRoot="";static get fapiClient(){return tD.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tW.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;tD.fapiClient||function(){throw Error(`${tk} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{i=await tD.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new y(t?.message||t,{code:"network_error"});if(!c())return e9.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:s,statusText:a,headers:o}=i;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&!t.skipUpdateClient&&this._updateClient(n),s>=200&&s<=299)return n;if(s>=400){let e=n?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"dev_browser_unauthenticated"===i?await tD.clerk.__internal_handleUnauthenticatedDevBrowser():401===s&&"requires_captcha"!==i&&await tD.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((i=tD.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=tD.clerk.frontendApi.replace("clerk.","");throw new k(`Clerk: Production Keys are only allowed for domain "${i}".
18
- API Error: ${n}`,{data:t,status:e})}}(s,e);let r={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new k(t||a,r)}return null}static _updateClient(e){let t=iQ(e);t&&tD.clerk&&tD.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let i=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?i.replace(/[^/]$/,"$&/")+encodeURIComponent(e):i}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await tD._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:r,path:n}=e,s=await tD._fetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await tD._baseFetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}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=tD.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tL(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class t$ extends tD{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?tL(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tL(e.last_used_at):null,this.updatedAt=tL(e.updated_at),this.createdAt=tL(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 tj extends tD{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?tL(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}}}(g=_||(_={}))[g.None=0]="None",g[g.Mutable=1]="Mutable",g[g.Watching=2]="Watching",g[g.RecursedCheck=4]="RecursedCheck",g[g.Recursed=8]="Recursed",g[g.Dirty=16]="Dirty",g[g.Pending=32]="Pending";let tB=[],{link:tJ,unlink:tK,propagate:tV,checkDirty:tq,endTracking:tH,startTracking:tG,shallowPropagate:tQ}=function({update:e,notify:t,unwatched:i}){let r=0;return{link:function(e,t){let i,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==n?n.nextDep:t.deps)&&i.dep===e){i.version=r,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===r&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==n?n.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:n,propagate:function(e){let i,r=e.nextSub;e:for(;;){let n=e.sub,s=n.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let r=t.deps;do{if(r===e)return!0;if(r===i)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|s,s&=1):s=0:n.flags=-9&s|32:s=0:n.flags=32|s,2&s&&t(n),1&s)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:r,prev:i},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(t,i){let r,n=0;e:for(;;){let a=t.dep,o=a.flags,l=!1;if(16&i.flags)l=!0;else if((17&o)==17){if(e(a)){let e=a.subs;void 0!==e.nextSub&&s(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=a.deps,i=a,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=r.value,r=r.prev):t=a,l){if(e(i)){o&&s(a),i=t.sub;continue}}else i.flags&=-33;if(i=t.sub,void 0!==t.nextDep){t=t.nextDep;continue e}l=!1}return l}},endTracking:function(e){let t=e.depsTail,i=void 0!==t?t.nextDep:e.deps;for(;void 0!==i;)i=n(i,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function n(e,t=e.sub){let r=e.dep,s=e.prevDep,a=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==a?a.prevDep=s:t.depsTail=s,void 0!==s?s.nextDep=a:t.deps=a,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&i(r),a}function s(e){do{let i=e.sub,r=e.nextSub,n=i.flags;(48&n)==32&&(i.flags=16|n,2&n&&t(i)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?t4(e):t6(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let r=t.subs;void 0!==r?e(r.sub):tB[tZ++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tK(t,e);while(void 0!==t)}}else"previousValue"in e||t8.call(e)}}),tX=0,tY=0,tZ=0;function t0(t){let i=e;return e=t,i}function t1(e){return t7.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t3(e){return t9.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t2(i){let r={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tJ(r,e):void 0!==t&&tJ(r,t);let n=t0(r);try{r.fn()}finally{t0(n)}return t8.bind(r)}function t4(e){let t=t0(e);tG(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t0(t),tH(e)}}function t6(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t5(){for(;tY<tZ;){let e=tB[tY];tB[tY++]=void 0,function e(t,i){if(16&i||32&i&&tq(t.deps,t)){let e=t0(t);tG(t);try{t.fn()}finally{t0(e),tH(t)}return}32&i&&(t.flags=-33&i);let r=t.deps;for(;void 0!==r;){let t=r.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),r=r.nextDep}}(e,e.flags&=-65)}tY=0,tZ=0}function t9(){let i=this.flags;if(16&i||32&i&&tq(this.deps,this)){if(t4(this)){let e=this.subs;void 0!==e&&tQ(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?tJ(this,e):void 0!==t&&tJ(this,t),this.value}function t7(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tV(e),tX||t5())}}else{let t=this.value;if(16&this.flags&&t6(this,t)){let e=this.subs;void 0!==e&&tQ(e)}return void 0!==e&&tJ(this,e),t}}function t8(){let e=this.deps;for(;void 0!==e;)e=tK(e,this);let t=this.subs;void 0!==t&&tK(t),this.flags=0}function ie(e){let{pageSize:t,initialPage:i,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:n+"",offset:((i??1)-1)*n+""})}class it{static #W="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${it.#W}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},r={...i,payer_type:"organization"===t?"org":"user"};return await tD._fetch({path:`${it.#W}/plans`,method:"GET",search:ie(r)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new iC(e))}})};getPlan=async e=>new iC(await tD._fetch({path:`${it.#W}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tD._fetch({path:it.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new iO(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await tD._fetch({path:it.path("/statements",{orgId:t}),method:"GET",search:ie(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new iP(e))}})};getStatement=async e=>new iP((await tD._fetch({path:it.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await tD._fetch({path:it.path("/payment_attempts",{orgId:t}),method:"GET",search:ie(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ib(e))}})};getPaymentAttempt=async e=>new ib(await tD._fetch({path:it.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new iw((await tD._fetch({path:it.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let ii=t1({resource:null}),ir=t1({error:null}),is=t1({status:"idle"}),ia=t3(()=>{let e=ii().resource,t=ir().error,i=is().status;return{errors:ig(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),io=t1({resource:null}),il=t1({error:null}),ic=t1({status:"idle"}),id=t3(()=>{let e=io().resource,t=il().error,i=ic().status;return{errors:ig(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:i,signUp:e?e.__internal_future:null}}),ih=t1({resource:null}),iu=t1({error:null}),ip=t1({status:"idle"}),im=t3(()=>{let e=ih().resource,t=iu().error,i=ip().status;return{errors:ig(t,{emailAddress:null}),fetchStatus:i,waitlist:e}});function ig(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!S(e))return i.raw=[e],i.global=[R(e)],i;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(i.raw?i.raw.push(e):i.raw=[e],r(e)){let t=Q(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[R(e)]),i}class i_ extends tD{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=tL(e.created_at)),e.updated_at&&(this.updatedAt=tL(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 iw extends tD{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 iU(e.payment_method):void 0,this.plan=new iC(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=to(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tL(e.free_trial_ends_at)),this.payer=new i_(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tt(()=>this._basePatch({path:it.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!S(e)||t>=4)return!1;let i=e?.status,r=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||r}})}class iy{resource=new iw(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,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 iw.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new iw(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:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await iw.clerk.setActive({session:iw.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var r,n,s;return void 0===iw.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tX,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),i?.(),--tX||t5(),++tX;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{s.delete(e),n.fetchSignal({status:"idle"}),--tX||t5()}})();return s.set(e,a),a})(e,t,i)}}class ib extends tD{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=ts(e.amount),this.paidAt=e.paid_at?tL(e.paid_at):null,this.failedAt=e.failed_at?tL(e.failed_at):null,this.updatedAt=tL(e.updated_at),this.paymentMethod=e.payment_method?new iU(e.payment_method):null,this.subscriptionItem=new iE(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let iv="/payment_methods",ik=async e=>{let{orgId:t,...i}=e;return new iA((await tD._fetch({path:it.path(`${iv}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},iS=async e=>{let{orgId:t,...i}=e;return new iU((await tD._fetch({path:it.path(iv,{orgId:t}),method:"POST",body:i}))?.response)},iI=async e=>{let{orgId:t,...i}=e??{};return await tD._fetch({path:it.path(iv,{orgId:t}),method:"GET",search:ie(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new iU(e))}})};class iU extends tD{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:tL(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tL(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new iZ((await tD._fetch({path:it.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tD._fetch({path:it.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class iA extends tD{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 iC extends tD{id;name;fee=null;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=e.fee?ts(e.fee):null,this.annualFee=e.annual_fee?ts(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ts(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 rp(e))),this}}class iP extends tD{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=tL(e.timestamp),this.totals=to(e.totals),this.groups=e.groups.map(e=>new iT(e))),this}}class iT{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tL(e.timestamp),this.items=e.items.map(e=>new ib(e))),this}}class iO extends tD{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=tL(e.created_at),this.updatedAt=e.updated_at?tL(e.updated_at):null,this.activeAt=tL(e.active_at),this.pastDueAt=e.past_due_at?tL(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ts(e.next_payment.amount),date:tL(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new iE(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class iE extends tD{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;credits;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new iC(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tL(e.created_at),this.pastDueAt=e.past_due_at?tL(e.past_due_at):null,this.periodStart=tL(e.period_start),this.periodEnd=e.period_end?tL(e.period_end):null,this.canceledAt=e.canceled_at?tL(e.canceled_at):null,this.amount=e.amount?ts(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ts(e.credit.amount)}:void 0,this.credits=e.credits?ta(e.credits):void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new iZ((await tD._fetch({path:it.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let ix="token:update",iR="user:signOut",iM="environment:update",iz="session:tokenResolved",iF=p(),iN={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=iN.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:r}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let r=e.slice(t.length+1);return i&&r.endsWith(`-${i}`)&&(r=r.slice(0,-(i.length+1))),r||void 0}};var iW=s(2105),iD='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 iL=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(i);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},i$=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=iL(iD,{name:"clerk-timers"});if(s?.addEventListener("message",n),!s)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:iW.t};let a=()=>{s||(s=iL(iD,{name:"clerk-timers"}),s?.addEventListener("message",n))};return{setTimeout:(e,n)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),r(s,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{a();let o=t();return i.set(o,e),r(s,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{a(),i.delete(e),r(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),r(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};var ij=s(5945),iB=s.n(ij);class iJ{lock=(function(e){let t=new(iB());return{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=i$();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}let iK="clerk",iV={broadcast:!0},iq={broadcast:!1};class iH{prefix;data;static fromKey(e){let[t,i,r=""]=e.split("::");return new iH(t,{audience:r,tokenId:i})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let iG=((e=iK)=>{let t=new Map,i=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{a(e)}),r));n();let s=i=>{n();let r=new iH(e,i),s=t.get(r.toKey());if(!s)return;let a=Math.floor(Date.now()/1e3)-s.createdAt;if((s.expiresIn??1/0)-a<=5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),void 0!==s.refreshTimeoutId&&clearTimeout(s.refreshTimeoutId),t.delete(r.toKey());return}return{entry:s.entry}},a=async({data:e})=>{let t,r=iN.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void e9.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:i,template:e.template,traceId:e.traceId},"tokenCache");try{t=new r2({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){e9.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,a=t.jwt?.claims?.exp;if(!n||!a)return void e9.warn("Token missing iat/exp claim, skipping cache update",{tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=s({tokenId:e.tokenId});if(t){let r=await t.entry.tokenResolver,s=r.jwt?.claims?.iat;if(s&&s>=n)return void e9.debug("Ignoring older token broadcast",{existingIat:s,incomingIat:n,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){e9.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e9.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:i,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},iq)},o=(n,s=iV)=>{let a=new iH(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId),t.delete(a))};n.tokenResolver.then(e=>{n.resolvedToken=e;let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let a=t.exp,o=t.iat,d=a-o;l.createdAt=o,l.expiresIn=d;let h=setTimeout(c,1e3*d);l.timeoutId=h,"function"==typeof h.unref&&h.unref();let u=d-15-2;if(u>0&&n.onRefresh){let e=setTimeout(()=>{n.onRefresh?.()},1e3*u);l.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let p=r;if(p&&s.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=iN.extractTemplate(n.tokenId,e,s),o=iN.build(e,a,s);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e9.info("Broadcasting token update to other tabs",{organizationId:s,sessionId:e,tabId:i,template:a,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:n.tokenId,tokenRaw:r,traceId:t};p.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:s,set:e=>{n(),o(e,iV)},size:()=>t.size}})();function iQ(e){if(!e)return;let t=e.client||e.meta?.client;return t?iX.getOrCreateInstance().fromJSON(t):void 0}class iX extends tD{static instance;pathRoot="/client";sessions=[];signUp=new rX;signIn=new rH;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iX.instance||(iX.instance=new iX(e)),iX.instance}static clearInstance(){iX.instance=null}static isClientResource(e){return!!e&&e instanceof iX}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(()=>{iG.clear(),this.id="",this.sessions=[],this.signUp=new rX(null),this.signIn=new rH(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=>(iG.clear(),e))}resetSignIn(){this.signIn=new rH(null),iF.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new rX(null),iF.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tD.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 rD(e)),e.sign_up&&this.signUp instanceof rX&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new rX(e.sign_up),e.sign_in&&this.signIn instanceof rH&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new rH(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tL(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tL(e.created_at||void 0),this.updatedAt=tL(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 iY extends tD{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 iZ{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 i0 extends tD{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}}}function i1({delayInMs:e}={delayInMs:1e3}){let t,i=i$(),r=!1,n=()=>{t&&(i.clearTimeout(t),i.cleanup()),r=!0},s=async a=>{r=!1,await a(n),r||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:n}}class i3 extends tD{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,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:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=i1();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=i1();return{startEnterpriseSSOLinkFlow:async({redirectUrl:i})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:i})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rr(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rf(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 i2=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function i4(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new T("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new T(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new T(t.message,{code:"passkey_registration_cancelled"}):i9(t),publicKeyCredential:null}}}let i6=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 i5({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:i6.createAbortSignal()});if(!i)return{error:new T("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:i,error:null}}catch(e){var i;return{error:"NotAllowedError"===(i=e).name?new T(i.message,{code:"passkey_retrieval_cancelled"}):i9(i),publicKeyCredential:null}}}function i9(e){return"AbortError"===e.name?new T(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new T(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function i7(e){let t=ri(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:ri(e.id)}));return{...e,allowCredentials:i,challenge:t}}function i8(e){return{type:e.type,id:e.id,rawId:rt(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function re(e){let t=e.response;return{...i8(e),response:{clientDataJSON:rt(t.clientDataJSON),authenticatorData:rt(t.authenticatorData),signature:rt(t.signature),userHandle:t.userHandle?rt(t.userHandle):null}}}let rt=i2.encode.bind(i2),ri=i2.decode.bind(i2);class rr extends tD{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===tD.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=tL(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class rn extends rr{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=ri((t=JSON.parse(e.nonce)).user.id),r=ri(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:ri(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class rs{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new ra(e.email_address),this.phoneNumber=new ra(e.phone_number),this.web3Wallet=new ra(e.web3_wallet),this.externalAccount=new rr(e.external_account)):(this.emailAddress=new ra(null),this.phoneNumber=new ra(null),this.web3Wallet=new ra(null),this.externalAccount=new rr(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 ra extends rr{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 ro extends tD{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,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?tL(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rr(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new rl(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 rl extends tD{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=tL(e.created_at),this.updatedAt=tL(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()}}}class rc extends tD{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 rd extends tD{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!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)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),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 rh extends tD{static instance;authConfig=new tj;displayConfig=new i0;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new nt;organizationSettings=new rd;commerceSettings=new iY;apiKeysSettings=new rc;protectConfig=new rT;static getInstance(){return rh.instance||(rh.instance=new rh),rh.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tj(e.auth_config),this.displayConfig=new i0(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new rd(e.organization_settings),this.userSettings=new nt(e.user_settings),this.commerceSettings=new iY(e.commerce_settings),this.apiKeysSettings=new rc(e.api_keys_settings),this.protectConfig=new rT(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(iF.emit(iM,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,partitioned_cookies:this.partitionedCookies,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 ru extends tD{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:i}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i}})};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 rr(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 rp extends tD{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 rf extends tD{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 rm extends tD{id;name=null;publicUrl=null;static async create(e,t={}){let i,r=t;return"string"==typeof t.file?(r=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new rm((await tD._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new rm((await tD._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 rg extends tD{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rg((await tD._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.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:tL(e.verification.expires_at)}:this.verification=null),this}}class r_ extends tD{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=tL(e.created_at),this.updatedAt=tL(e.updated_at),e.public_user_data&&(this.publicUserData=new rO(e.public_user_data))),this}}class rw extends tD{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=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class ry extends tD{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 rw(e)),this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class rb extends tD{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 rb((await tD._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rb((await tD._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tD._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:ie(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new ry(e)),total_count:i,has_role_set_migration:r}});getDomains=async e=>await tD._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:ie(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rg(e))}});getDomain=async({domainId:e})=>new rg((await tD._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tD._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:ie(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new r_(e))}});createDomain=async e=>rg.create(this.id,{name:e});getMemberships=async e=>await tD._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:ie({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rk(e))}});getInvitations=async e=>await tD._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:ie(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rv(e))}});addMember=async({userId:e,role:t})=>await tD._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new rk(e?.response));inviteMember=async e=>rv.create(this.id,e);inviteMembers=async e=>rv.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tD._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new rk(e?.response));removeMember=async e=>await tD._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rk(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await tD._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rb(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tD._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new rb(e?.response)))};initializePaymentMethod=e=>ik({...e,orgId:this.id});addPaymentMethod=e=>iS({...e,orgId:this.id});getPaymentMethods=e=>iI({...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=tL(e.created_at),this.updatedAt=tL(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:t}=e||{},i=(await tD._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class rv extends tD{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new rv((await tD._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:r}=t;return((await tD._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new rv(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=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}class rk extends tD{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tD._fetch({path:"/me/organization_memberships",method:"GET",search:ie({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rk(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 rb(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rO(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tL(e.created_at),this.updatedAt=tL(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(`${tk} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rS extends tD{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tD._fetch({path:"/me/organization_suggestions",method:"GET",search:ie(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rS(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=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}function rI(){return o()&&"function"==typeof window.PublicKeyCredential}async function rU(){try{return rI()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rA(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rC extends tD{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tD._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rC(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...i8(t),response:{clientDataJSON:rt(i.clientDataJSON),attestationObject:rt(i.attestationObject),transports:i.getTransports()}});return tD._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rC(e?.response))}static async registerPasskey(){let e=rC.clerk.__internal_isWebAuthnSupported||rI,t=rC.clerk.__internal_createPublicCredentials||i4,i=rC.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rA;if(!e())throw new T("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,s=n?.publicKey;if(s||tO("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new T("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:a,error:o}=await t(s);if(!a)throw o;return this.attemptVerification(r.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new iZ((await tD._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?tL(e.last_used_at):null,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),e.verification&&(this.verification=new rn(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 rP extends tD{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,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:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};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 rr(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rf(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 rT extends tD{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 rO{firstName;lastName;imageUrl;hasImage;identifier;userId;username;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.username=e.username),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,username:this.username}}}let rE={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"}},rx=new Set(["first_factor","second_factor","multi_factor"]),rR=new Set(["strict_mfa","strict","moderate","lax"]),rM=new Set(["o","org","organization"]),rz=new Set(["u","user"]),rF=(e,t)=>{let{org:i,user:r}=rN(e),[n,s]=t.split(":"),a=void 0!==s,o=s||n;if(a&&!rM.has(n)&&!rz.has(n))throw Error(`Invalid scope: ${n}`);if(a){if(rM.has(n))return i.includes(o);if(rz.has(n))return r.includes(o)}return[...i,...r].includes(o)},rN=e=>{let t=[],i=[];if(!e)return{org:t,user:i};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),s=n.indexOf(":");if(-1===s)throw Error(`Invalid claim element (missing colon): ${n}`);let a=n.slice(0,s),o=n.slice(s+1);"o"===a?t.push(o):"u"===a?i.push(o):("ou"===a||"uo"===a)&&(t.push(o),i.push(o))}return{org:t,user:i}};class rW extends tD{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rr(null);secondFactorVerification=new rr(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rD(e.session),this.level=e.level,this.supportedFirstFactors=ee(e.supported_first_factors),this.supportedSecondFactors=ee(e.supported_second_factors),this.firstFactorVerification=new rr(e.first_factor_verification),this.secondFactorVerification=new rr(e.second_factor_verification)),this}}class rD extends tD{pathRoot="/client/sessions";static #D=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rD}constructor(e){super(),this.fromJSON(e),this.#L(this.lastActiveToken)}end=()=>(iG.clear(),this._basePost({action:"end"}));remove=()=>(iG.clear(),this._basePost({action:"remove"}));_touchPost=async({skipUpdateClient:e}={skipUpdateClient:!1})=>{let t=await tD._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId}},{skipUpdateClient:e});return this.fromJSON(t?.response||t),t};touch=async()=>(await this._touchPost(),this.lastActiveToken&&iF.emit(ix,{token:this.lastActiveToken}),this);__internal_touch=async()=>iQ(await this._touchPost({skipUpdateClient:!0}));clearCache=()=>iG.clear();getToken=async e=>{try{let t=await tt(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!E(e)||e?.status===429)&&(c()?t<=8:t<=3)});if(!t&&!c())throw new U("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!c())throw new U("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,i=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:i?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let i=((e,t)=>{let{features:i,plans:r}=t;return e.feature&&i?rF(i,e.feature):e.plan&&r?rF(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&i&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&rR.has(e),n="object"==typeof e&&(t=e.level,rx.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?rE[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:r,afterMinutes:n}=i(),[s,a]=t,o=-1!==s?n>s:null,l=-1!==a?n>a:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==a?l:o;case"multi_factor":return -1===a?o:o&&l}})(e,t);return[i||r,n].some(e=>null===e)?[i||r,n].some(e=>!0===e):[i||r,n].every(e=>!0===e)})(e)};#L=e=>{if(e){let t=this.#$();iG.set({tokenId:t,tokenResolver:Promise.resolve(e),onRefresh:()=>this.#j(void 0,this.lastActiveOrganizationId,t,!0)})}};#$(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return iN.build(this.id,e,i)}startVerification=async({level:e})=>new rW((await tD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tA("Session.prepareFirstFactorVerification",e.strategy)}return new rW((await tD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(re(e.publicKeyCredential))}:{...e},new rW((await tD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rD.clerk.__internal_isWebAuthnSupported||rI,i=rD.clerk.__internal_getPublicCredentials||i5;if(!t())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?i7(JSON.parse(e)):null;r||tO("get");let{publicKeyCredential:n,error:s}=await i({publicKeyOptions:r,conditionalUI:!1});if(!n)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rW((await tD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rW((await tD._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=tL(e.expire_at),this.abandonAt=tL(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tL(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tL(e.created_at),this.updatedAt=tL(e.updated_at),this.user=new r9(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rO(e.public_user_data)),this.lastActiveToken=e.last_active_token?new r2(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){let t;if(!this.user)return null;let{skipCache:i=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,s=this.#$(r,n),a=i?void 0:iG.get({tokenId:s}),o=!r&&n===this.lastActiveOrganizationId;if(a){let e=a.entry.resolvedToken??await a.entry.tokenResolver;o&&e.getRawString()&&iF.emit(ix,{token:e}),t=e.getRawString()||null}else if(l())t=await this.#B(r,n,s,o,i);else throw new y("Browser is offline, skipping token fetch",{code:"network_error"});if(null===t&&!c())throw new y("Network request failed while offline",{code:"network_error"});return t}#J(e,t,i){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=e?{}:{organizationId:t??null},s=this.lastActiveToken?.getRawString();return r2.create(r,n,i?{debug:"skip_cache"}:void 0).catch(e=>{if(I.is(e)&&s)return r2.create(r,{...n},{expired_token:s});throw e})}#K(e,t){!t||e.getRawString()&&(iF.emit(ix,{token:e}),e.jwt&&(this.lastActiveToken=e,iF.emit(iz,null)))}#B(e,t,i,r,n){e9.info("Fetching new token from API",{organizationId:t,template:e,tokenId:i},"session");let s=this.#J(e,t,n);return iG.set({tokenId:i,tokenResolver:s,onRefresh:()=>this.#j(e,t,i,r)}),s.then(e=>{let t=e.getRawString();if(!t)throw new y("Token fetch returned empty response",{code:"network_error"});return this.#K(e,r),t})}#j(e,t,i,r){rD.#D.has(i)||(rD.#D.add(i),this.#J(e,t,!1).then(n=>{n.getRawString()&&(iG.set({tokenId:i,tokenResolver:Promise.resolve(n),onRefresh:()=>this.#j(e,t,i,r)}),this.#K(n,r))}).catch(e=>{e9.warn("Background token refresh failed",{error:e,tokenId:i},"session")}).finally(()=>{rD.#D.delete(i)}))}get currentTask(){let[e]=this.tasks??[];return e}}class rL extends tD{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tD.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rL(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tL(e.expire_at),this.abandonAt=tL(e.abandon_at),this.lastActiveAt=tL(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}s(4821);let r$=(e,t,i)=>{let{onValidation:r=iW.t,onValidationComplexity:n=iW.t}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let i=e.allowed_special_characters.replace("[","\\[");i=i.replace("]","\\]"),t=RegExp(`[${i}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:i,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=i,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,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,t),l=(({min_zxcvbn_strength:e,onResult:t})=>i=>r=>{let n=i(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,i)=>{let{onValidation:d=r,onValidationComplexity:h=n}=i||{};if(!a)return;let u=o(t);h(0===Object.keys(u).length),c={...c,complexity:u},s&&e().then(e=>{let i=l(e)(t);d({...c={...c,strength:i},strength:i})}),c.complexity&&0===Object.keys(c.complexity).length&&s||d(c)}};function rj(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rB(e,t,i,r,n){if(!e.client||!r.popup)return;let s=rj(e.frontendApi),{redirectUrl:a}=r,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${s}/popup-callback`),d=e.buildUrlWithAuth(`${s}/popup-callback?return_url=${encodeURIComponent(l)}`),h=async t=>{if(t.origin!==s)return;let i=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),i=!0}else t.data.return_url&&(e.navigate(t.data.return_url),i=!0);i&&window.removeEventListener("message",h)};window.addEventListener("message",h),await i({...r,redirectUrlComplete:c,redirectUrl:d},n)}function rJ(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=rj(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",i),n.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(n.toString()),a=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function rK(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rj(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),i()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rV(e,t){iF.emit("resource:error",{resource:e,error:null}),iF.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return iF.emit("resource:error",{resource:e,error:t}),{error:t}}finally{iF.emit("resource:fetch",{resource:e,status:"idle"})}}let rq=()=>{var e;return(e=new tr,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:i,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...n},graphs:s}),r})}).loadZxcvbn};class rH extends tD{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new rr(null);secondFactorVerification=new rr(null);identifier=null;createdSessionId=null;userData=new r7(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e9.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rG(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e9.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},i=tu();if(i&&(t.locale=i),this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tN(rH.clerk),i=await e.managedOrInvisible({action:"signin"});if(!i)throw new y("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(e9.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={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":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tA("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return e9.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(re(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=i1();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||tU("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e[a].status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(e9.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e9.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=rH.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tT(c,rH.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tP("popup"),rB(rH.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:r,strategy:n="web3_metamask_signature",walletName:s}=e||{},a=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tP("generateSignature"),"solana"!==a||s||tP("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||tC("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tC("SignIn");try{t=await r({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await r({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await t_().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:t_().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await t_().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:t_().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await t_().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:t_().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await t_().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:t_().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await t_().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>t_().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=rH.clerk.__internal_isWebAuthnSupported||rI,r=rH.clerk.__internal_getPublicCredentials||i5,n=rH.clerk.__internal_isWebAuthnAutofillSupported||rU;if(!i())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tk} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:s}=this.firstFactorVerification,a=s?i7(JSON.parse(s)):null;a||tO("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rH.clerk.__internal_environment?.userSettings.passwordSettings)return r$(rq(),{...rH.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ee(e.supported_first_factors),this.supportedSecondFactors=ee(e.supported_second_factors),this.firstFactorVerification=new rr(e.first_factor_verification),this.secondFactorVerification=new rr(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new r7(e.user_data),this.clientTrustState=e.client_trust_state??void 0),iF.emit("resource:update",{resource:this}),this}clientBypass(){return rH.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=rH.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&rH.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=rH.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:Z(this.supportedFirstFactors),supported_second_factors:Z(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 rG{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(!n())return null;const e=eO("__clerk_status"),t=eO("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==rH.clerk.client&&rH.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.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),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#V=!1;#q;constructor(e){this.#q=e}get id(){return this.#q.id}get identifier(){return this.#q.identifier}get createdSessionId(){return this.#q.createdSessionId}get userData(){return this.#q.userData}get status(){return this.#q.status||"needs_identifier"}get supportedFirstFactors(){return this.#q.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#q.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#q.firstFactorVerification.status}get existingSession(){if("failed"===this.#q.firstFactorVerification.status&&this.#q.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#q.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#q.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#q.firstFactorVerification}get secondFactorVerification(){return this.#q.secondFactorVerification}get canBeDiscarded(){return this.#V}async sendResetPasswordEmailCode(){if(!this.#q.id)throw Error("Cannot reset password without a sign in.");return rV(this.#q,async()=>{let e=this.#q.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new y("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#q.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#q.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return rV(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.#q.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new y("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:i}=e;await this.#q.__internal_basePost({body:{phoneNumberId:i,strategy:"reset_password_phone_code"},action:"prepare_first_factor"})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=rH.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&rH.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=rH.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||rH.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new tN(rH.clerk),i=await t.managedOrInvisible({action:"signin"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n={...e,captchaToken:t,captchaWidgetType:i,captchaError:r,locale:tu()||void 0};await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})}async create(e){return rV(this.#q,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 rV(this.#q,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#q.identifier,r=tu();await this.#q.__internal_basePost({path:this.#q.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#q.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rV(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new y("Email code factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:r}=e;if(!this.#q.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rV(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new y("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.#q.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rV(this.#q,async()=>{let{run:e,stop:t}=i1();await new Promise((i,r)=>{e(async()=>{try{let e=await this.#q.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.#q.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rV(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new y("Phone code factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,popup:n,oidcPrompt:s,enterpriseConnectionId:a,identifier:o}=e;return rV(this.#q,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:rH.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rJ(rH.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#q.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#q.firstFactorVerification;"unverified"===c&&d&&(n?(await rK(rH.clerk,{popup:n,externalVerificationRedirectURL:d}),await this.#q.reload()):eL(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return rV(this.#q,async()=>{let r,n,s;switch(i){case"metamask":r=await t_().getMetamaskIdentifier(),n=t_().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await t_().getCoinbaseWalletIdentifier(),n=t_().generateSignatureWithCoinbaseWallet;break;case"base":r=await t_().getBaseIdentifier(),n=t_().generateSignatureWithBase;break;case"okx_wallet":r=await t_().getOKXWalletIdentifier(),n=t_().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new y("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await t_().getSolanaIdentifier(e.walletName),n=t=>t_().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:r});let a=this.#q.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new y("Web3 first factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new y("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await n({identifier:r,nonce:o,provider:i});else throw e}await this.#q.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=rH.clerk.__internal_isWebAuthnSupported||rI,r=rH.clerk.__internal_getPublicCredentials||i5,n=rH.clerk.__internal_isWebAuthnAutofillSupported||rU;if(!i())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});return rV(this.#q,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new y("Passkey factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,i=e?i7(JSON.parse(e)):null;if(!i)throw new y("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await n());let{publicKeyCredential:a,error:o}=await r({publicKeyOptions:i,conditionalUI:s});if(!a)throw new T(o.message,{code:"passkey_retrieval_failed"});await this.#q.__internal_basePost({body:{publicKeyCredential:JSON.stringify(re(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rV(this.#q,async()=>{let e=this.#q.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new y("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#q.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return rV(this.#q,async()=>{let e=this.#q.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new y("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#q.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor"})})}async verifyMFAEmailCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eO("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#q.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rV(this.#q,async()=>{rH.clerk.client&&!rH.clerk.client.sessions.some(e=>e.id===this.#q.createdSessionId)&&await rH.clerk.client.reload(),this.#V=!0,await rH.clerk.setActive({session:this.#q.createdSessionId,navigate:t})})}reset(){if(!rH.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#V=!0,rH.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#q.supportedFirstFactors)return null;if(t){let i=this.#q.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#q.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.#q.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#q.identifier);if(r)return r;let n=this.#q.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rQ(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class rX extends tD{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new rs(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 t=this._status;this._status=e,e&&t!==e&&e9.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new r1(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e9.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tu();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tN(rX.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new y("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:rQ(t)})};prepareVerification=e=>(e9.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e9.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:t}=i1();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||tU("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};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:t,strategy:i="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:i})};authenticateWithWeb3=async e=>{let t,{generateSignature:i,identifier:r,unsafeMetadata:n,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tP("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||tC("SignUp");try{t=await i({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await t_().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:t_().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await t_().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:t_().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await t_().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:t_().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await t_().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:t_().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let r=await t_().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>t_().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=rX.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:n,redirectUrl:h,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return s&&this.id?this.update(e):this.create(e)},{verifications:p}=await u().catch(async e=>{if(S(e)&&O(e))return await rX.clerk.__internal_environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tT(m,rX.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tP("popup"),rB(rX.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rQ(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rX.clerk.__internal_environment?.userSettings.passwordSettings)return r$(rq(),{...rX.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};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 rs(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),iF.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__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 rX.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=rX.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=rX.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||rZ(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>tD._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new r3(e)))}let rY=new Set(["email_link","email_code","phone_code"]);function rZ(e){return!!e&&(rY.has(e)||e.startsWith("web3_"))}class r0{#q;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#q=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#q.verifications.emailAddress}get phoneNumber(){return this.#q.verifications.phoneNumber}get web3Wallet(){return this.#q.verifications.web3Wallet}get externalAccount(){return this.#q.verifications.externalAccount}get emailLinkVerification(){if(!n())return null;let e=eO("__clerk_status"),t=eO("__clerk_created_session");if(!e||!t)return null;let i="verified"===e&&void 0!==rX.clerk.client&&rX.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}}class r1{verifications;#V=!1;#q;constructor(e){this.#q=e,this.verifications=new r0(this.#q,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#q.id}get requiredFields(){return this.#q.requiredFields}get optionalFields(){return this.#q.optionalFields}get missingFields(){return this.#q.missingFields}get status(){return this.#q.status||"missing_requirements"}get username(){return this.#q.username}get firstName(){return this.#q.firstName}get lastName(){return this.#q.lastName}get emailAddress(){return this.#q.emailAddress}get phoneNumber(){return this.#q.phoneNumber}get web3Wallet(){return this.#q.web3wallet}get hasPassword(){return this.#q.hasPassword}get unsafeMetadata(){return this.#q.unsafeMetadata}get createdSessionId(){return this.#q.createdSessionId}get createdUserId(){return this.#q.createdUserId}get abandonAt(){return this.#q.abandonAt}get legalAcceptedAt(){return this.#q.legalAcceptedAt}get locale(){return this.#q.locale}get unverifiedFields(){return this.#q.unverifiedFields}get isTransferable(){return"transferable"===this.#q.verifications.externalAccount.status&&this.#q.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#q.verifications.externalAccount.status||"unverified"===this.#q.verifications.externalAccount.status)&&this.#q.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#q.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#q.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#V}shouldBypassCaptchaForAttempt(e){let t=rX.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=rX.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||rZ(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(rX.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new tN(rX.clerk),i=await t.managedOrInvisible({action:"signup"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rQ(e.unsafeMetadata):void 0,locale:e.locale??tu()};await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})}async create(e){return rV(this.#q,async()=>{await this._create(e)})}async update(e){return rV(this.#q,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rQ(e.unsafeMetadata):void 0};await this.#q.__internal_basePatch({path:this.#q.pathRoot,body:t})})}async password(e){return rV(this.#q,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rQ(e.unsafeMetadata):void 0};this.#q.id?await this.#q.__internal_basePatch({body:n}):await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})})}async sendEmailCode(){return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rV(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return rV(this.#q,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#q.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification"})})}async waitForEmailLinkVerification(){return rV(this.#q,async()=>{let{run:e,stop:t}=i1();await new Promise((i,r)=>{e(()=>this.#q.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rV(this.#q,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken({strategy:t}),u=i;try{new URL(i)}catch{u=window.location.origin+i}let p={redirectUrl:rX.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:u};if(c){let e=rJ(rX.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.#q.__internal_basePost({path:this.#q.pathRoot,body:{strategy:t,...p,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(S(e)&&O(e))return await rX.clerk.__internal_environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.#q.verifications.externalAccount;"unverified"===m&&g&&(c?(await rK(rX.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#q.reload()):eL(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rV(this.#q,async()=>{let e,s,a;switch(n){case"metamask":e=await t_().getMetamaskIdentifier(),s=t_().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await t_().getCoinbaseWalletIdentifier(),s=t_().generateSignatureWithCoinbaseWallet;break;case"base":e=await t_().getBaseIdentifier(),s=t_().generateSignatureWithBase;break;case"okx_wallet":e=await t_().getOKXWalletIdentifier(),s=t_().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#q.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:r}),await this.#q.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#q.verifications.web3Wallet;l||tC("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.#q.__internal_basePost({body:{signature:a,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rV(this.#q,async()=>{if(!this.#q.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#V=!0,await rX.clerk.setActive({session:this.#q.createdSessionId,navigate:t})})}reset(){if(!rX.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#V=!0,rX.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class r3 extends tD{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class r2 extends tD{pathRoot="tokens";jwt;static async create(e,t={},i={}){return new r2(await tD._fetch({method:"POST",path:e,body:t,search:i}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=th(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=th(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class r4 extends tD{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=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}}class r6 extends tD{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=tL(e.updated_at),this.createdAt=tL(e.created_at)),this}}class r5 extends tD{advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await tD._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new r5(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class r9 extends tD{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 r9}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case i3:return this.primaryEmailAddressId===e.id;case rP:return this.primaryPhoneNumberId===e.id;case ni:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new i3({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rC.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rP({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new ni({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r}=e||{};return new ru((await tD._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new r4((await tD._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new r4((await tD._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new iZ((await tD._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r6((await tD._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rQ(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=>(iF.emit(iR,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rL.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?rm.delete(`${this.path()}/profile_image`):rm.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>r8.retrieve(e);getOrganizationSuggestions=e=>rS.retrieve(e);getOrganizationMemberships=e=>rk.retrieve(e);getOrganizationCreationDefaults=()=>r5.retrieve();leaveOrganization=async e=>new iZ((await tD._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ik(e);addPaymentMethod=e=>iS(e);getPaymentMethods=e=>iI(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:t,name:i})=>i||[e,t].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 i3(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 rP(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 ni(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 ru(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rC(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rk(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new ro(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=tL(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tL(e.legal_accepted_at)),this.updatedAt=tL(e.updated_at||void 0),this.createdAt=tL(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 r7{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 r8 extends tD{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tD._fetch({path:"/me/organization_invitations",method:"GET",search:ie(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new r8(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=tL(e.created_at),this.updatedAt=tL(e.updated_at)),this}}let ne={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 nt extends tD{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:{...ne,name:"phone_number"},username:{...ne,name:"username"},web3_wallet:{...ne,name:"web3_wallet"},first_name:{...ne,name:"first_name"},last_name:{...ne,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:{...ne,name:"authenticator_app"},backup_code:{...ne,name:"backup_code"},passkey:{...ne,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,mfa:{required:!1}};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,t])=>t.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,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.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 ni extends tD{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,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:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new rr(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class nr extends tD{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tL(e.updated_at),this.createdAt=tL(e.created_at),iF.emit("resource:update",{resource:this})),this}async join(e){return rV(this,async()=>{await nr.join(e)})}static async join(e){return new nr(await tD._fetch({path:"/waitlist",method:"POST",body:e}))}}function nn(e,t){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,r=e,i.organizationMemberships.length!==r.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function ns(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(iX.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rD.isSessionResource(e)){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let i=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==r?.permissions?.length}(e,t)||(i=e,r=t,!!i.user!=!!r.user||!!i.user&&!!r.user&&nn(i.user,r.user))}if(r9.isUserResource(e))return nn(e,t)}catch{}return!0}(e,t)?e:t}let na="__clerk_db_jwt";function no(e,t){let i=new URL(e),r=i.searchParams.get(na);i.searchParams.delete(na);let n=r||t;return n&&i.searchParams.set(na,n),i}let nl=e=>{let t=new URL(e);return t.searchParams.delete(na),t},nc=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function nd(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var nh=function e(t,i){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=nd({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in n)n[a]&&(s+="; "+a,!0!==n[a]&&(s+="="+n[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+s}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},n=0;n<i.length;n++){var s=i[n].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",nd({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,nd({},this.attributes,t))},withConverter:function(t){return e(nd({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function nu(e){return{get:()=>nh.get(e),set(t,i={}){nh.set(e,t,i)},remove(t){nh.remove(e,t)}}}let np=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function nf(e,t){let i=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return i.setFullYear(i.getFullYear()+t),i}let nm=nu("__clerk_test_etld"),ng=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function n_(){try{return ng.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let nw="__client_uat",ny="__session",nb=e=>{let t=e.usePartitionedCookies(),i=t||tf()||n_()?"None":"Lax",r=np(i);return{sameSite:i,secure:r,partitioned:t&&r}};async function nv(e){let t;try{t=await eh(e)}catch(o){var i;i=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(i)||(console.log(i),V.add(i));let{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=r(e);t=n.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let nk=e=>{let t=e.usePartitionedCookies(),i=t||tf()||n_()?"None":"Lax",r=np(i);return{sameSite:i,secure:r,partitioned:t&&r}};class nS{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await nv(e.publishableKey),s=new nS(e,t,n,i,r);return await s.setup(),s}constructor(e,t,r,n,s){this.clerk=e,this.instanceType=n,this.clerkEventBus=s,iF.on(ix,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),iF.on(iR,()=>this.handleSignOut()),iF.on(iM,()=>{this.devBrowser.refreshCookies()}),this.refreshTokenOnFocus(),this.startPollingForToken();const a={usePartitionedCookies:()=>rh.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let r=nu(nw),n=nu(eu(nw,e));return{set:e=>{let s=nf(Date.now(),1),a=t.usePartitionedCookies(),o=a||tf()||n_()?"None":"Strict",l=np(o),c=a&&l,d=function(e=window.location.hostname,t=nm,r){if(i)return i;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let n=e.split(".");if(1===n.length)return e;for(let e=n.length-2;e>=0;e--){let s=n.slice(e).join(".");if(t.set("1",{...r,domain:s}),"1"===t.get())return t.remove({...r,domain:s}),i=s,s;t.remove({...r,domain:s})}return i=e,e}(void 0,void 0,{sameSite:o,secure:l}),h="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(h=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),r.remove(),n.set(h,{domain:d,expires:s,partitioned:c,sameSite:o,secure:l}),r.set(h,{domain:d,expires:s,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(n.get()||r.get()||"0",10)}})(r,a),this.sessionCookie=((e,t)=>{let i=nu(ny),r=nu(eu(ny,e));return{set:e=>{let n=nf(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=nb(t);o&&(i.remove(),r.remove()),i.set(e,{expires:n,sameSite:s,secure:a,partitioned:o}),r.set(e,{expires:n,sameSite:s,secure:a,partitioned:o})},remove:()=>{let e=nb(t);i.remove(e),r.remove(e),e.partitioned&&(i.remove(),r.remove())},get:()=>r.get()||i.get()}})(r,a),this.activeCookie=(()=>{let e=nu("clerk_active_context"),t={secure:np("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i,cookieOptions:r}){let n,s,a=(n=nu(na),s=nu(eu(na,e)),{get:()=>s.get()||n.get(),set:e=>{let t=nf(Date.now(),1),{sameSite:i,secure:a,partitioned:o}=nk(r);o&&(s.remove(),n.remove()),s.set(e,{expires:t,sameSite:i,secure:a,partitioned:o}),n.set(e,{expires:t,sameSite:i,secure:a,partitioned:o})},remove:()=>{let e=nk(r);s.remove(e),n.remove(e),e.partitioned&&(s.remove(),n.remove())}});function o(){return a.get()}function l(e){a.set(e)}function c(){a.remove()}return{clear:function(){c()},setup:async function e(){var e;let r,n;if(!e_(t))return;i.onBeforeRequest(e=>{let t=o();t&&e?.url&&(e.url=no(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&l(i)});let s=(r=(e=new URL(window.location.href)).searchParams.get(na)||"",(n=nl(nc(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",n),r);if(s)return void l(s);if(a.get())return;let c=i.buildUrl({path:"/dev_browser"}),d=await fetch(c.toString(),{method:"POST"});if(!d.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await d.json()).errors);e[0]?tS(e[0].longMessage):tS()}let h=await d.json();l(h?.id)},getDevBrowser:o,setDevBrowser:l,removeDevBrowser:c,refreshCookies:function(){let e=o();e&&l(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r,cookieOptions:a})}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 t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${tk} Missing dev browser. Please contact support.`);return no(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new iJ,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 t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||c()||e9.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(S(e)||b(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(x(e))return void this.clerk.handleUnauthenticated().catch(e0.lQ);this.clerkEventBus.emit(f,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",i=`${e}:${t}`;":"!==i?this.activeCookie.set(i):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,i]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&i===n}getSessionCookie(){return this.sessionCookie.get()}}class nI{clerk;captchaChallenge;timers;constructor(e,t=new tN(e),i=i$()){this.clerk=e,this.captchaChallenge=t,this.timers=i}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 nU=["/client","/waitlist"];class nA{async getBaseFapiProxyOptions(){let e=await tD.clerk.session?.getToken();if(!e)throw new y("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 tD._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:ie({...e,subject:e?.subject??tD.clerk.organization?.id??tD.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new t$(e))}})}async create(e){return new t$(await tD._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tD.clerk.organization?.id??tD.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new t$(await tD._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let nC=new Map;class nP{#M=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#M){if(n())for(let e of(this.#M=!0,t.loaders))try{this.applyLoader(e)}catch(e){q(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void q(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",i=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":r.setAttribute(t,String(i));break;default:q(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),i){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(i?.startsWith("#")){let e=document.getElementById(i.substring(1));if(!e)return void q(`[protect] loader target element not found: ${i}`);e.appendChild(r);return}q(`[protect] loader target is invalid: ${i}`)}}}class nT{signInResourceSignal=ii;signInErrorSignal=ir;signInFetchSignal=is;signInSignal=ia;signUpResourceSignal=io;signUpErrorSignal=il;signUpFetchSignal=ic;signUpSignal=id;waitlistResourceSignal=ih;waitlistErrorSignal=iu;waitlistFetchSignal=ip;waitlistSignal=im;_waitlistInstance;__internal_effect=t2;__internal_computed=t3;constructor(){iF.on("resource:update",this.onResourceUpdated),iF.on("resource:error",this.onResourceError),iF.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new nr(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rH&&this.signInErrorSignal({error:e.error}),e.resource instanceof rX&&this.signUpErrorSignal({error:e.error}),e.resource instanceof nr&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rH){if(nO(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rX){if(nO(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof nr&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rH&&this.signInFetchSignal({status:e.status}),e.resource instanceof rX&&this.signUpFetchSignal({status:e.status}),e.resource instanceof nr&&this.waitlistFetchSignal({status:e.status})}}function nO(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let nE="cannot_render_billing_disabled",nx="cannot_render_user_missing",nR="cannot_render_organizations_disabled",nM="cannot_render_organization_missing",nz="cannot_render_single_session_enabled",nF={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 nN{static version="6.3.1-snapshot.v20260311230607";static sdkMetadata={name:"@clerk/clerk-js",version:"6.3.1-snapshot.v20260311230607"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nT;internal_last_error=null;environment;#H;#G="";#Q;#X;#Y;#Z;#ee;#et=null;#ei;#er;#en;#es="loading";#ea=[];#eo=[];#el={};#ec=null;#ed=0;#eh=p();get __internal_queryClient(){return this.#H||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#H||(this.#H=new e,this.#eh.emit("queryClientStatus","ready"))}),this.#H?{__tag:"clerk-rq-client",client:this.#H}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#G}get version(){return nN.version}set sdkMetadata(e){nN.sdkMetadata=e}get sdkMetadata(){return nN.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#es}get isSatellite(){return!!tp()&&(0,e0.VK)(this.#el.isSatellite,new URL(window.location.href),!1)}get domain(){if(tp()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}((0,e0.VK)(this.#Q,new URL(window.location.href)));if("production"===this.#en){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return""}get proxyUrl(){if(tp()){let e=(0,e0.VK)(this.#X,new URL(window.location.href));return!e||e$(e)||ej(e)||tc.throwInvalidProxyUrl({url:e}),e?ej(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ec(this.publishableKey);return e?e.frontendApi:tc.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#en}get isStandardBrowser(){return this.#el.standardBrowser||!1}get billing(){return nN._billing||(nN._billing=new it),nN._billing}get apiKeys(){return nN._apiKeys||(nN._apiKeys=new nA),nN._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===a&&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:t,orgId:i,planId:r,planPeriod:n}=e;return`${t}-${i||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=nC.get(c);if(d)return d.signals.computedSignal();let h=(i=t1({resource:null}),r=t1({error:null}),n=t1({status:"idle"}),s=t3(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:ig(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),u=new iy(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return nC.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#el[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tc.throwMissingPublishableKeyError();const i=ec(e);if(!i)return tc.throwInvalidPublishableKeyError({key:e});this.#Q=t?.domain,this.#X=t?.proxyUrl,this.environment=rh.getInstance(),this.#en=i.instanceType,this.#G=e,this.#er=function(e){let t=[],i=[];async function r(e){for await(let i of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:r,search:n,rotatingTokenNonce:s}){let a=new URLSearchParams(n);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.3.1-snapshot.v20260311230607"),s&&a.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&a.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&a.append("_method",t),i&&!nU.some(e=>i.startsWith(e))&&r&&a.append("_clerk_session_id",r),ef([...a.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),a=n.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),eb({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eb({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:c="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 t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(d)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===c||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?ef(d,{keyEncoder:X}):d);let h=await r(o),u="GET"===c?"GET":"POST",p=o.url,f={...o,method:u,credentials:o.credentials||"include"};try{if(h){let e=i?.fetchMaxTries??(l()?4:11);s=await tt(()=>fetch(p,f),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===u&&i<e,onBeforeRetry:e=>{p.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){let e=p.toString();e9.error("network error",{error:t,url:e,method:c},"fapiClient");throw Error(`${tk} Network error at "${e}" - ${t}. Please try again.`)}let m=204!==s.status?await s.json():null,g=Object.assign(s,{payload:m});return s.ok||e9.error("request failed",{method:c,path:o.path,status:s.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:a,onAfterResponse:function(e){i.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eh.emit(f,"loading"),this.#eh.prioritizedOn(f,e=>this.#es=e),this.#eh.on(f,e=>{tp()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eu()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new y("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tp()&&("ready"===this.#es||"degraded"===this.#es)&&this.#eu()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),tD.clerk=this,this.#Z=new nP}getFapiClient=()=>this.#er;load=async e=>{if(e9.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#en||e?.unsafe_disableDevelopmentModeConsoleWarning||q("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#el=this.#ep(e),this.#el.ui?.ClerkUI&&(this.#ei=Promise.resolve(this.#el.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#el,new tr))),"development"===this.#en&&(this.#el.routerPush||this.#el.routerReplace)&&(!this.#el.routerPush||!this.#el.routerReplace)){let e=this.#el.routerPush?"routerReplace":"routerPush";q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}iF.on(iz,()=>{this.#ef(this.session)}),this.#el.sdkMetadata&&(nN.sdkMetadata=this.#el.sdkMetadata),!1!==this.#el.telemetry&&(this.telemetry=new eq({clerkVersion:nN.version,samplingRate:1,perEventSampling:!this.#el.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#el.telemetry}),this.#el.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=eZ(e);if(i){t=i;break}}else t=eZ(i);return{themeName:t}}(this.#el.appearance)}));try{this.#el.standardBrowser?await this.#em():await this.#eg();let e=this.#el.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#el.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,s=r||i&&!n,a=i&&!r?"error":void 0;s&&function(e={}){if(e2)return;let{enabled:t=!1,...i}=e;t&&(e1=!0,e2=!0,e5(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#Z?.load(this.environment),e9.info("load() complete",{},"clerk")}catch(e){throw this.#eh.emit(f,"error"),e9.error("load() failed",{error:e},"clerk"),e}}};#e_(){let e;return!!(!this.#el.signUpUrl&&this.#el.signInUrl&&(e=this.#el.signInUrl,!ep.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0.lQ,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0.lQ,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();e9.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:n?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=tn(this.#el.standardBrowser);iF.emit(iR,null),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#ef(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#ew(),this.#el.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e9.info("signOut() complete",{redirectUrl:ev(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#ew(),await l?.remove(),await o(),e9.info("signOut() complete",{redirectUrl:ev(s)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(eY("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(M(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotOpenSignInOrSignUp,{code:nz});return}this.assertComponentsReady(this.#ei);let t="SignIn";this.#ei.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let i={withSignUp:e?.withSignUp??this.#e_()};this.telemetry?.record(eY(t,e,i))};closeSignIn=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(z(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotRenderAnyBillingComponent("Checkout"),{code:nE});return}if(!this.user){if("development"===this.#en)throw new y(eN.cannotOpenCheckout,{code:nx});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(z(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotRenderAnyBillingComponent("PlanDetails"),{code:nE});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(eY("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#en)throw new y(eN.cannotOpenUserProfile,{code:nx});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(eY("UserVerification",e))};__internal_closeReverification=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#en||q(`Clerk: "${i}" requires an active user session. Ensure a user is signed in before executing ${i}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#en&&this.__internal_openEnableOrganizationsPrompt({caller:i,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eX("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ei),this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await s.e("279").then(s.bind(s,5608));return e};openSignUp=e=>{if(M(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotOpenSignInOrSignUp,{code:nz});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(eY("SignUp",e))};closeSignUp=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#en)throw new y(eN.cannotOpenUserProfile,{code:nx});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eY("UserProfile",e,t))};closeUserProfile=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nR})}});if(t){if(!this.organization){if("development"===this.#en)throw new y(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:nM});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(eY("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nR})}});t&&(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(eY("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(eY("Waitlist",e))};closeWaitlist=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ei);let i="SignIn";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#e_()};this.telemetry?.record(eX(i,t,r))};unmountSignIn=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ei);let i="UserAvatar";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eX(i,t))};unmountUserAvatar=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ei);let i="SignUp";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eX(i,t))};unmountSignUp=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#en)throw new y(eN.cannotRenderComponentWhenUserDoesNotExist,{code:nx});return}this.assertComponentsReady(this.#ei);let i="UserProfile";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eX(i,t,r))};unmountUserProfile=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nR})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#en)throw new y(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:nM});return}this.assertComponentsReady(this.#ei);let n="OrganizationProfile";this.#ei.then(e=>e.ensureMounted({preloadHint:n})).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eX(n,t))};unmountOrganizationProfile=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nR})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="CreateOrganization";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eX(r,t))};unmountCreateOrganization=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:nR})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="OrganizationSwitcher";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eX(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:nR})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="OrganizationList";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eX(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ei);let i="UserButton";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eX(i,t,r))};unmountUserButton=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ei);let i="Waitlist";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eX(i,t))};unmountWaitlist=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(z(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotRenderAnyBillingComponent("PricingTable"),{code:nE});return}this.assertComponentsReady(this.#ei);let i="PricingTable";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eX(i,t))};unmountPricingTable=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ei);let i="OAuthConsent";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),F(this,i=this.environment)&&N(this,i)){if("development"===this.#en)throw new y(eN.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&N(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(F(this,this.environment)){if("development"===this.#en)throw new y(eN.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ei);let r="APIKeys";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eX(r,t))};unmountAPIKeys=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new y(eN.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:nR})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="TaskChooseOrganization";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eX(r,t))};unmountTaskChooseOrganization=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ei);let i="TaskResetPassword";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(eX("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#ei);let i="TaskSetupMFA";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(eX("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,e9.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:i??null},"clerk");try{var s;let a;if(!this.client)throw e9.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===n&&!this.session)throw e9.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 n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e0.lQ,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(s={...this.#el,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||q('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=i}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let h=c?.status==="pending"&&c?.currentTask&&this.#el.taskUrls?.[c?.currentTask.key],u=!!(i||h||r);if(tp()&&globalThis.document.hasFocus()||!this.#el.standardBrowser){let e;if(u&&c)try{(e=await c.__internal_touch())&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(x(e))this.handleUnauthenticated();else throw e}else await this.#ey(c);c=this.#eb(c?.id,e)}try{await c?.getToken()||iF.emit(ix,{token:null})}catch(e){if(U.is(e))e9.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let p=tn(this.#el.standardBrowser);if(u&&await p.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#ew(),h){let e=i?eb({base:h,hashSearchParams:{redirectUrl:i}},{stringify:!0}):h;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>{if(e=!0,!this.client?.isEligibleForTouch())return t;let i=new URL(t,window.location.href),r=this.client.buildTouchUrl({redirectUrl:i});return this.buildUrlWithAuth(r)};await r({session:c,decorateUrl:t}),"development"===this.#en&&!e&&this.client.isEligibleForTouch()&&q("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else if(i){if(this.client.isEligibleForTouch()){let e=new URL(i,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(i)}}}),p.isUnloading())return;this.#ef(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var i;let r;return i=e,e=e=>{var t;r||={...e},i(r={...{client:ns((t=r).client,e.client),session:ns(t.session,e.session),user:ns(t.user,e.user),organization:ns(t.organization,e.organization)}})},this.#ea.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ea=this.#ea.filter(t=>t!==e)}};on=(...e)=>{this.#eh.on(...e)};off=(...e)=>{this.#eh.off(...e)};__internal_addNavigationListener=e=>(this.#eo.push(e),()=>{this.#eo=this.#eo.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tp())return;if(void 0===window.location){let i=t?.replace&&this.#el.routerReplace?this.#el.routerReplace:this.#el.routerPush;return i?(e9.info(`Clerk is navigating to: ${e}`),await i(e,{windowNavigate:eL})):void 0}setTimeout(()=>{this.#ev()},0);let i=new URL(e,window.location.href);this.#ek.includes(i.protocol)||(console.warn(`Clerk: "${i.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),i=new URL("/",window.location.href));let r=t?.replace&&this.#el.routerReplace?this.#el.routerReplace:this.#el.routerPush;if(e9.info(`Clerk is navigating to: ${i}`),this.#el.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void eL(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eL};return await r(ev(i),n)};buildUrlWithAuth(e){if("production"===this.#en)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#Y?this.#Y.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#eS(t));let i=this.isSatellite?this.#eI(e):e;return this.#eU("signInUrl",{...i,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#eS(t));let i=this.isSatellite?this.#eI(e):e;return this.#eU("signUpUrl",{...i,redirectUrl:t},e?.initialValues)}#eS=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(W,D),t.toString()}catch{return e}};#eI=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#eS(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#eS(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#eS(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#eS(t.signUpFallbackRedirectUrl)),t};buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#el,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eC(this.#el,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#el.afterSignOutUrl?this.buildUrlWithAuth(this.#el.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#el.newSubscriptionRedirectUrl?this.#el.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eb({base:this.#el.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#el.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#el.afterMultiSessionSingleSignOutUrl):this.#el.signInUrl?this.buildUrlWithAuth(eb({base:this.#el.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 t=this.session?.currentTask;if(!t)return"";let i=this.#el.taskUrls?.[t.key];return i||eb({base:this.buildSignInUrl(e),hashPath:eM(t)},{stringify:!0})}#eA=async()=>{if(!tp())return;let e=new URLSearchParams({[W]:L}),t=eO(j);t&&e$(t)||function(){throw Error(`${tk} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=eb({base:eO(j),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tp())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tp())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tp())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tp())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tp())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tp())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tp())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tp())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tp())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tp())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tp())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eO("__clerk_status");if("expired"===i)throw new P("expired");if("client_mismatch"===i)throw new P("client_mismatch");if("verified"!==i)throw new P("failed");let r=eO("__clerk_created_session"),{signIn:n,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===s.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e0.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,i)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,s="identifier"in(e||{})?e:r,a="missingFields"in(e||{})?e:n,o=e=>i&&"function"==typeof i?i(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await i.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:s}=t,{externalAccount:a}=i.verifications,o={status:i.status,missingFields:i.missingFields,externalAccountStatus:a.status,externalAccountErrorCode:a.error?.code,externalAccountSessionId:a.error?.meta?.sessionId,sessionId:i.createdSessionId},l={status:t.status,firstFactorVerificationStatus:s.status,firstFactorVerificationErrorCode:s.error?.code,firstFactorVerificationSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||n.signInUrl),h=c(e.signUpUrl||n.signUpUrl),u=c(e.firstFactorUrl||eb({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||eb({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||eb({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eC(this.#el,e),g=c(e.continueSignUpUrl||eb({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:r,navigate:n,handleComplete:s,redirectUrl:a="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return s&&s();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:a,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let s=ex();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return n(i,{searchParams:s});if(r)return n(r,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||eb({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eb({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),w=e.signInUrl||n.signInUrl,y=e.signUpUrl||n.signUpUrl,b=async({session:e,baseUrl:t,redirectUrl:i})=>{e.currentTask?await ez(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:w,redirectUrl:m.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignInUrl()})}});case"needs_first_factor":return u();case"needs_second_factor":return p();case"needs_new_password":return f();default:tI("sign in")}}let v="user_locked"===o.externalAccountErrorCode,k="user_locked"===l.firstFactorVerificationErrorCode;if(v)return h();if(k)return d();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return u();if("needs_new_password"===l.status)return f();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let t=await i.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});case"missing_requirements":return _({missingFields:t.missingFields});default:tI("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return p();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,I="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||I){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await b({session:e,baseUrl:S?y:w,redirectUrl:m.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?h():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?_({missingFields:i.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iX.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&iF.emit(iR,null),this.setActive({session:null})}catch(e){if(S(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#Y&&await this.#Y.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(S(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});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:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,h=n.replace("web3_","").replace("_signature",""),u=await t_().getWeb3Identifier({provider:h,walletName:o});switch(h){case"metamask":l=t_().generateSignatureWithMetamask;break;case"base":l=t_().generateSignatureWithBase;break;case"coinbase_wallet":l=t_().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new y("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>t_().generateSignatureWithSolana({...e,walletName:o});break;default:l=t_().generateSignatureWithOKXWallet}let p=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),f=p(a||eb({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),m=p(t||eb({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:l,strategy:n,walletName:o})}catch(e){if(tl(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:l,unsafeMetadata:r,strategy:n,legalAccepted:s,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await m();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await ez(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await f();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rb.create({name:e,slug:t});getOrganization=async e=>rb.get(e);joinWaitlist=async({emailAddress:e})=>nr.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,t)=>{if(!this.client){let t=this.#el.selectInitialSession?this.#el.selectInitialSession(e):this.#eC(e);this.#ef(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#eb(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e0.lQ)(),this.#ef(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||c()||e9.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),iF.emit(ix,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#eP()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rh(e)};__internal_onBeforeRequest=e=>{this.#er.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#er.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#ep({...this.#el,...e.options})};return this.#ei?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eT=()=>{let e=new URLSearchParams({[j]:window.location.href});return eb({base:this.#el.signInUrl,searchParams:e},{stringify:!0})};#eO=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eE=()=>{let e=eO(W);return e!==L&&!!this.isSatellite&&(e===D||!1!==this.#el.satelliteAutoSync&&!!this.#Y?.isSignedOut())};#ex=()=>"production"!==this.#en&&!this.isSatellite&&!!eO(j);#eR=async()=>{"development"===this.instanceType?await this.navigate(this.#eT()):"production"===this.instanceType&&await this.navigate(this.#eO())};#eM=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${tk} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${tk} The signInUrl needs to be on a different origin than your satellite application.`)}()};#ez=()=>{this.isSatellite&&("development"!==this.#en||this.#el.signInUrl||function(){throw Error(`${tk} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tk} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#el.signInUrl&&this.#eM(this.#el.signInUrl,window.location.origin))};#em=async()=>{if(this.#Y=await nS.create(this,this.#er,this.#en,this.#eh),this.#ez(),this.#eE())return void await this.#eR();if(this.#ex())return void await this.#eA();this.#ec=(()=>{if(!n())return{onPageFocus:e0.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#et=new BroadcastChannel("clerk")),this.#eF();let e=function(e=window.location.hostname){if(!e)return!1;let t=ew.get(e);void 0===t&&(t=er.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||en.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ew.set(e,t));return t}(window?.location.hostname),t="development"===this.#en&&!e,i=0,r=0;for(;r<2;){r++;try{let e=rh.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=tv.getItem(tw,null);e&&this.updateEnvironment(new rh(e))}),r=async()=>iX.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(E(e))throw e;++i;let t=this.#Y?.getSessionCookie(),r=function(e){let t;try{t=new r2({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iX.clearInstance(),!t?.jwt)return iX.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:r,orgId:n,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,r,n,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=rN(e.fea),{permissions:a,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let i=e.split(",").map(e=>e.trim());return{permissions:i,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(i.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(n>=i.length)continue;let a=i[n];if(a)for(let e=0;e<a.length;e++)1===a[e]&&r.push(`org:${s}:${t[e]}`)}return r}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:r,orgPermissions:n,factorVerificationAge:s}})(t.jwt.claims),c={object:"client",last_active_session_id:i,id:"client_init",sessions:[{object:"session",id:i,status:"active",last_active_organization_id:n||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:n&&o&&s?[{object:"organization_membership",id:n,role:s,permissions:a||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return iX.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#Y?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#Y?.startPollingForToken()}),null}),[,n]=await (0,e0.vd)([e,r()]);if("rejected"===n.status){let e=n.reason;if(tl(e,"requires_captcha"))await r();else throw e}if(this.#Y?.setClientUatCookieForDevelopmentInstances(),await this.#eN())return;break}catch(e){if(tl(e,"dev_browser_unauthenticated"))await this.#Y.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tk} Something went wrong initializing Clerk.`)}()}this.#ee=new nI(this),this.#ee.start(),this.#eW(),this.#eD(),this.#eL(),this.#eh.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eg=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rh.getInstance().fetch({touch:!1,fetchMaxTries:i}),iX.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(b(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new rh(i?.environment),iX.clearInstance(),t=iX.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#eh.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rh.getInstance().fetch({touch:!1,fetchMaxTries:1}),iX.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eP()};#eC=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#eF=()=>{n()&&(this.#ec?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#ed>Date.now())&&(this.#ed=Date.now()+5e3,this.#el.touchSession&&this.#ey(this.session))}),this.#et?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),iF.on(iR,()=>{this.#et?.postMessage({type:"signout"})}),iF.on(iM,()=>{tv.setItem(tw,this.environment?.__internal_toSnapshot(),864e5)}))};#ey=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{if(x(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#eP=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#ea))t(e)}};#ev=()=>{for(let e of this.#eo)e()};#ew=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eP()};#e$=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#ej=(e=this.session)=>({session:e||null,organization:this.#e$(e),user:e?e.user:null});#ef=(e,t)=>{let{session:i,organization:r,user:n}=this.#ej(e);this.session=i,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#eP()};#eb=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#eD=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ei?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eL=()=>{this.#el.__internal_keyless_claimKeylessApplicationUrl&&this.#ei?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#el.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#el.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#el.__internal_keyless_dismissPrompt}})})};#eU=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#el[e]||this.environment.displayConfig[e];this.#e_()&&(r=this.#el.signInUrl);let n=new eC(this.#el,t).toSearchParams(),s=new URLSearchParams(i||{}),a=eb({base:r,hashPath:this.#e_()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,n]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eN=async()=>{var e;let t,i,r,n,s=new URLSearchParams(window.location.search).get("redirect_url"),a="production"===this.instanceType,o=null!==s&&(e=this.frontendApi,i=(t=new URL(s,em)).pathname,r=eU.includes(i)||eA.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#el.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#el.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,em),(!eU.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#ep=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,i=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...nF,...e,ui:i,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ey(t)}`),r.push(`https://*.${ey(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#eW=()=>{try{eE(W),eE(eP),eE($),eE("__clerk_handshake"),eE("__clerk_handshake_nonce"),eE("__clerk_help")}catch{}};get #ek(){let e=eD;return this.#el.allowedRedirectProtocols&&(e=e.concat(this.#el.allowedRedirectProtocols)),e}#eu(){return void 0!==this.client}}let nW=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",nD=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",nL=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new nN(nW,{proxyUrl:nD,domain:nL}))})(),{}})());
16
+ (This notice only appears in development)`,eW=e=>eN(`${e} as a function is not supported in this environment. The value will be ignored. Provide an absolute URL instead.`),eD={proxyUrlAsFunctionNotSupported:eW("proxyUrl"),domainAsFunctionNotSupported:eW("domain"),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=>eN(`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=>eN(`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(eD)){let t=eD[e];"function"!=typeof t&&(eD[e]=eN(t))}let eL="clerk:beforeunload",e$=["http:","https:","wails:","chrome-extension:"];function ej(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eL)),window.location.href=t.href}function eB(e){return/^http(s)?:\/\//.test(e||"")}function eJ(e){return e.startsWith("/")}var eK=class{#l;#c=864e5;constructor(e){this.#l=e}isEventThrottled(e){let t=Date.now(),i=this.#d(e),r=this.#l.getItem(i);return!!r&&!(t-r>this.#c)||(this.#l.setItem(i,t),!1)}#d(e){let{sk:t,pk:i,payload:r,...n}=e,s={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>s[e]))}},eV=class{#h="clerk_telemetry_throttler";getItem(e){return this.#u()[e]}setItem(e,t){try{let i=this.#u();i[e]=t,localStorage.setItem(this.#h,JSON.stringify(i))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#h)}}removeItem(e){try{let t=this.#u();delete t[e],localStorage.setItem(this.#h,JSON.stringify(t))}catch{}}#u(){try{let e=localStorage.getItem(this.#h);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eq=class{#l=new Map;#p=1e4;getItem(e){return this.#l.size>this.#p?void this.#l.clear():this.#l.get(e)}setItem(e,t){this.#l.set(e,t)}removeItem(e){this.#l.delete(e)}};let eH=new Set(["error","warn","info","debug","trace"]);var eG=class{#f;#m;#g={};#_=[];#w=null;constructor(e){this.#f={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.#g.clerkVersion=e.clerkVersion??"":this.#g.clerkVersion="",this.#g.sdk=e.sdk,this.#g.sdkVersion=e.sdkVersion,this.#g.publishableKey=e.publishableKey??"";const t=ec(e.publishableKey);t&&(this.#g.instanceType=t.instanceType),e.secretKey&&(this.#g.secretKey=e.secretKey.substring(0,16)),this.#m=new eK(eV.isSupported()?new eV:new eq)}get isEnabled(){return!("development"!==this.#g.instanceType||this.#f.disabled||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#f.debug||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#y(e.event,e.payload);if(this.#b(t.event,t),!this.#v(t,e.eventSamplingRate))return;this.#_.push({kind:"event",value:t}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#S(e))return;let t="string"==typeof e?.level&&eH.has(e.level),i="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!i||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==r});return}let s=this.#I(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#g.publishableKey||null,payload:this.#U(e.context)};this.#_.push({kind:"log",value:a}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#v(e,t){return this.isEnabled&&!this.isDebug&&this.#A(e,t)}#S(e){return!0}#A(e,t){let i=Math.random();return!!(i<=this.#f.samplingRate&&(!1===this.#f.perEventSampling||void 0===t||i<=t))&&!this.#m.isEventThrottled(e)}#k(){if("undefined"==typeof window)return void this.#C();if(this.#_.length>=this.#f.maxBufferSize){this.#w&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#w)):clearTimeout(Number(this.#w))),this.#C();return}this.#w||("requestIdleCallback"in window?this.#w=requestIdleCallback(()=>{this.#C(),this.#w=null}):this.#w=setTimeout(()=>{this.#C(),this.#w=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#w=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),i=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),i.length>0&&fetch(new URL("/v1/logs",this.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:i})}).catch(()=>void 0)}#b(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#I(){let e={name:this.#g.sdk,version:this.#g.sdkVersion};if("undefined"!=typeof window){let t=window;if(t.Clerk){let i=t.Clerk;if("object"==typeof i&&null!==i&&"constructor"in i&&"function"==typeof i.constructor&&i.constructor.sdkMetadata){let{name:t,version:r}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#y(e,t){let i=this.#I();return{event:e,cv:this.#g.clerkVersion??"",it:this.#g.instanceType??"",sdk:i.name,sdkv:i.version,...this.#g.publishableKey?{pk:this.#g.publishableKey}:{},...this.#g.secretKey?{sk:this.#g.secretKey}:{},payload:t}}#U(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let eQ="COMPONENT_MOUNTED",eX=new Set(["SignIn","SignUp"]);function eY(e){return function(t,i,r){return{event:e,eventSamplingRate:e===eQ?eX.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,theme:!!i?.appearance?.theme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...r}}}}function eZ(e,t,i){return eY(eQ)(e,t,i)}function e0(e,t,i){return eY("COMPONENT_OPENED")(e,t,i)}function e1(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}var e3=s(2044);let e2=!1,e4=null,e5=!1,e6=[];function e9(e,t,i,r){e2&&(e6.push({level:e,message:t,context:i,source:r,ts:Date.now()}),e6.length>200&&e6.shift())}async function e7(e){try{if(!e2||e4)return;let{getDebugLogger:t}=await s.e("507").then(s.bind(s,9854)),i=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(i&&(e4=i)&&0!==e6.length){for(let e of e6){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e4.error(e.message,t,e.source);break;case"warn":e4.warn(e.message,t,e.source);break;case"info":e4.info(e.message,t,e.source);break;case"debug":e4.debug(e.message,t,e.source)}}e6.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e8={debug(e,t,i){e4?e4.debug(e,t,i):e9("debug",e,t,i)},error(e,t,i){e4?e4.error(e,t,i):e9("error",e,t,i)},info(e,t,i){e4?e4.info(e,t,i):e9("info",e,t,i)},warn(e,t,i){e4?e4.warn(e,t,i):e9("warn",e,t,i)}},te={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tt=async e=>new Promise(t=>setTimeout(t,e)),ti=(e,t)=>t?e*(1+Math.random()):e,tr=async(e,t={})=>{var i;let r,n=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...te,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await tt((e=ti(e=i.initialDelay*Math.pow(i.factor,r),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!s(e,++n))throw e;h&&await h(n),c&&1===n?await tt(ti(100,d)):await u()}},tn=async e=>tr(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class ts{#P={"@zxcvbn-ts/core":()=>tn(()=>s.e("729").then(s.bind(s,7010))),"@zxcvbn-ts/language-common":()=>tn(()=>s.e("873").then(s.bind(s,655))),"@base-org/account":()=>tn(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,71))),"@coinbase/wallet-sdk":()=>tn(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,5537))),"@stripe/stripe-js":()=>tn(()=>s.e("279").then(s.bind(s,5608)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let ta=(e=!1)=>{let t,i;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,i=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",i),window.addEventListener(eL,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(eL,i)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},to=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tl=e=>({proration:e.proration?{amount:to(e.proration.amount),cycleDaysRemaining:e.proration.cycle_days_remaining,cycleDaysTotal:e.proration.cycle_days_total,cycleRemainingPercent:e.proration.cycle_remaining_percent}:null,payer:e.payer?{remainingBalance:to(e.payer.remaining_balance),appliedAmount:to(e.payer.applied_amount)}:null,total:to(e.total)}),tc=e=>{let t={grandTotal:to(e.grand_total),subtotal:to(e.subtotal),taxTotal:to(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?to(e.past_due):null),"credit"in e&&(t.credit=e.credit?to(e.credit):null),"credits"in e&&(t.credits=e.credits?tl(e.credits):null),"total_due_now"in e&&(t.totalDueNow=to(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?to(e.total_due_after_free_trial):null),t};function td(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let th=C({packageName:"@clerk/clerk-js"});function tu(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tp(e){let t=(e||"").split("."),[i,r,n]=t;if(3!==t.length||!i||!r||!n)throw Error("JWT could not be decoded");let s=JSON.parse(tu(r)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:r,signature:n},header:JSON.parse(tu(i)),claims:a}}function tf(){if(!n())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tm(){return void 0!==globalThis.document}function tg(){if(!function(){if(!tm())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var t_=class e{#T=[];#O={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #E=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#x),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=e=>{let t=this.#T.find(t=>t.info.name===this.#O[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#T.some(t=>t.info.uuid===e.detail.info.uuid)||this.#T.push(e.detail)}},tw=class e{#R=void 0;#F=!1;static #E=null;constructor(){}async #M(){if(this.#F)return;this.#F=!0;let e=await s.e("836").then(s.bind(s,5527)).then(e=>e.getWallets());this.#R=e.get(),e.on("register",()=>{this.#R=e.get()}),e.on("unregister",()=>{this.#R=e.get()})}#z(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#N(e){return"solana:signMessage"in e.features}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=async e=>{await this.#M();let t=(this.#R||[]).find(t=>t.name===e&&this.#z(t)&&this.#N(t));if(t&&this.#z(t))return t;if("undefined"==typeof window)return;let i=window.solana;if(i&&"function"==typeof i.connect&&"function"==typeof i.signMessage)return i}};let ty=()=>(function(e){let t=C({packageName:"@clerk/shared"});async function i(e){let{provider:t,walletName:i}=e,r=await f(t,i);if(!r)return"";if("solana"===t){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let n=await r.request({method:"eth_requestAccounts"});return n&&n[0]||""}let r=async e=>{let{identifier:t,nonce:i,provider:r,walletName:n=""}=e,s=await f(r,n);if(!s)return"";if("solana"===r)try{let e=s.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let r=await s.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(i)});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 y("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new y("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await s.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function n(){return await i({provider:"metamask"})}async function s(){return await i({provider:"coinbase_wallet"})}async function a(){return await i({provider:"okx_wallet"})}async function o(){return await i({provider:"base"})}async function l(e){return await i({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 h(e){return await r({...e,provider:"okx_wallet"})}async function u(e){return await r({...e,provider:"base"})}async function p(e){return await r({...e,provider:"solana"})}async function f(i,r){if("coinbase_wallet"===i){let t=await e.import("@coinbase/wallet-sdk");return t?t.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"===i)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===i?r&&0!==r.length?await tw.getInstance().get(r):void t.throw("Wallet name must be provided to get Solana wallet provider"):t_.getInstance().get(i)}return{getWeb3Identifier:i,generateWeb3Signature:r,getMetamaskIdentifier:n,getCoinbaseWalletIdentifier:s,getOKXWalletIdentifier:a,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:h,generateSignatureWithBase:u,generateSignatureWithSolana:p}})(new ts),tb="environment",tv=JSON.stringify,tk=JSON.parse;class tS{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let r={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),tv(r))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let r=tk(i);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let tI="ClerkJS:";function tU(e=""){throw Error(`${tI} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tA(e){throw Error(`${tI} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tC(e){throw Error(`${tI} You need to start a ${e} flow by calling ${e}.create() first.`)}function tP(e,t){throw Error(`${tI} Strategy "${t}" is not a valid strategy for ${e}.`)}function tT(e){throw Error(`${tI} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tO(e=""){throw Error(`${tI} Missing '${e}' option`)}function tE(e,t){throw Error(`${tI} Response: ${e||0} not supported yet.
17
+ For more information contact us at ${t}`)}function tx(e){throw Error(`${tI} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tR(e="",t){let{async:i,defer:r,beforeLoad:n,crossOrigin:s,nonce:a}=t||{};return tr(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");s&&l.setAttribute("crossorigin",s),l.async=i||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=a,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tF(e){return window.turnstile||await tM(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tM(e){try{return await tR("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function tz(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tN=async e=>{let t,i,r,n,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:d,closeModal:h,openModal:u}=e,p=await tF(l),f=[],m="",g="",_=s,w=0,y=null,b="invisible";if(c&&d){y=a,n=c,b="modal";try{await u?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:s,size:a}=tz(e);t=n,r=s,i=a}}if(!n&&"smart"===a){let e=document.getElementById(B);if(e){b="smart",y="smart",n=`#${B}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tz(e);t=s,r=a,i=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){b="invisible",_=o,y="invisible",n=`.${J}`;let e=document.createElement("div");e.classList.add(J),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(n,{sitekey:_,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){h?.(),s([e,o])},"before-interactive-callback":()=>{if(d){let e=document.querySelector(d);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(B);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===i?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(f.push(e),w<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{n&&!document.querySelector(n)?a([f.join(","),o]):(p.reset(o),w++)},250):a([f.join(","),o])},"unsupported-callback":function(){return a(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){a([e,void 0])}});try{[m,g]=await v(),p.remove(g)}catch([e,t]){throw t&&p.remove(t),{captchaError:e}}finally{if("modal"===b&&h?.(),"invisible"===b){let e=document.querySelector(`.${J}`);e&&document.body.removeChild(e)}if("smart"===b){let e=document.getElementById(B);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:m,captchaWidgetType:y}},tW=e=>{let t=e.__internal_environment,i=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:i,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class tD{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:r,nonce:n}=tW(this.clerk);return i&&t&&r?{...await tN({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||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:t,canUseCaptcha:i,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:s,nonce:a}=tW(this.clerk);if(i&&t&&s){let i=await tN({captchaProvider:n,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...i,captchaAction:"verify"}:i}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){if("undefined"==typeof document)throw new y("Captcha is not supported in non-browser environments",{code:"captcha_unavailable"});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 tL{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tL.instance||(tL.instance=new tL(iZ,tD)),tL.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new y("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 t()}catch(r){let i;if(!S(r)||b(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>i=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{i(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class t${static clerk;id;pathRoot="";static get fapiClient(){return t$.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tL.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;t$.fapiClient||function(){throw Error(`${tI} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{i=await t$.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new y(t?.message||t,{code:"network_error"});if(!c())return e8.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:s,statusText:a,headers:o}=i;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&!t.skipUpdateClient&&this._updateClient(n),s>=200&&s<=299)return n;if(s>=400){let e=n?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"dev_browser_unauthenticated"===i?await t$.clerk.__internal_handleUnauthenticatedDevBrowser():401===s&&"requires_captcha"!==i&&await t$.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((i=t$.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=t$.clerk.frontendApi.replace("clerk.","");throw new k(`Clerk: Production Keys are only allowed for domain "${i}".
18
+ API Error: ${n}`,{data:t,status:e})}}(s,e);let r={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new k(t||a,r)}return null}static _updateClient(e){let t=iY(e);t&&t$.clerk&&t$.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let i=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?i.replace(/[^/]$/,"$&/")+encodeURIComponent(e):i}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await t$._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:r,path:n}=e,s=await t$._fetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await t$._baseFetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}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=t$.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tj(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tB extends t${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?tj(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tj(e.last_used_at):null,this.updatedAt=tj(e.updated_at),this.createdAt=tj(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 tJ extends t${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?tj(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}}}(g=_||(_={}))[g.None=0]="None",g[g.Mutable=1]="Mutable",g[g.Watching=2]="Watching",g[g.RecursedCheck=4]="RecursedCheck",g[g.Recursed=8]="Recursed",g[g.Dirty=16]="Dirty",g[g.Pending=32]="Pending";let tK=[],{link:tV,unlink:tq,propagate:tH,checkDirty:tG,endTracking:tQ,startTracking:tX,shallowPropagate:tY}=function({update:e,notify:t,unwatched:i}){let r=0;return{link:function(e,t){let i,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==n?n.nextDep:t.deps)&&i.dep===e){i.version=r,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===r&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==n?n.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:n,propagate:function(e){let i,r=e.nextSub;e:for(;;){let n=e.sub,s=n.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let r=t.deps;do{if(r===e)return!0;if(r===i)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|s,s&=1):s=0:n.flags=-9&s|32:s=0:n.flags=32|s,2&s&&t(n),1&s)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:r,prev:i},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(t,i){let r,n=0;e:for(;;){let a=t.dep,o=a.flags,l=!1;if(16&i.flags)l=!0;else if((17&o)==17){if(e(a)){let e=a.subs;void 0!==e.nextSub&&s(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=a.deps,i=a,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=r.value,r=r.prev):t=a,l){if(e(i)){o&&s(a),i=t.sub;continue}}else i.flags&=-33;if(i=t.sub,void 0!==t.nextDep){t=t.nextDep;continue e}l=!1}return l}},endTracking:function(e){let t=e.depsTail,i=void 0!==t?t.nextDep:e.deps;for(;void 0!==i;)i=n(i,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function n(e,t=e.sub){let r=e.dep,s=e.prevDep,a=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==a?a.prevDep=s:t.depsTail=s,void 0!==s?s.nextDep=a:t.deps=a,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&i(r),a}function s(e){do{let i=e.sub,r=e.nextSub,n=i.flags;(48&n)==32&&(i.flags=16|n,2&n&&t(i)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?t6(e):t9(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let r=t.subs;void 0!==r?e(r.sub):tK[t1++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tq(t,e);while(void 0!==t)}}else"previousValue"in e||it.call(e)}}),tZ=0,t0=0,t1=0;function t3(t){let i=e;return e=t,i}function t2(e){return ie.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t4(e){return t8.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t5(i){let r={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tV(r,e):void 0!==t&&tV(r,t);let n=t3(r);try{r.fn()}finally{t3(n)}return it.bind(r)}function t6(e){let t=t3(e);tX(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t3(t),tQ(e)}}function t9(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t7(){for(;t0<t1;){let e=tK[t0];tK[t0++]=void 0,function e(t,i){if(16&i||32&i&&tG(t.deps,t)){let e=t3(t);tX(t);try{t.fn()}finally{t3(e),tQ(t)}return}32&i&&(t.flags=-33&i);let r=t.deps;for(;void 0!==r;){let t=r.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),r=r.nextDep}}(e,e.flags&=-65)}t0=0,t1=0}function t8(){let i=this.flags;if(16&i||32&i&&tG(this.deps,this)){if(t6(this)){let e=this.subs;void 0!==e&&tY(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?tV(this,e):void 0!==t&&tV(this,t),this.value}function ie(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tH(e),tZ||t7())}}else{let t=this.value;if(16&this.flags&&t9(this,t)){let e=this.subs;void 0!==e&&tY(e)}return void 0!==e&&tV(this,e),t}}function it(){let e=this.deps;for(;void 0!==e;)e=tq(e,this);let t=this.subs;void 0!==t&&tq(t),this.flags=0}function ii(e){let{pageSize:t,initialPage:i,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:n+"",offset:((i??1)-1)*n+""})}class ir{static #W="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${ir.#W}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},r={...i,payer_type:"organization"===t?"org":"user"};return await t$._fetch({path:`${ir.#W}/plans`,method:"GET",search:ii(r)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new iT(e))}})};getPlan=async e=>new iT(await t$._fetch({path:`${ir.#W}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await t$._fetch({path:ir.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new ix(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await t$._fetch({path:ir.path("/statements",{orgId:t}),method:"GET",search:ii(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new iO(e))}})};getStatement=async e=>new iO((await t$._fetch({path:ir.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await t$._fetch({path:ir.path("/payment_attempts",{orgId:t}),method:"GET",search:ii(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ik(e))}})};getPaymentAttempt=async e=>new ik(await t$._fetch({path:ir.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new ib((await t$._fetch({path:ir.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let is=t2({resource:null}),ia=t2({error:null}),io=t2({status:"idle"}),il=t4(()=>{let e=is().resource,t=ia().error,i=io().status;return{errors:iw(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),ic=t2({resource:null}),id=t2({error:null}),ih=t2({status:"idle"}),iu=t4(()=>{let e=ic().resource,t=id().error,i=ih().status;return{errors:iw(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:i,signUp:e?e.__internal_future:null}}),ip=t2({resource:null}),im=t2({error:null}),ig=t2({status:"idle"}),i_=t4(()=>{let e=ip().resource,t=im().error,i=ig().status;return{errors:iw(t,{emailAddress:null}),fetchStatus:i,waitlist:e}});function iw(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!S(e))return i.raw=[e],i.global=[R(e)],i;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(i.raw?i.raw.push(e):i.raw=[e],r(e)){let t=Q(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[R(e)]),i}class iy extends t${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=tj(e.created_at)),e.updated_at&&(this.updatedAt=tj(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 ib extends t${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 iC(e.payment_method):void 0,this.plan=new iT(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tc(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tj(e.free_trial_ends_at)),this.payer=new iy(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tr(()=>this._basePatch({path:ir.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!S(e)||t>=4)return!1;let i=e?.status,r=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||r}})}class iv{resource=new ib(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,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 ib.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new ib(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:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await ib.clerk.setActive({session:ib.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var r,n,s;return void 0===ib.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tZ,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),i?.(),--tZ||t7(),++tZ;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{s.delete(e),n.fetchSignal({status:"idle"}),--tZ||t7()}})();return s.set(e,a),a})(e,t,i)}}class ik extends t${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=to(e.amount),this.paidAt=e.paid_at?tj(e.paid_at):null,this.failedAt=e.failed_at?tj(e.failed_at):null,this.updatedAt=tj(e.updated_at),this.paymentMethod=e.payment_method?new iC(e.payment_method):null,this.subscriptionItem=new iR(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let iS="/payment_methods",iI=async e=>{let{orgId:t,...i}=e;return new iP((await t$._fetch({path:ir.path(`${iS}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},iU=async e=>{let{orgId:t,...i}=e;return new iC((await t$._fetch({path:ir.path(iS,{orgId:t}),method:"POST",body:i}))?.response)},iA=async e=>{let{orgId:t,...i}=e??{};return await t$._fetch({path:ir.path(iS,{orgId:t}),method:"GET",search:ii(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new iC(e))}})};class iC extends t${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:tj(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tj(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new i1((await t$._fetch({path:ir.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await t$._fetch({path:ir.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class iP extends t${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 iT extends t${id;name;fee=null;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=e.fee?to(e.fee):null,this.annualFee=e.annual_fee?to(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?to(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 rm(e))),this}}class iO extends t${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=tj(e.timestamp),this.totals=tc(e.totals),this.groups=e.groups.map(e=>new iE(e))),this}}class iE{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tj(e.timestamp),this.items=e.items.map(e=>new ik(e))),this}}class ix extends t${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=tj(e.created_at),this.updatedAt=e.updated_at?tj(e.updated_at):null,this.activeAt=tj(e.active_at),this.pastDueAt=e.past_due_at?tj(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:to(e.next_payment.amount),date:tj(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new iR(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class iR extends t${id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;credits;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new iT(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tj(e.created_at),this.pastDueAt=e.past_due_at?tj(e.past_due_at):null,this.periodStart=tj(e.period_start),this.periodEnd=e.period_end?tj(e.period_end):null,this.canceledAt=e.canceled_at?tj(e.canceled_at):null,this.amount=e.amount?to(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:to(e.credit.amount)}:void 0,this.credits=e.credits?tl(e.credits):void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new i1((await t$._fetch({path:ir.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let iF="token:update",iM="user:signOut",iz="environment:update",iN="session:tokenResolved",iW=p(),iD={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=iD.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:r}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let r=e.slice(t.length+1);return i&&r.endsWith(`-${i}`)&&(r=r.slice(0,-(i.length+1))),r||void 0}};var iL=s(2105),i$='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 ij=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(i);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},iB=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=ij(i$,{name:"clerk-timers"});if(s?.addEventListener("message",n),!s)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:iL.t};let a=()=>{s||(s=ij(i$,{name:"clerk-timers"}),s?.addEventListener("message",n))};return{setTimeout:(e,n)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),r(s,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{a();let o=t();return i.set(o,e),r(s,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{a(),i.delete(e),r(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),r(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};var iJ=s(5945),iK=s.n(iJ);class iV{lock=(function(e){let t=new(iK());return{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=iB();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}let iq="clerk",iH={broadcast:!0},iG={broadcast:!1};class iQ{prefix;data;static fromKey(e){let[t,i,r=""]=e.split("::");return new iQ(t,{audience:r,tokenId:i})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let iX=((e=iq)=>{let t=new Map,i=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{a(e)}),r));n();let s=i=>{n();let r=new iQ(e,i),s=t.get(r.toKey());if(!s)return;let a=Math.floor(Date.now()/1e3)-s.createdAt;if((s.expiresIn??1/0)-a<=5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),void 0!==s.refreshTimeoutId&&clearTimeout(s.refreshTimeoutId),t.delete(r.toKey());return}return{entry:s.entry}},a=async({data:e})=>{let t,r=iD.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void e8.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:i,template:e.template,traceId:e.traceId},"tokenCache");try{t=new r5({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){e8.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,a=t.jwt?.claims?.exp;if(!n||!a)return void e8.warn("Token missing iat/exp claim, skipping cache update",{tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=s({tokenId:e.tokenId});if(t){let r=await t.entry.tokenResolver,s=r.jwt?.claims?.iat;if(s&&s>=n)return void e8.debug("Ignoring older token broadcast",{existingIat:s,incomingIat:n,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){e8.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e8.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:i,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},iG)},o=(n,s=iH)=>{let a=new iQ(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId),t.delete(a))};n.tokenResolver.then(e=>{n.resolvedToken=e;let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let a=t.exp,o=t.iat,d=a-o;l.createdAt=o,l.expiresIn=d;let h=setTimeout(c,1e3*d);l.timeoutId=h,"function"==typeof h.unref&&h.unref();let u=d-15-2;if(u>0&&n.onRefresh){let e=setTimeout(()=>{n.onRefresh?.()},1e3*u);l.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let p=r;if(p&&s.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=iD.extractTemplate(n.tokenId,e,s),o=iD.build(e,a,s);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e8.info("Broadcasting token update to other tabs",{organizationId:s,sessionId:e,tabId:i,template:a,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:n.tokenId,tokenRaw:r,traceId:t};p.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:s,set:e=>{n(),o(e,iH)},size:()=>t.size}})();function iY(e){if(!e)return;let t=e.client||e.meta?.client;return t?iZ.getOrCreateInstance().fromJSON(t):void 0}class iZ extends t${static instance;pathRoot="/client";sessions=[];signUp=new rZ;signIn=new rQ;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iZ.instance||(iZ.instance=new iZ(e)),iZ.instance}static clearInstance(){iZ.instance=null}static isClientResource(e){return!!e&&e instanceof iZ}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(()=>{iX.clear(),this.id="",this.sessions=[],this.signUp=new rZ(null),this.signIn=new rQ(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=>(iX.clear(),e))}resetSignIn(){this.signIn=new rQ(null),iW.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new rZ(null),iW.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return t$.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 r$(e)),e.sign_up&&this.signUp instanceof rZ&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new rZ(e.sign_up),e.sign_in&&this.signIn instanceof rQ&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new rQ(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tj(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tj(e.created_at||void 0),this.updatedAt=tj(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 i0 extends t${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 i1{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 i3 extends t${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}}}function i2({delayInMs:e}={delayInMs:1e3}){let t,i=iB(),r=!1,n=()=>{t&&(i.clearTimeout(t),i.cleanup()),r=!0},s=async a=>{r=!1,await a(n),r||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:n}}class i4 extends t${id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,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:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=i2();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=i2();return{startEnterpriseSSOLinkFlow:async({redirectUrl:i})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:i})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rs(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rg(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 i5=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function i6(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new T("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new T(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new T(t.message,{code:"passkey_registration_cancelled"}):i8(t),publicKeyCredential:null}}}let i9=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 i7({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:i9.createAbortSignal()});if(!i)return{error:new T("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:i,error:null}}catch(e){var i;return{error:"NotAllowedError"===(i=e).name?new T(i.message,{code:"passkey_retrieval_cancelled"}):i8(i),publicKeyCredential:null}}}function i8(e){return"AbortError"===e.name?new T(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new T(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function re(e){let t=rn(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:rn(e.id)}));return{...e,allowCredentials:i,challenge:t}}function rt(e){return{type:e.type,id:e.id,rawId:rr(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function ri(e){let t=e.response;return{...rt(e),response:{clientDataJSON:rr(t.clientDataJSON),authenticatorData:rr(t.authenticatorData),signature:rr(t.signature),userHandle:t.userHandle?rr(t.userHandle):null}}}let rr=i5.encode.bind(i5),rn=i5.decode.bind(i5);class rs extends t${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===t$.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=tj(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class ra extends rs{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=rn((t=JSON.parse(e.nonce)).user.id),r=rn(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:rn(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class ro{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new rl(e.email_address),this.phoneNumber=new rl(e.phone_number),this.web3Wallet=new rl(e.web3_wallet),this.externalAccount=new rs(e.external_account)):(this.emailAddress=new rl(null),this.phoneNumber=new rl(null),this.web3Wallet=new rl(null),this.externalAccount=new rs(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 rl extends rs{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 rc extends t${id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,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?tj(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rs(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new rd(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 rd extends t${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=tj(e.created_at),this.updatedAt=tj(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()}}}class rh extends t${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 ru extends t${actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!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)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),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 rp extends t${static instance;authConfig=new tJ;displayConfig=new i3;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new nr;organizationSettings=new ru;commerceSettings=new i0;apiKeysSettings=new rh;protectConfig=new rE;static getInstance(){return rp.instance||(rp.instance=new rp),rp.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tJ(e.auth_config),this.displayConfig=new i3(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new ru(e.organization_settings),this.userSettings=new nr(e.user_settings),this.commerceSettings=new i0(e.commerce_settings),this.apiKeysSettings=new rh(e.api_keys_settings),this.protectConfig=new rE(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(iW.emit(iz,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,partitioned_cookies:this.partitionedCookies,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 rf extends t${id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:i}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i}})};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 rs(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 rm extends t${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 rg extends t${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 r_ extends t${id;name=null;publicUrl=null;static async create(e,t={}){let i,r=t;return"string"==typeof t.file?(r=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new r_((await t$._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new r_((await t$._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 rw extends t${id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rw((await t$._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.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:tj(e.verification.expires_at)}:this.verification=null),this}}class ry extends t${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=tj(e.created_at),this.updatedAt=tj(e.updated_at),e.public_user_data&&(this.publicUserData=new rx(e.public_user_data))),this}}class rb extends t${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=tj(e.created_at),this.updatedAt=tj(e.updated_at)),this}}class rv extends t${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 rb(e)),this.createdAt=tj(e.created_at),this.updatedAt=tj(e.updated_at)),this}}class rk extends t${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 rk((await t$._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rk((await t$._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await t$._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:ii(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new rv(e)),total_count:i,has_role_set_migration:r}});getDomains=async e=>await t$._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:ii(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rw(e))}});getDomain=async({domainId:e})=>new rw((await t$._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await t$._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:ii(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ry(e))}});createDomain=async e=>rw.create(this.id,{name:e});getMemberships=async e=>await t$._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:ii({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rI(e))}});getInvitations=async e=>await t$._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:ii(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rS(e))}});addMember=async({userId:e,role:t})=>await t$._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new rI(e?.response));inviteMember=async e=>rS.create(this.id,e);inviteMembers=async e=>rS.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await t$._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new rI(e?.response));removeMember=async e=>await t$._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rI(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await t$._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rk(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await t$._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new rk(e?.response)))};initializePaymentMethod=e=>iI({...e,orgId:this.id});addPaymentMethod=e=>iU({...e,orgId:this.id});getPaymentMethods=e=>iA({...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=tj(e.created_at),this.updatedAt=tj(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:t}=e||{},i=(await t$._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class rS extends t${id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new rS((await t$._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:r}=t;return((await t$._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new rS(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=tj(e.created_at),this.updatedAt=tj(e.updated_at)),this}}class rI extends t${id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await t$._fetch({path:"/me/organization_memberships",method:"GET",search:ii({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rI(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 rk(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rx(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tj(e.created_at),this.updatedAt=tj(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(`${tI} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rU extends t${id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await t$._fetch({path:"/me/organization_suggestions",method:"GET",search:ii(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rU(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=tj(e.created_at),this.updatedAt=tj(e.updated_at)),this}}function rA(){return o()&&"function"==typeof window.PublicKeyCredential}async function rC(){try{return rA()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rP(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rT extends t${id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return t$._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rT(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...rt(t),response:{clientDataJSON:rr(i.clientDataJSON),attestationObject:rr(i.attestationObject),transports:i.getTransports()}});return t$._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rT(e?.response))}static async registerPasskey(){let e=rT.clerk.__internal_isWebAuthnSupported||rA,t=rT.clerk.__internal_createPublicCredentials||i6,i=rT.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rP;if(!e())throw new T("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,s=n?.publicKey;if(s||tx("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new T("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:a,error:o}=await t(s);if(!a)throw o;return this.attemptVerification(r.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new i1((await t$._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?tj(e.last_used_at):null,this.createdAt=tj(e.created_at),this.updatedAt=tj(e.updated_at),e.verification&&(this.verification=new ra(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 rO extends t${id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,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:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};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 rs(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rg(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 rE extends t${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 rx{firstName;lastName;imageUrl;hasImage;identifier;userId;username;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.username=e.username),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,username:this.username}}}let rR={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"}},rF=new Set(["first_factor","second_factor","multi_factor"]),rM=new Set(["strict_mfa","strict","moderate","lax"]),rz=new Set(["o","org","organization"]),rN=new Set(["u","user"]),rW=(e,t)=>{let{org:i,user:r}=rD(e),[n,s]=t.split(":"),a=void 0!==s,o=s||n;if(a&&!rz.has(n)&&!rN.has(n))throw Error(`Invalid scope: ${n}`);if(a){if(rz.has(n))return i.includes(o);if(rN.has(n))return r.includes(o)}return[...i,...r].includes(o)},rD=e=>{let t=[],i=[];if(!e)return{org:t,user:i};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),s=n.indexOf(":");if(-1===s)throw Error(`Invalid claim element (missing colon): ${n}`);let a=n.slice(0,s),o=n.slice(s+1);"o"===a?t.push(o):"u"===a?i.push(o):("ou"===a||"uo"===a)&&(t.push(o),i.push(o))}return{org:t,user:i}};class rL extends t${status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rs(null);secondFactorVerification=new rs(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new r$(e.session),this.level=e.level,this.supportedFirstFactors=ee(e.supported_first_factors),this.supportedSecondFactors=ee(e.supported_second_factors),this.firstFactorVerification=new rs(e.first_factor_verification),this.secondFactorVerification=new rs(e.second_factor_verification)),this}}class r$ extends t${pathRoot="/client/sessions";static #D=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof r$}constructor(e){super(),this.fromJSON(e),this.#L(this.lastActiveToken)}end=()=>(iX.clear(),this._basePost({action:"end"}));remove=()=>(iX.clear(),this._basePost({action:"remove"}));_touchPost=async({skipUpdateClient:e}={skipUpdateClient:!1})=>{let t=await t$._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId}},{skipUpdateClient:e});return this.fromJSON(t?.response||t),t};touch=async()=>(await this._touchPost(),this.lastActiveToken&&iW.emit(iF,{token:this.lastActiveToken}),this);__internal_touch=async()=>iY(await this._touchPost({skipUpdateClient:!0}));clearCache=()=>iX.clear();getToken=async e=>{try{let t=await tr(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!E(e)||e?.status===429)&&(c()?t<=8:t<=3)});if(!t&&!c())throw new U("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!c())throw new U("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,i=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:i?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let i=((e,t)=>{let{features:i,plans:r}=t;return e.feature&&i?rW(i,e.feature):e.plan&&r?rW(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&i&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&rM.has(e),n="object"==typeof e&&(t=e.level,rF.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?rR[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:r,afterMinutes:n}=i(),[s,a]=t,o=-1!==s?n>s:null,l=-1!==a?n>a:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==a?l:o;case"multi_factor":return -1===a?o:o&&l}})(e,t);return[i||r,n].some(e=>null===e)?[i||r,n].some(e=>!0===e):[i||r,n].every(e=>!0===e)})(e)};#L=e=>{if(e){let t=this.#$();iX.set({tokenId:t,tokenResolver:Promise.resolve(e),onRefresh:()=>this.#j(void 0,this.lastActiveOrganizationId,t,!0)})}};#$(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return iD.build(this.id,e,i)}startVerification=async({level:e})=>new rL((await t$._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tP("Session.prepareFirstFactorVerification",e.strategy)}return new rL((await t$._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(ri(e.publicKeyCredential))}:{...e},new rL((await t$._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=r$.clerk.__internal_isWebAuthnSupported||rA,i=r$.clerk.__internal_getPublicCredentials||i7;if(!t())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?re(JSON.parse(e)):null;r||tx("get");let{publicKeyCredential:n,error:s}=await i({publicKeyOptions:r,conditionalUI:!1});if(!n)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rL((await t$._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rL((await t$._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=tj(e.expire_at),this.abandonAt=tj(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tj(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tj(e.created_at),this.updatedAt=tj(e.updated_at),this.user=new r8(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rx(e.public_user_data)),this.lastActiveToken=e.last_active_token?new r5(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){let t;if(!this.user)return null;let{skipCache:i=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,s=this.#$(r,n),a=i?void 0:iX.get({tokenId:s}),o=!r&&n===this.lastActiveOrganizationId;if(a){let e=a.entry.resolvedToken??await a.entry.tokenResolver;o&&e.getRawString()&&iW.emit(iF,{token:e}),t=e.getRawString()||null}else if(l())t=await this.#B(r,n,s,o,i);else throw new y("Browser is offline, skipping token fetch",{code:"network_error"});if(null===t&&!c())throw new y("Network request failed while offline",{code:"network_error"});return t}#J(e,t,i){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=e?{}:{organizationId:t??null},s=this.lastActiveToken?.getRawString();return r5.create(r,n,i?{debug:"skip_cache"}:void 0).catch(e=>{if(I.is(e)&&s)return r5.create(r,{...n},{expired_token:s});throw e})}#K(e,t){!t||e.getRawString()&&(iW.emit(iF,{token:e}),e.jwt&&(this.lastActiveToken=e,iW.emit(iN,null)))}#B(e,t,i,r,n){e8.info("Fetching new token from API",{organizationId:t,template:e,tokenId:i},"session");let s=this.#J(e,t,n);return iX.set({tokenId:i,tokenResolver:s,onRefresh:()=>this.#j(e,t,i,r)}),s.then(e=>{let t=e.getRawString();if(!t)throw new y("Token fetch returned empty response",{code:"network_error"});return this.#K(e,r),t})}#j(e,t,i,r){r$.#D.has(i)||(r$.#D.add(i),this.#J(e,t,!1).then(n=>{n.getRawString()&&(iX.set({tokenId:i,tokenResolver:Promise.resolve(n),onRefresh:()=>this.#j(e,t,i,r)}),this.#K(n,r))}).catch(e=>{e8.warn("Background token refresh failed",{error:e,tokenId:i},"session")}).finally(()=>{r$.#D.delete(i)}))}get currentTask(){let[e]=this.tasks??[];return e}}class rj extends t${pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=t$.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rj(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tj(e.expire_at),this.abandonAt=tj(e.abandon_at),this.lastActiveAt=tj(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}s(4821);let rB=(e,t,i)=>{let{onValidation:r=iL.t,onValidationComplexity:n=iL.t}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let i=e.allowed_special_characters.replace("[","\\[");i=i.replace("]","\\]"),t=RegExp(`[${i}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:i,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=i,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,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,t),l=(({min_zxcvbn_strength:e,onResult:t})=>i=>r=>{let n=i(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,i)=>{let{onValidation:d=r,onValidationComplexity:h=n}=i||{};if(!a)return;let u=o(t);h(0===Object.keys(u).length),c={...c,complexity:u},s&&e().then(e=>{let i=l(e)(t);d({...c={...c,strength:i},strength:i})}),c.complexity&&0===Object.keys(c.complexity).length&&s||d(c)}};function rJ(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rK(e,t,i,r,n){if(!e.client||!r.popup)return;let s=rJ(e.frontendApi),{redirectUrl:a}=r,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${s}/popup-callback`),d=e.buildUrlWithAuth(`${s}/popup-callback?return_url=${encodeURIComponent(l)}`),h=async t=>{if(t.origin!==s)return;let i=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),i=!0}else t.data.return_url&&(e.navigate(t.data.return_url),i=!0);i&&window.removeEventListener("message",h)};window.addEventListener("message",h),await i({...r,redirectUrlComplete:c,redirectUrl:d},n)}function rV(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=rJ(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",i),n.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(n.toString()),a=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function rq(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rJ(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),i()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rH(e,t){iW.emit("resource:error",{resource:e,error:null}),iW.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return iW.emit("resource:error",{resource:e,error:t}),{error:t}}finally{iW.emit("resource:fetch",{resource:e,status:"idle"})}}let rG=()=>{var e;return(e=new ts,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:i,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...n},graphs:s}),r})}).loadZxcvbn};class rQ extends t${pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new rs(null);secondFactorVerification=new rs(null);identifier=null;createdSessionId=null;userData=new ne(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e8.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rX(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e8.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},i=tf();if(i&&(t.locale=i),this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tD(rQ.clerk),i=await e.managedOrInvisible({action:"signin"});if(!i)throw new y("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(e8.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={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":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tP("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return e8.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(ri(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=i2();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||tC("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e[a].status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(e8.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e8.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=rQ.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tE(c,rQ.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,ej);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tO("popup"),rK(rQ.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:r,strategy:n="web3_metamask_signature",walletName:s}=e||{},a=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tO("generateSignature"),"solana"!==a||s||tO("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||tT("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tT("SignIn");try{t=await r({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await r({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await ty().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ty().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ty().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ty().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ty().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ty().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ty().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ty().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await ty().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>ty().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=rQ.clerk.__internal_isWebAuthnSupported||rA,r=rQ.clerk.__internal_getPublicCredentials||i7,n=rQ.clerk.__internal_isWebAuthnAutofillSupported||rC;if(!i())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tI} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:s}=this.firstFactorVerification,a=s?re(JSON.parse(s)):null;a||tx("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rQ.clerk.__internal_environment?.userSettings.passwordSettings)return rB(rG(),{...rQ.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ee(e.supported_first_factors),this.supportedSecondFactors=ee(e.supported_second_factors),this.firstFactorVerification=new rs(e.first_factor_verification),this.secondFactorVerification=new rs(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new ne(e.user_data),this.clientTrustState=e.client_trust_state??void 0),iW.emit("resource:update",{resource:this}),this}clientBypass(){return rQ.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=rQ.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&rQ.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=rQ.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:Z(this.supportedFirstFactors),supported_second_factors:Z(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 rX{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(!n())return null;const e=eE("__clerk_status"),t=eE("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==rQ.clerk.client&&rQ.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.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),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#V=!1;#q;constructor(e){this.#q=e}get id(){return this.#q.id}get identifier(){return this.#q.identifier}get createdSessionId(){return this.#q.createdSessionId}get userData(){return this.#q.userData}get status(){return this.#q.status||"needs_identifier"}get supportedFirstFactors(){return this.#q.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#q.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#q.firstFactorVerification.status}get existingSession(){if("failed"===this.#q.firstFactorVerification.status&&this.#q.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#q.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#q.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#q.firstFactorVerification}get secondFactorVerification(){return this.#q.secondFactorVerification}get canBeDiscarded(){return this.#V}async sendResetPasswordEmailCode(){if(!this.#q.id)throw Error("Cannot reset password without a sign in.");return rH(this.#q,async()=>{let e=this.#q.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new y("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#q.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#q.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return rH(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.#q.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new y("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:i}=e;await this.#q.__internal_basePost({body:{phoneNumberId:i,strategy:"reset_password_phone_code"},action:"prepare_first_factor"})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=rQ.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&rQ.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=rQ.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||rQ.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new tD(rQ.clerk),i=await t.managedOrInvisible({action:"signin"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n={...e,captchaToken:t,captchaWidgetType:i,captchaError:r,locale:tf()||void 0};await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})}async create(e){return rH(this.#q,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 rH(this.#q,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#q.identifier,r=tf();await this.#q.__internal_basePost({path:this.#q.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#q.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rH(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new y("Email code factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:r}=e;if(!this.#q.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rH(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new y("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.#q.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rH(this.#q,async()=>{let{run:e,stop:t}=i2();await new Promise((i,r)=>{e(async()=>{try{let e=await this.#q.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.#q.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#q.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rH(this.#q,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new y("Phone code factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,popup:n,oidcPrompt:s,enterpriseConnectionId:a,identifier:o}=e;return rH(this.#q,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:rQ.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rV(rQ.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#q.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#q.firstFactorVerification;"unverified"===c&&d&&(n?(await rq(rQ.clerk,{popup:n,externalVerificationRedirectURL:d}),await this.#q.reload()):ej(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return rH(this.#q,async()=>{let r,n,s;switch(i){case"metamask":r=await ty().getMetamaskIdentifier(),n=ty().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await ty().getCoinbaseWalletIdentifier(),n=ty().generateSignatureWithCoinbaseWallet;break;case"base":r=await ty().getBaseIdentifier(),n=ty().generateSignatureWithBase;break;case"okx_wallet":r=await ty().getOKXWalletIdentifier(),n=ty().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new y("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await ty().getSolanaIdentifier(e.walletName),n=t=>ty().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:r});let a=this.#q.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new y("Web3 first factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new y("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await n({identifier:r,nonce:o,provider:i});else throw e}await this.#q.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=rQ.clerk.__internal_isWebAuthnSupported||rA,r=rQ.clerk.__internal_getPublicCredentials||i7,n=rQ.clerk.__internal_isWebAuthnAutofillSupported||rC;if(!i())throw new T("Passkeys are not supported",{code:"passkey_not_supported"});return rH(this.#q,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new y("Passkey factor not found",{code:"factor_not_found"});await this.#q.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,i=e?re(JSON.parse(e)):null;if(!i)throw new y("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await n());let{publicKeyCredential:a,error:o}=await r({publicKeyOptions:i,conditionalUI:s});if(!a)throw new T(o.message,{code:"passkey_retrieval_failed"});await this.#q.__internal_basePost({body:{publicKeyCredential:JSON.stringify(ri(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rH(this.#q,async()=>{let e=this.#q.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new y("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#q.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return rH(this.#q,async()=>{let e=this.#q.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new y("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#q.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor"})})}async verifyMFAEmailCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eE("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#q.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rH(this.#q,async()=>{rQ.clerk.client&&!rQ.clerk.client.sessions.some(e=>e.id===this.#q.createdSessionId)&&await rQ.clerk.client.reload(),this.#V=!0,await rQ.clerk.setActive({session:this.#q.createdSessionId,navigate:t})})}reset(){if(!rQ.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#V=!0,rQ.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#q.supportedFirstFactors)return null;if(t){let i=this.#q.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#q.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.#q.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#q.identifier);if(r)return r;let n=this.#q.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rY(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class rZ extends t${pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new ro(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 t=this._status;this._status=e,e&&t!==e&&e8.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new r2(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e8.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tf();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tD(rZ.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new y("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:rY(t)})};prepareVerification=e=>(e8.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e8.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:t}=i2();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||tC("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};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:t,strategy:i="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:i})};authenticateWithWeb3=async e=>{let t,{generateSignature:i,identifier:r,unsafeMetadata:n,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tO("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||tT("SignUp");try{t=await i({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await ty().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:ty().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await ty().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:ty().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await ty().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:ty().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await ty().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:ty().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let r=await ty().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>ty().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=rZ.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:n,redirectUrl:h,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return s&&this.id?this.update(e):this.create(e)},{verifications:p}=await u().catch(async e=>{if(S(e)&&O(e))return await rZ.clerk.__internal_environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tE(m,rZ.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,ej);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tO("popup"),rK(rZ.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rY(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rZ.clerk.__internal_environment?.userSettings.passwordSettings)return rB(rG(),{...rZ.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};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 ro(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),iW.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__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 rZ.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=rZ.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=rZ.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||r1(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>t$._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new r4(e)))}let r0=new Set(["email_link","email_code","phone_code"]);function r1(e){return!!e&&(r0.has(e)||e.startsWith("web3_"))}class r3{#q;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#q=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#q.verifications.emailAddress}get phoneNumber(){return this.#q.verifications.phoneNumber}get web3Wallet(){return this.#q.verifications.web3Wallet}get externalAccount(){return this.#q.verifications.externalAccount}get emailLinkVerification(){if(!n())return null;let e=eE("__clerk_status"),t=eE("__clerk_created_session");if(!e||!t)return null;let i="verified"===e&&void 0!==rZ.clerk.client&&rZ.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}}class r2{verifications;#V=!1;#q;constructor(e){this.#q=e,this.verifications=new r3(this.#q,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#q.id}get requiredFields(){return this.#q.requiredFields}get optionalFields(){return this.#q.optionalFields}get missingFields(){return this.#q.missingFields}get status(){return this.#q.status||"missing_requirements"}get username(){return this.#q.username}get firstName(){return this.#q.firstName}get lastName(){return this.#q.lastName}get emailAddress(){return this.#q.emailAddress}get phoneNumber(){return this.#q.phoneNumber}get web3Wallet(){return this.#q.web3wallet}get hasPassword(){return this.#q.hasPassword}get unsafeMetadata(){return this.#q.unsafeMetadata}get createdSessionId(){return this.#q.createdSessionId}get createdUserId(){return this.#q.createdUserId}get abandonAt(){return this.#q.abandonAt}get legalAcceptedAt(){return this.#q.legalAcceptedAt}get locale(){return this.#q.locale}get unverifiedFields(){return this.#q.unverifiedFields}get isTransferable(){return"transferable"===this.#q.verifications.externalAccount.status&&this.#q.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#q.verifications.externalAccount.status||"unverified"===this.#q.verifications.externalAccount.status)&&this.#q.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#q.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#q.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#V}shouldBypassCaptchaForAttempt(e){let t=rZ.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=rZ.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||r1(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(rZ.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new tD(rZ.clerk),i=await t.managedOrInvisible({action:"signup"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rY(e.unsafeMetadata):void 0,locale:e.locale??tf()};await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})}async create(e){return rH(this.#q,async()=>{await this._create(e)})}async update(e){return rH(this.#q,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rY(e.unsafeMetadata):void 0};await this.#q.__internal_basePatch({path:this.#q.pathRoot,body:t})})}async password(e){return rH(this.#q,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rY(e.unsafeMetadata):void 0};this.#q.id?await this.#q.__internal_basePatch({body:n}):await this.#q.__internal_basePost({path:this.#q.pathRoot,body:n})})}async sendEmailCode(){return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rH(this.#q,async()=>{await this.#q.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return rH(this.#q,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#q.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification"})})}async waitForEmailLinkVerification(){return rH(this.#q,async()=>{let{run:e,stop:t}=i2();await new Promise((i,r)=>{e(()=>this.#q.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rH(this.#q,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken({strategy:t}),u=i;try{new URL(i)}catch{u=window.location.origin+i}let p={redirectUrl:rZ.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:u};if(c){let e=rV(rZ.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.#q.__internal_basePost({path:this.#q.pathRoot,body:{strategy:t,...p,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(S(e)&&O(e))return await rZ.clerk.__internal_environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.#q.verifications.externalAccount;"unverified"===m&&g&&(c?(await rq(rZ.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#q.reload()):ej(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rH(this.#q,async()=>{let e,s,a;switch(n){case"metamask":e=await ty().getMetamaskIdentifier(),s=ty().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ty().getCoinbaseWalletIdentifier(),s=ty().generateSignatureWithCoinbaseWallet;break;case"base":e=await ty().getBaseIdentifier(),s=ty().generateSignatureWithBase;break;case"okx_wallet":e=await ty().getOKXWalletIdentifier(),s=ty().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#q.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:r}),await this.#q.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#q.verifications.web3Wallet;l||tT("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.#q.__internal_basePost({body:{signature:a,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eE("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rH(this.#q,async()=>{if(!this.#q.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#V=!0,await rZ.clerk.setActive({session:this.#q.createdSessionId,navigate:t})})}reset(){if(!rZ.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#V=!0,rZ.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class r4 extends t${id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class r5 extends t${pathRoot="tokens";jwt;static async create(e,t={},i={}){return new r5(await t$._fetch({method:"POST",path:e,body:t,search:i}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tp(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tp(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class r6 extends t${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=tj(e.updated_at),this.createdAt=tj(e.created_at)),this}}class r9 extends t${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=tj(e.updated_at),this.createdAt=tj(e.created_at)),this}}class r7 extends t${advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await t$._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new r7(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class r8 extends t${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 r8}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case i4:return this.primaryEmailAddressId===e.id;case rO:return this.primaryPhoneNumberId===e.id;case nn:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new i4({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rT.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rO({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new nn({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r}=e||{};return new rf((await t$._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new r6((await t$._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new r6((await t$._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new i1((await t$._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r9((await t$._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rY(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=>(iW.emit(iM,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rj.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?r_.delete(`${this.path()}/profile_image`):r_.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>nt.retrieve(e);getOrganizationSuggestions=e=>rU.retrieve(e);getOrganizationMemberships=e=>rI.retrieve(e);getOrganizationCreationDefaults=()=>r7.retrieve();leaveOrganization=async e=>new i1((await t$._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>iI(e);addPaymentMethod=e=>iU(e);getPaymentMethods=e=>iA(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:t,name:i})=>i||[e,t].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 i4(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 rO(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 nn(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 rf(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rT(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rI(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new rc(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=tj(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tj(e.legal_accepted_at)),this.updatedAt=tj(e.updated_at||void 0),this.createdAt=tj(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 ne{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 nt extends t${id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await t$._fetch({path:"/me/organization_invitations",method:"GET",search:ii(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nt(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=tj(e.created_at),this.updatedAt=tj(e.updated_at)),this}}let ni={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 nr extends t${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:{...ni,name:"phone_number"},username:{...ni,name:"username"},web3_wallet:{...ni,name:"web3_wallet"},first_name:{...ni,name:"first_name"},last_name:{...ni,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:{...ni,name:"authenticator_app"},backup_code:{...ni,name:"backup_code"},passkey:{...ni,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,mfa:{required:!1}};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,t])=>t.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,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.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 nn extends t${id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,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:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new rs(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class ns extends t${pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tj(e.updated_at),this.createdAt=tj(e.created_at),iW.emit("resource:update",{resource:this})),this}async join(e){return rH(this,async()=>{await ns.join(e)})}static async join(e){return new ns(await t$._fetch({path:"/waitlist",method:"POST",body:e}))}}function na(e,t){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,r=e,i.organizationMemberships.length!==r.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function no(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(iZ.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(r$.isSessionResource(e)){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let i=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==r?.permissions?.length}(e,t)||(i=e,r=t,!!i.user!=!!r.user||!!i.user&&!!r.user&&na(i.user,r.user))}if(r8.isUserResource(e))return na(e,t)}catch{}return!0}(e,t)?e:t}let nl="__clerk_db_jwt";function nc(e,t){let i=new URL(e),r=i.searchParams.get(nl);i.searchParams.delete(nl);let n=r||t;return n&&i.searchParams.set(nl,n),i}let nd=e=>{let t=new URL(e);return t.searchParams.delete(nl),t},nh=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function nu(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var np=function e(t,i){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=nu({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in n)n[a]&&(s+="; "+a,!0!==n[a]&&(s+="="+n[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+s}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},n=0;n<i.length;n++){var s=i[n].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",nu({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,nu({},this.attributes,t))},withConverter:function(t){return e(nu({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function nf(e){return{get:()=>np.get(e),set(t,i={}){np.set(e,t,i)},remove(t){np.remove(e,t)}}}let nm=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ng(e,t){let i=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return i.setFullYear(i.getFullYear()+t),i}let n_=nf("__clerk_test_etld"),nw=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function ny(){try{return nw.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let nb="__client_uat",nv="__session",nk=e=>{let t=e.usePartitionedCookies(),i=t||tg()||ny()?"None":"Lax",r=nm(i);return{sameSite:i,secure:r,partitioned:t&&r}};async function nS(e){let t;try{t=await eh(e)}catch(o){var i;i=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(i)||(console.log(i),V.add(i));let{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=r(e);t=n.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let nI=e=>{let t=e.usePartitionedCookies(),i=t||tg()||ny()?"None":"Lax",r=nm(i);return{sameSite:i,secure:r,partitioned:t&&r}};class nU{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await nS(e.publishableKey),s=new nU(e,t,n,i,r);return await s.setup(),s}constructor(e,t,r,n,s){this.clerk=e,this.instanceType=n,this.clerkEventBus=s,iW.on(iF,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),iW.on(iM,()=>this.handleSignOut()),iW.on(iz,()=>{this.devBrowser.refreshCookies()}),this.refreshTokenOnFocus(),this.startPollingForToken();const a={usePartitionedCookies:()=>rp.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let r=nf(nb),n=nf(eu(nb,e));return{set:e=>{let s=ng(Date.now(),1),a=t.usePartitionedCookies(),o=a||tg()||ny()?"None":"Strict",l=nm(o),c=a&&l,d=function(e=window.location.hostname,t=n_,r){if(i)return i;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let n=e.split(".");if(1===n.length)return e;for(let e=n.length-2;e>=0;e--){let s=n.slice(e).join(".");if(t.set("1",{...r,domain:s}),"1"===t.get())return t.remove({...r,domain:s}),i=s,s;t.remove({...r,domain:s})}return i=e,e}(void 0,void 0,{sameSite:o,secure:l}),h="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(h=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),r.remove(),n.set(h,{domain:d,expires:s,partitioned:c,sameSite:o,secure:l}),r.set(h,{domain:d,expires:s,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(n.get()||r.get()||"0",10)}})(r,a),this.sessionCookie=((e,t)=>{let i=nf(nv),r=nf(eu(nv,e));return{set:e=>{let n=ng(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=nk(t);o&&(i.remove(),r.remove()),i.set(e,{expires:n,sameSite:s,secure:a,partitioned:o}),r.set(e,{expires:n,sameSite:s,secure:a,partitioned:o})},remove:()=>{let e=nk(t);i.remove(e),r.remove(e),e.partitioned&&(i.remove(),r.remove())},get:()=>r.get()||i.get()}})(r,a),this.activeCookie=(()=>{let e=nf("clerk_active_context"),t={secure:nm("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i,cookieOptions:r}){let n,s,a=(n=nf(nl),s=nf(eu(nl,e)),{get:()=>s.get()||n.get(),set:e=>{let t=ng(Date.now(),1),{sameSite:i,secure:a,partitioned:o}=nI(r);o&&(s.remove(),n.remove()),s.set(e,{expires:t,sameSite:i,secure:a,partitioned:o}),n.set(e,{expires:t,sameSite:i,secure:a,partitioned:o})},remove:()=>{let e=nI(r);s.remove(e),n.remove(e),e.partitioned&&(s.remove(),n.remove())}});function o(){return a.get()}function l(e){a.set(e)}function c(){a.remove()}return{clear:function(){c()},setup:async function e(){var e;let r,n;if(!ew(t))return;i.onBeforeRequest(e=>{let t=o();t&&e?.url&&(e.url=nc(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&l(i)});let s=(r=(e=new URL(window.location.href)).searchParams.get(nl)||"",(n=nd(nh(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",n),r);if(s)return void l(s);if(a.get())return;let c=i.buildUrl({path:"/dev_browser"}),d=await fetch(c.toString(),{method:"POST"});if(!d.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await d.json()).errors);e[0]?tU(e[0].longMessage):tU()}let h=await d.json();l(h?.id)},getDevBrowser:o,setDevBrowser:l,removeDevBrowser:c,refreshCookies:function(){let e=o();e&&l(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r,cookieOptions:a})}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 t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${tI} Missing dev browser. Please contact support.`);return nc(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new iV,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 t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||c()||e8.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(S(e)||b(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(x(e))return void this.clerk.handleUnauthenticated().catch(e3.lQ);this.clerkEventBus.emit(f,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",i=`${e}:${t}`;":"!==i?this.activeCookie.set(i):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,i]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&i===n}getSessionCookie(){return this.sessionCookie.get()}}class nA{clerk;captchaChallenge;timers;constructor(e,t=new tD(e),i=iB()){this.clerk=e,this.captchaChallenge=t,this.timers=i}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 nC=["/client","/waitlist"];class nP{async getBaseFapiProxyOptions(){let e=await t$.clerk.session?.getToken();if(!e)throw new y("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 t$._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:ii({...e,subject:e?.subject??t$.clerk.organization?.id??t$.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new tB(e))}})}async create(e){return new tB(await t$._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??t$.clerk.organization?.id??t$.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tB(await t$._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let nT=new Map;class nO{#F=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#F){if(n())for(let e of(this.#F=!0,t.loaders))try{this.applyLoader(e)}catch(e){q(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void q(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",i=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":r.setAttribute(t,String(i));break;default:q(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),i){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(i?.startsWith("#")){let e=document.getElementById(i.substring(1));if(!e)return void q(`[protect] loader target element not found: ${i}`);e.appendChild(r);return}q(`[protect] loader target is invalid: ${i}`)}}}class nE{signInResourceSignal=is;signInErrorSignal=ia;signInFetchSignal=io;signInSignal=il;signUpResourceSignal=ic;signUpErrorSignal=id;signUpFetchSignal=ih;signUpSignal=iu;waitlistResourceSignal=ip;waitlistErrorSignal=im;waitlistFetchSignal=ig;waitlistSignal=i_;_waitlistInstance;__internal_effect=t5;__internal_computed=t4;constructor(){iW.on("resource:update",this.onResourceUpdated),iW.on("resource:error",this.onResourceError),iW.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new ns(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rQ&&this.signInErrorSignal({error:e.error}),e.resource instanceof rZ&&this.signUpErrorSignal({error:e.error}),e.resource instanceof ns&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rQ){if(nx(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rZ){if(nx(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof ns&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rQ&&this.signInFetchSignal({status:e.status}),e.resource instanceof rZ&&this.signUpFetchSignal({status:e.status}),e.resource instanceof ns&&this.waitlistFetchSignal({status:e.status})}}function nx(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let nR="cannot_render_billing_disabled",nF="cannot_render_user_missing",nM="cannot_render_organizations_disabled",nz="cannot_render_organization_missing",nN="cannot_render_single_session_enabled",nW={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 nD{static version="6.3.1";static sdkMetadata={name:"@clerk/clerk-js",version:"6.3.1"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nE;internal_last_error=null;environment;#H;#G="";#Q;#X;#Y;#Z;#ee;#et=null;#ei;#er;#en;#es="loading";#ea=[];#eo=[];#el={};#ec=null;#ed=0;#eh=p();get __internal_queryClient(){return this.#H||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#H||(this.#H=new e,this.#eh.emit("queryClientStatus","ready"))}),this.#H?{__tag:"clerk-rq-client",client:this.#H}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#G}get version(){return nD.version}set sdkMetadata(e){nD.sdkMetadata=e}get sdkMetadata(){return nD.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#es}get isSatellite(){return!!tm()&&(0,e3.VK)(this.#el.isSatellite,new URL(window.location.href),!1)}get domain(){if(tm()){let e=ep((0,e3.VK)(this.#Q,new URL(window.location.href)));if("production"===this.#en){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return"function"==typeof this.#Q?(q(eD.domainAsFunctionNotSupported),""):ep(this.#Q||"")}get proxyUrl(){if(tm()){let e=(0,e3.VK)(this.#X,new URL(window.location.href));return!e||eB(e)||eJ(e)||th.throwInvalidProxyUrl({url:e}),e?eJ(e)?new URL(e,window.location.origin).toString():e:""}return"function"==typeof this.#X?(q(eD.proxyUrlAsFunctionNotSupported),""):this.#X||""}get frontendApi(){let e=ec(this.publishableKey);return e?e.frontendApi:th.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#en}get isStandardBrowser(){return this.#el.standardBrowser||!1}get billing(){return nD._billing||(nD._billing=new ir),nD._billing}get apiKeys(){return nD._apiKeys||(nD._apiKeys=new nP),nD._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===a&&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:t,orgId:i,planId:r,planPeriod:n}=e;return`${t}-${i||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=nT.get(c);if(d)return d.signals.computedSignal();let h=(i=t2({resource:null}),r=t2({error:null}),n=t2({status:"idle"}),s=t4(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:iw(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),u=new iv(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return nT.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#el[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return th.throwMissingPublishableKeyError();const i=ec(e);if(!i)return th.throwInvalidPublishableKeyError({key:e});this.#Q=t?.domain,this.#X=t?.proxyUrl,this.environment=rp.getInstance(),this.#en=i.instanceType,this.#G=e,this.#er=function(e){let t=[],i=[];async function r(e){for await(let i of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:r,search:n,rotatingTokenNonce:s}){let a=new URLSearchParams(n);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.3.1"),s&&a.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&a.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&a.append("_method",t),i&&!nC.some(e=>i.startsWith(e))&&r&&a.append("_clerk_session_id",r),em([...a.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),a=n.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),ev({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return ev({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:c="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 t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(d)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===c||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?em(d,{keyEncoder:X}):d);let h=await r(o),u="GET"===c?"GET":"POST",p=o.url,f={...o,method:u,credentials:o.credentials||"include"};try{if(h){let e=i?.fetchMaxTries??(l()?4:11);s=await tr(()=>fetch(p,f),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===u&&i<e,onBeforeRetry:e=>{p.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){let e=p.toString();e8.error("network error",{error:t,url:e,method:c},"fapiClient");throw Error(`${tI} Network error at "${e}" - ${t}. Please try again.`)}let m=204!==s.status?await s.json():null,g=Object.assign(s,{payload:m});return s.ok||e8.error("request failed",{method:c,path:o.path,status:s.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:a,onAfterResponse:function(e){i.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eh.emit(f,"loading"),this.#eh.prioritizedOn(f,e=>this.#es=e),this.#eh.on(f,e=>{tm()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eu()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new y("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tm()&&("ready"===this.#es||"degraded"===this.#es)&&this.#eu()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),t$.clerk=this,this.#Z=new nO}getFapiClient=()=>this.#er;load=async e=>{if(e8.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#en||e?.unsafe_disableDevelopmentModeConsoleWarning||q("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#el=this.#ep(e),this.#el.ui?.ClerkUI&&(this.#ei=Promise.resolve(this.#el.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#el,new ts))),"development"===this.#en&&(this.#el.routerPush||this.#el.routerReplace)&&(!this.#el.routerPush||!this.#el.routerReplace)){let e=this.#el.routerPush?"routerReplace":"routerPush";q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}iW.on(iN,()=>{this.#ef(this.session)}),this.#el.sdkMetadata&&(nD.sdkMetadata=this.#el.sdkMetadata),!1!==this.#el.telemetry&&(this.telemetry=new eG({clerkVersion:nD.version,samplingRate:1,perEventSampling:!this.#el.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#el.telemetry}),this.#el.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=e1(e);if(i){t=i;break}}else t=e1(i);return{themeName:t}}(this.#el.appearance)}));try{this.#el.standardBrowser?await this.#em():await this.#eg();let e=this.#el.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#el.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,s=r||i&&!n,a=i&&!r?"error":void 0;s&&function(e={}){if(e5)return;let{enabled:t=!1,...i}=e;t&&(e2=!0,e5=!0,e7(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#Z?.load(this.environment),e8.info("load() complete",{},"clerk")}catch(e){throw this.#eh.emit(f,"error"),e8.error("load() failed",{error:e},"clerk"),e}}};#e_(){let e;return!!(!this.#el.signUpUrl&&this.#el.signInUrl&&(e=this.#el.signInUrl,!ef.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3.lQ,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3.lQ,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();e8.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:n?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=ta(this.#el.standardBrowser);iW.emit(iM,null),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#ef(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#ew(),this.#el.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e8.info("signOut() complete",{redirectUrl:ek(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#ew(),await l?.remove(),await o(),e8.info("signOut() complete",{redirectUrl:ek(s)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(e0("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(F(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotOpenSignInOrSignUp,{code:nN});return}this.assertComponentsReady(this.#ei);let t="SignIn";this.#ei.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let i={withSignUp:e?.withSignUp??this.#e_()};this.telemetry?.record(e0(t,e,i))};closeSignIn=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(M(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotRenderAnyBillingComponent("Checkout"),{code:nR});return}if(!this.user){if("development"===this.#en)throw new y(eD.cannotOpenCheckout,{code:nF});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(M(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotRenderAnyBillingComponent("PlanDetails"),{code:nR});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(e0("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#en)throw new y(eD.cannotOpenUserProfile,{code:nF});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(e0("UserVerification",e))};__internal_closeReverification=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#en||q(`Clerk: "${i}" requires an active user session. Ensure a user is signed in before executing ${i}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#en&&this.__internal_openEnableOrganizationsPrompt({caller:i,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eZ("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ei),this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await s.e("279").then(s.bind(s,5608));return e};openSignUp=e=>{if(F(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotOpenSignInOrSignUp,{code:nN});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(e0("SignUp",e))};closeSignUp=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#en)throw new y(eD.cannotOpenUserProfile,{code:nF});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e0("UserProfile",e,t))};closeUserProfile=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nM})}});if(t){if(!this.organization){if("development"===this.#en)throw new y(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(e0("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nM})}});t&&(this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(e0("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(e0("Waitlist",e))};closeWaitlist=()=>{this.#ei?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ei);let i="SignIn";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#e_()};this.telemetry?.record(eZ(i,t,r))};unmountSignIn=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ei);let i="UserAvatar";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eZ(i,t))};unmountUserAvatar=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ei);let i="SignUp";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eZ(i,t))};unmountSignUp=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#en)throw new y(eD.cannotRenderComponentWhenUserDoesNotExist,{code:nF});return}this.assertComponentsReady(this.#ei);let i="UserProfile";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eZ(i,t,r))};unmountUserProfile=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:nM})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#en)throw new y(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ei);let n="OrganizationProfile";this.#ei.then(e=>e.ensureMounted({preloadHint:n})).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eZ(n,t))};unmountOrganizationProfile=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:nM})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="CreateOrganization";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eZ(r,t))};unmountCreateOrganization=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:nM})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="OrganizationSwitcher";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eZ(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ei),this.#ei.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:nM})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="OrganizationList";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eZ(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ei);let i="UserButton";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eZ(i,t,r))};unmountUserButton=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ei);let i="Waitlist";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eZ(i,t))};unmountWaitlist=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(M(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotRenderAnyBillingComponent("PricingTable"),{code:nR});return}this.assertComponentsReady(this.#ei);let i="PricingTable";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eZ(i,t))};unmountPricingTable=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ei);let i="OAuthConsent";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),z(this,i=this.environment)&&N(this,i)){if("development"===this.#en)throw new y(eD.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&N(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(z(this,this.environment)){if("development"===this.#en)throw new y(eD.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ei);let r="APIKeys";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eZ(r,t))};unmountAPIKeys=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new y(eD.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:nM})}});if(!i)return;this.assertComponentsReady(this.#ei);let r="TaskChooseOrganization";this.#ei.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eZ(r,t))};unmountTaskChooseOrganization=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ei);let i="TaskResetPassword";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(eZ("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#ei);let i="TaskSetupMFA";this.#ei.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(eZ("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#ei?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,e8.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:i??null},"clerk");try{var s;let a;if(!this.client)throw e8.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===n&&!this.session)throw e8.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 n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3.lQ,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(s={...this.#el,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||q('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=i}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let h=c?.status==="pending"&&c?.currentTask&&this.#el.taskUrls?.[c?.currentTask.key],u=!!(i||h||r);if(tm()&&globalThis.document.hasFocus()||!this.#el.standardBrowser){let e;if(u&&c)try{(e=await c.__internal_touch())&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(x(e))this.handleUnauthenticated();else throw e}else await this.#ey(c);c=this.#eb(c?.id,e)}try{await c?.getToken()||iW.emit(iF,{token:null})}catch(e){if(U.is(e))e8.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let p=ta(this.#el.standardBrowser);if(u&&await p.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#ew(),h){let e=i?ev({base:h,hashSearchParams:{redirectUrl:i}},{stringify:!0}):h;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>{if(e=!0,!this.client?.isEligibleForTouch())return t;let i=new URL(t,window.location.href),r=this.client.buildTouchUrl({redirectUrl:i});return this.buildUrlWithAuth(r)};await r({session:c,decorateUrl:t}),"development"===this.#en&&!e&&this.client.isEligibleForTouch()&&q("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else if(i){if(this.client.isEligibleForTouch()){let e=new URL(i,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(i)}}}),p.isUnloading())return;this.#ef(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var i;let r;return i=e,e=e=>{var t;r||={...e},i(r={...{client:no((t=r).client,e.client),session:no(t.session,e.session),user:no(t.user,e.user),organization:no(t.organization,e.organization)}})},this.#ea.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ea=this.#ea.filter(t=>t!==e)}};on=(...e)=>{this.#eh.on(...e)};off=(...e)=>{this.#eh.off(...e)};__internal_addNavigationListener=e=>(this.#eo.push(e),()=>{this.#eo=this.#eo.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tm())return;if(void 0===window.location){let i=t?.replace&&this.#el.routerReplace?this.#el.routerReplace:this.#el.routerPush;return i?(e8.info(`Clerk is navigating to: ${e}`),await i(e,{windowNavigate:ej})):void 0}setTimeout(()=>{this.#ev()},0);let i=new URL(e,window.location.href);this.#ek.includes(i.protocol)||(console.warn(`Clerk: "${i.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),i=new URL("/",window.location.href));let r=t?.replace&&this.#el.routerReplace?this.#el.routerReplace:this.#el.routerPush;if(e8.info(`Clerk is navigating to: ${i}`),this.#el.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void ej(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:ej};return await r(ek(i),n)};buildUrlWithAuth(e){if("production"===this.#en)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#Y?this.#Y.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#eS(t));let i=this.isSatellite?this.#eI(e):e;return this.#eU("signInUrl",{...i,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#eS(t));let i=this.isSatellite?this.#eI(e):e;return this.#eU("signUpUrl",{...i,redirectUrl:t},e?.initialValues)}#eS=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(W,D),t.toString()}catch{return e}};#eI=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#eS(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#eS(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#eS(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#eS(t.signUpFallbackRedirectUrl)),t};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 eP(this.#el,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eP(this.#el,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#el.afterSignOutUrl?this.buildUrlWithAuth(this.#el.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#el.newSubscriptionRedirectUrl?this.#el.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ev({base:this.#el.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#el.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#el.afterMultiSessionSingleSignOutUrl):this.#el.signInUrl?this.buildUrlWithAuth(ev({base:this.#el.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 t=this.session?.currentTask;if(!t)return"";let i=this.#el.taskUrls?.[t.key];return i||ev({base:this.buildSignInUrl(e),hashPath:eM(t)},{stringify:!0})}#eA=async()=>{if(!tm())return;let e=new URLSearchParams({[W]:L}),t=eE(j);t&&eB(t)||function(){throw Error(`${tI} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=ev({base:eE(j),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tm())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tm())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tm())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tm())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tm())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tm())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tm())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tm())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tm())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tm())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tm())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eE("__clerk_status");if("expired"===i)throw new P("expired");if("client_mismatch"===i)throw new P("client_mismatch");if("verified"!==i)throw new P("failed");let r=eE("__clerk_created_session"),{signIn:n,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===s.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e3.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,i)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,s="identifier"in(e||{})?e:r,a="missingFields"in(e||{})?e:n,o=e=>i&&"function"==typeof i?i(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await i.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:s}=t,{externalAccount:a}=i.verifications,o={status:i.status,missingFields:i.missingFields,externalAccountStatus:a.status,externalAccountErrorCode:a.error?.code,externalAccountSessionId:a.error?.meta?.sessionId,sessionId:i.createdSessionId},l={status:t.status,firstFactorVerificationStatus:s.status,firstFactorVerificationErrorCode:s.error?.code,firstFactorVerificationSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||n.signInUrl),h=c(e.signUpUrl||n.signUpUrl),u=c(e.firstFactorUrl||ev({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||ev({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||ev({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eP(this.#el,e),g=c(e.continueSignUpUrl||ev({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:r,navigate:n,handleComplete:s,redirectUrl:a="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return s&&s();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:a,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let s=eR();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return n(i,{searchParams:s});if(r)return n(r,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||ev({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ev({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),w=e.signInUrl||n.signInUrl,y=e.signUpUrl||n.signUpUrl,b=async({session:e,baseUrl:t,redirectUrl:i})=>{e.currentTask?await ez(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:w,redirectUrl:m.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignInUrl()})}});case"needs_first_factor":return u();case"needs_second_factor":return p();case"needs_new_password":return f();default:tA("sign in")}}let v="user_locked"===o.externalAccountErrorCode,k="user_locked"===l.firstFactorVerificationErrorCode;if(v)return h();if(k)return d();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return u();if("needs_new_password"===l.status)return f();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let t=await i.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});case"missing_requirements":return _({missingFields:t.missingFields});default:tA("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await b({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return p();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,I="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||I){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await b({session:e,baseUrl:S?y:w,redirectUrl:m.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?h():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?_({missingFields:i.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iZ.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&iW.emit(iM,null),this.setActive({session:null})}catch(e){if(S(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#Y&&await this.#Y.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(S(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});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:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,h=n.replace("web3_","").replace("_signature",""),u=await ty().getWeb3Identifier({provider:h,walletName:o});switch(h){case"metamask":l=ty().generateSignatureWithMetamask;break;case"base":l=ty().generateSignatureWithBase;break;case"coinbase_wallet":l=ty().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new y("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>ty().generateSignatureWithSolana({...e,walletName:o});break;default:l=ty().generateSignatureWithOKXWallet}let p=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),f=p(a||ev({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),m=p(t||ev({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:l,strategy:n,walletName:o})}catch(e){if(td(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:l,unsafeMetadata:r,strategy:n,legalAccepted:s,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await m();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await ez(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await f();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rk.create({name:e,slug:t});getOrganization=async e=>rk.get(e);joinWaitlist=async({emailAddress:e})=>ns.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,t)=>{if(!this.client){let t=this.#el.selectInitialSession?this.#el.selectInitialSession(e):this.#eC(e);this.#ef(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#eb(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3.lQ)(),this.#ef(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||c()||e8.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),iW.emit(iF,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#eP()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rp(e)};__internal_onBeforeRequest=e=>{this.#er.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#er.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#ep({...this.#el,...e.options})};return this.#ei?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eT=()=>{let e=new URLSearchParams({[j]:window.location.href});return ev({base:this.#el.signInUrl,searchParams:e},{stringify:!0})};#eO=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eE=()=>{let e=eE(W);return e!==L&&!!this.isSatellite&&(e===D||!1!==this.#el.satelliteAutoSync&&!!this.#Y?.isSignedOut())};#ex=()=>"production"!==this.#en&&!this.isSatellite&&!!eE(j);#eR=async()=>{"development"===this.instanceType?await this.navigate(this.#eT()):"production"===this.instanceType&&await this.navigate(this.#eO())};#eF=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${tI} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${tI} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eM=()=>{this.isSatellite&&("development"!==this.#en||this.#el.signInUrl||function(){throw Error(`${tI} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tI} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#el.signInUrl&&this.#eF(this.#el.signInUrl,window.location.origin))};#em=async()=>{if(this.#Y=await nU.create(this,this.#er,this.#en,this.#eh),this.#eM(),this.#eE())return void await this.#eR();if(this.#ex())return void await this.#eA();this.#ec=(()=>{if(!n())return{onPageFocus:e3.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#et=new BroadcastChannel("clerk")),this.#ez();let e=function(e=window.location.hostname){if(!e)return!1;let t=ey.get(e);void 0===t&&(t=er.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||en.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ey.set(e,t));return t}(window?.location.hostname),t="development"===this.#en&&!e,i=0,r=0;for(;r<2;){r++;try{let e=rp.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=tS.getItem(tb,null);e&&this.updateEnvironment(new rp(e))}),r=async()=>iZ.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(E(e))throw e;++i;let t=this.#Y?.getSessionCookie(),r=function(e){let t;try{t=new r5({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iZ.clearInstance(),!t?.jwt)return iZ.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:r,orgId:n,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,r,n,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=rD(e.fea),{permissions:a,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let i=e.split(",").map(e=>e.trim());return{permissions:i,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(i.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(n>=i.length)continue;let a=i[n];if(a)for(let e=0;e<a.length;e++)1===a[e]&&r.push(`org:${s}:${t[e]}`)}return r}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:r,orgPermissions:n,factorVerificationAge:s}})(t.jwt.claims),c={object:"client",last_active_session_id:i,id:"client_init",sessions:[{object:"session",id:i,status:"active",last_active_organization_id:n||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:n&&o&&s?[{object:"organization_membership",id:n,role:s,permissions:a||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return iZ.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#Y?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#Y?.startPollingForToken()}),null}),[,n]=await (0,e3.vd)([e,r()]);if("rejected"===n.status){let e=n.reason;if(td(e,"requires_captcha"))await r();else throw e}if(this.#Y?.setClientUatCookieForDevelopmentInstances(),await this.#eN())return;break}catch(e){if(td(e,"dev_browser_unauthenticated"))await this.#Y.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tI} Something went wrong initializing Clerk.`)}()}this.#ee=new nA(this),this.#ee.start(),this.#eW(),this.#eD(),this.#eL(),this.#eh.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eg=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rp.getInstance().fetch({touch:!1,fetchMaxTries:i}),iZ.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(b(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new rp(i?.environment),iZ.clearInstance(),t=iZ.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#eh.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rp.getInstance().fetch({touch:!1,fetchMaxTries:1}),iZ.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eP()};#eC=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#ez=()=>{n()&&(this.#ec?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#ed>Date.now())&&(this.#ed=Date.now()+5e3,this.#el.touchSession&&this.#ey(this.session))}),this.#et?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),iW.on(iM,()=>{this.#et?.postMessage({type:"signout"})}),iW.on(iz,()=>{tS.setItem(tb,this.environment?.__internal_toSnapshot(),864e5)}))};#ey=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{if(x(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#eP=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#ea))t(e)}};#ev=()=>{for(let e of this.#eo)e()};#ew=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eP()};#e$=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#ej=(e=this.session)=>({session:e||null,organization:this.#e$(e),user:e?e.user:null});#ef=(e,t)=>{let{session:i,organization:r,user:n}=this.#ej(e);this.session=i,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#eP()};#eb=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#eD=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ei?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eL=()=>{this.#el.__internal_keyless_claimKeylessApplicationUrl&&this.#ei?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#el.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#el.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#el.__internal_keyless_dismissPrompt}})})};#eU=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#el[e]||this.environment.displayConfig[e];this.#e_()&&(r=this.#el.signInUrl);let n=new eP(this.#el,t).toSearchParams(),s=new URLSearchParams(i||{}),a=ev({base:r,hashPath:this.#e_()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,n]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eN=async()=>{var e;let t,i,r,n,s=new URLSearchParams(window.location.search).get("redirect_url"),a="production"===this.instanceType,o=null!==s&&(e=this.frontendApi,i=(t=new URL(s,eg)).pathname,r=eA.includes(i)||eC.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#el.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#el.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,eg),(!eA.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#ep=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,i=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...nW,...e,ui:i,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${eb(t)}`),r.push(`https://*.${eb(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#eW=()=>{try{ex(W),ex(eT),ex($),ex("__clerk_handshake"),ex("__clerk_handshake_nonce"),ex("__clerk_help")}catch{}};get #ek(){let e=e$;return this.#el.allowedRedirectProtocols&&(e=e.concat(this.#el.allowedRedirectProtocols)),e}#eu(){return void 0!==this.client}}let nL=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",n$=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",nj=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new nD(nL,{proxyUrl:n$,domain:nj}))})(),{}})());