UNPKG

@accounter/client

Version:
4 lines • 169 kB
import{s as e}from"./dist-BBBZL-zT.js";import{o as t}from"./utils-C9b7NsUD.js";import{n,t as r}from"./dist-vGISINVi.js";n();var i=e(t()),a=function(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},a(e,t)};function o(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);a(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)};function c(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function l(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function u(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function d(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function f(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}var p={timeoutInSeconds:60},m=1e4,h=`memory`,g={name:`auth0-spa-js`,version:`2.19.2`},_=()=>Date.now(),v=`default`,y=class e extends Error{constructor(t,n){super(n),this.error=t,this.error_description=n,Object.setPrototypeOf(this,e.prototype)}static fromPayload(t){let{error:n,error_description:r}=t;return new e(n,r)}},b=class e extends y{constructor(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;super(t,n),this.state=r,this.appState=i,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends y{constructor(t,n,r,i){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;super(t,n),this.connection=r,this.state=i,this.appState=a,Object.setPrototypeOf(this,e.prototype)}},te=class e extends y{constructor(){super(`timeout`,`Timeout`),Object.setPrototypeOf(this,e.prototype)}},ne=class e extends te{constructor(t){super(),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},re=class e extends y{constructor(t){super(`cancelled`,`Popup closed`),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},ie=class e extends y{constructor(){super(`popup_open`,"Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,e.prototype)}},ae=class e extends y{constructor(t,n,r,i){super(t,n),this.mfa_token=r,this.mfa_requirements=i,Object.setPrototypeOf(this,e.prototype)}},oe=class e extends y{constructor(t,n){super(`missing_refresh_token`,`Missing Refresh Token (audience: '${le(t,[`default`])}', scope: '${le(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},se=class e extends y{constructor(t,n){super(`missing_scopes`,`Missing requested scopes after refresh (audience: '${le(t,[`default`])}', missing scope: '${le(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},ce=class e extends y{constructor(t){super(`use_dpop_nonce`,`Server rejected DPoP proof: wrong nonce`),this.newDpopNonce=t,Object.setPrototypeOf(this,e.prototype)}};function le(e){return e&&!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).includes(e)?e:``}var ue=()=>window.crypto,de=()=>{let e=``;for(;e.length<43;){let t=ue().getRandomValues(new Uint8Array(43-e.length));for(let n of t)e.length<43&&n<198&&(e+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.`[n%66])}return e},fe=e=>btoa(e),pe=[{key:`name`,type:[`string`]},{key:`version`,type:[`string`,`number`]},{key:`env`,type:[`object`]}],me=function(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return Object.keys(e).reduce((n,r)=>{if(t&&r===`env`)return n;let i=pe.find(e=>e.key===r);return i&&i.type.includes(typeof e[r])&&(n[r]=e[r]),n},{})},he=e=>{var{clientId:t}=e,n=f(e,[`clientId`]);return new URLSearchParams((e=>Object.keys(e).filter(t=>e[t]!==void 0).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{}))(Object.assign({client_id:t},n))).toString()},ge=async e=>await ue().subtle.digest({name:`SHA-256`},new TextEncoder().encode(e)),_e=e=>(e=>decodeURIComponent(atob(e).split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)))(e.replace(/_/g,`/`).replace(/-/g,`+`)),ve=e=>{let t=new Uint8Array(e);return(e=>{let t={"+":`-`,"/":`_`,"=":``};return e.replace(/[+/=]/g,e=>t[e])})(window.btoa(String.fromCharCode(...Array.from(t))))},ye=typeof globalThis<`u`?globalThis:typeof window<`u`?window:r===void 0?typeof self<`u`?self:{}:r,be={},xe={};Object.defineProperty(xe,`__esModule`,{value:!0});var Se=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);r===void 0?n===void 0?e.locked.set(t,[]):e.locked.set(t,[n]):n!==void 0&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())})},this.unlock=function(t){var n=e.locked.get(t);if(n!==void 0&&n.length!==0){var r=n.pop();e.locked.set(t,n),r!==void 0&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return e.instance===void 0&&(e.instance=new e),e.instance},e}();xe.default=function(){return Se.getInstance()};var x=ye&&ye.__awaiter||function(e,t,n,r){return new(n||=Promise)(function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(o,s)}c((r=r.apply(e,t||[])).next())})},S=ye&&ye.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw TypeError(`Generator is already executing.`);for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!((i=i.length>0&&i[i.length-1])||a[0]!==6&&a[0]!==2)){o=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(a[0]===6&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}},Ce=ye;Object.defineProperty(be,`__esModule`,{value:!0});var we=xe,Te=`browser-tabs-lock-key`,Ee={key:function(e){return x(Ce,void 0,void 0,function(){return S(this,function(e){throw Error(`Unsupported`)})})},getItem:function(e){return x(Ce,void 0,void 0,function(){return S(this,function(e){throw Error(`Unsupported`)})})},clear:function(){return x(Ce,void 0,void 0,function(){return S(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return x(Ce,void 0,void 0,function(){return S(this,function(e){throw Error(`Unsupported`)})})},setItem:function(e,t){return x(Ce,void 0,void 0,function(){return S(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 De(e){return new Promise(function(t){return setTimeout(t,e)})}function Oe(e){for(var t=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`,n=``,r=0;r<e;r++)n+=t[Math.floor(61*Math.random())];return n}var ke=be.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+Oe(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,e.waiters===void 0&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return n===void 0&&(n=5e3),x(this,void 0,void 0,function(){var r,i,a,o,s,c,l;return S(this,function(u){switch(u.label){case 0:r=Date.now()+Oe(4),i=Date.now()+n,a=Te+`-`+t,o=this.storageHandler===void 0?Ee:this.storageHandler,u.label=1;case 1:return Date.now()<i?[4,De(30)]:[3,8];case 2:return u.sent(),o.getItemSync(a)===null?(s=this.id+`-`+t+`-`+r,[4,De(Math.floor(25*Math.random()))]):[3,5];case 3:return u.sent(),o.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,De(30)];case 4:return u.sent(),(c=o.getItemSync(a))!==null&&(l=JSON.parse(c)).id===this.id&&l.iat===r?(this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0]):[3,7];case 5:return e.lockCorrector(this.storageHandler===void 0?Ee:this.storageHandler),[4,this.waitForSomethingToChange(i)];case 6:u.sent(),u.label=7;case 7:return r=Date.now()+Oe(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return x(this,void 0,void 0,function(){var n=this;return S(this,function(r){return setTimeout(function(){return x(n,void 0,void 0,function(){var n,r,i;return S(this,function(a){switch(a.label){case 0:return[4,we.default().lock(t)];case 1:return a.sent(),this.acquiredIatSet.has(t)?(n=this.storageHandler===void 0?Ee:this.storageHandler,(r=n.getItemSync(e))===null?(we.default().unlock(t),[2]):((i=JSON.parse(r)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(i)),we.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(we.default().unlock(t),[2])}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return x(this,void 0,void 0,function(){return S(this,function(n){switch(n.label){case 0:return[4,new Promise(function(n){var r=!1,i=Date.now(),a=!1;function o(){if(a||=(window.removeEventListener(`storage`,o),e.removeFromWaiting(o),clearTimeout(s),!0),!r){r=!0;var t=50-(Date.now()-i);t>0?setTimeout(n,t):n(null)}}window.addEventListener(`storage`,o),e.addToWaiting(o);var s=setTimeout(o,Math.max(0,t-Date.now()))})];case 1:return n.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),e.waiters!==void 0&&e.waiters.push(t)},e.removeFromWaiting=function(t){e.waiters!==void 0&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){e.waiters!==void 0&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return x(this,void 0,void 0,function(){return S(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 x(this,void 0,void 0,function(){var n,r,i,a;return S(this,function(o){switch(o.label){case 0:return n=this.storageHandler===void 0?Ee:this.storageHandler,r=Te+`-`+t,(i=n.getItemSync(r))===null?[2]:(a=JSON.parse(i)).id===this.id?[4,we.default().lock(a.iat)]:[3,2];case 1:o.sent(),this.acquiredIatSet.delete(a.iat),n.removeItemSync(r),we.default().unlock(a.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,i=[],a=0;;){var o=r.keySync(a);if(o===null)break;i.push(o),a++}for(var s=!1,c=0;c<i.length;c++){var l=i[c];if(l.includes(Te)){var u=r.getItemSync(l);if(u!==null){var d=JSON.parse(u);(d.timeRefreshed===void 0&&d.timeAcquired<n||d.timeRefreshed!==void 0&&d.timeRefreshed<n)&&(r.removeItemSync(l),s=!0)}}}s&&e.notifyWaiters()},e.waiters=void 0,e}(),Ae=class{async runWithLock(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),t);try{return await navigator.locks.request(e,{mode:`exclusive`,signal:r.signal},async e=>{if(clearTimeout(i),!e)throw Error(`Lock not available`);return await n()})}catch(e){throw clearTimeout(i),e?.name===`AbortError`?new te:e}}},je=class{constructor(){this.activeLocks=new Set,this.lock=new ke,this.pagehideHandler=()=>{this.activeLocks.forEach(e=>this.lock.releaseLock(e)),this.activeLocks.clear()}}async runWithLock(e,t,n){let r=!1;for(let n=0;n<10&&!r;n++)r=await this.lock.acquireLock(e,t);if(!r)throw new te;this.activeLocks.add(e),this.activeLocks.size===1&&typeof window<`u`&&window.addEventListener(`pagehide`,this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),this.activeLocks.size===0&&typeof window<`u`&&window.removeEventListener(`pagehide`,this.pagehideHandler)}}};function Me(){return typeof navigator<`u`&&typeof(e=navigator.locks)?.request==`function`?new Ae:new je;var e}var Ne=null,Pe=new TextEncoder,Fe=new TextDecoder;function Ie(e){return typeof e==`string`?Pe.encode(e):Fe.decode(e)}function Le(e){if(typeof e.modulusLength!=`number`||e.modulusLength<2048)throw new He(`${e.name} modulusLength must be at least 2048 bits`)}async function Re(e,t,n){if(!1===n.usages.includes(`sign`))throw TypeError(`private CryptoKey instances used for signing assertions must include "sign" in their "usages"`);let r=`${Be(Ie(JSON.stringify(e)))}.${Be(Ie(JSON.stringify(t)))}`;return`${r}.${Be(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:`SHA-256`};case`RSA-PSS`:return Le(e.algorithm),{name:e.algorithm.name,saltLength:32};case`RSASSA-PKCS1-v1_5`:return Le(e.algorithm),{name:e.algorithm.name};case`Ed25519`:return{name:e.algorithm.name}}throw new Ve}(n),n,Ie(r)))}`}var ze;if(Uint8Array.prototype.toBase64)ze=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;ze=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(``)).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}}function Be(e){return ze(e)}var Ve=class extends Error{constructor(e){var t;super(e??`operation not supported`),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}},He=class extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}};function Ue(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`PS256`;throw new Ve(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`RSASSA-PKCS1-v1_5`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`RS256`;throw new Ve(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`ECDSA`:return function(e){if(e.algorithm.namedCurve===`P-256`)return`ES256`;throw new Ve(`unsupported EcKeyAlgorithm namedCurve`)}(e);case`Ed25519`:return`Ed25519`;default:throw new Ve(`unsupported CryptoKey algorithm name`)}}function We(e){return e instanceof CryptoKey}function Ge(e){return We(e)&&e.type===`public`}async function Ke(e,t,n,r,i,a){let o=e?.privateKey,s=e?.publicKey;if(!We(c=o)||c.type!==`private`)throw TypeError(`"keypair.privateKey" must be a private CryptoKey`);var c;if(!Ge(s))throw TypeError(`"keypair.publicKey" must be a public CryptoKey`);if(!0!==s.extractable)throw TypeError(`"keypair.publicKey.extractable" must be true`);if(typeof t!=`string`)throw TypeError(`"htu" must be a string`);if(typeof n!=`string`)throw TypeError(`"htm" must be a string`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`"nonce" must be a string or undefined`);if(i!==void 0&&typeof i!=`string`)throw TypeError(`"accessToken" must be a string or undefined`);if(a!==void 0&&(typeof a!=`object`||!a||Array.isArray(a)))throw TypeError(`"additional" must be an object`);return Re({alg:Ue(o),typ:`dpop+jwt`,jwk:await qe(s)},Object.assign(Object.assign({},a),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:r,htu:t,ath:i?Be(await crypto.subtle.digest(`SHA-256`,Ie(i))):void 0}),o)}async function qe(e){let{kty:t,e:n,n:r,x:i,y:a,crv:o}=await crypto.subtle.exportKey(`jwk`,e);return{kty:t,crv:o,e:n,n:r,x:i,y:a}}var Je=`dpop-nonce`,Ye=[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:token-exchange`,`http://auth0.com/oauth/grant-type/mfa-oob`,`http://auth0.com/oauth/grant-type/mfa-otp`,`http://auth0.com/oauth/grant-type/mfa-recovery-code`];function Xe(){return async function(e,t){var n;let r;if(typeof e!=`string`||e.length===0)throw TypeError(`"alg" must be a non-empty string`);switch(e){case`PS256`:r={name:`RSA-PSS`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`RS256`:r={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`ES256`:r={name:`ECDSA`,namedCurve:`P-256`};break;case`Ed25519`:r={name:`Ed25519`};break;default:throw new Ve}return crypto.subtle.generateKey(r,(n=t?.extractable)!=null&&n,[`sign`,`verify`])}(`ES256`,{extractable:!1})}function Ze(e){return async function(e){if(!Ge(e))throw TypeError(`"publicKey" must be a public CryptoKey`);if(!0!==e.extractable)throw TypeError(`"publicKey.extractable" must be true`);let t=await qe(e),n;switch(t.kty){case`EC`:n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case`OKP`:n={crv:t.crv,kty:t.kty,x:t.x};break;case`RSA`:n={e:t.e,kty:t.kty,n:t.n};break;default:throw new Ve(`unsupported JWK kty`)}return Be(await crypto.subtle.digest({name:`SHA-256`},Ie(JSON.stringify(n))))}(e.publicKey)}function Qe(e){let{keyPair:t,url:n,method:r,nonce:i,accessToken:a}=e;return Ke(t,function(e){let t=new URL(e);return t.search=``,t.hash=``,t.href}(n),r,i,a)}var $e=(e,t)=>new Promise(function(n,r){let i=new MessageChannel;i.port1.onmessage=function(e){e.data.error?r(Error(e.data.error)):n(e.data),i.port1.close()},t.postMessage(e,[i.port2])}),et=(e,t,n)=>{let r=new AbortController,i;return t.signal=r.signal,Promise.race([fetch(e,t),new Promise((e,t)=>{i=setTimeout(()=>{r.abort(),t(Error(`Timeout when executing 'fetch'`))},n)})]).finally(()=>{clearTimeout(i)})},tt=async function(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:m;return i?(async(e,t,n,r,i,a,o,s)=>$e({type:`refresh`,auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:r,useFormData:o,useMrrt:s},a))(e,t,n,r,o,i,a,arguments.length>7?arguments[7]:void 0):(async(e,t,n)=>{let r=await et(e,t,n);return{ok:r.ok,json:await r.json(),headers:(i=r.headers,[...i].reduce((e,t)=>{let[n,r]=t;return e[n]=r,e},{}))};var i})(e,r,o)};async function nt(e,t,n,r,i,a,o,s,c,l){if(c){let t=await c.generateProof({url:e,method:i.method||`GET`,nonce:await c.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:t})}let u,d=null;for(let c=0;c<3;c++)try{u=await tt(e,n,r,i,a,o,t,s),d=null;break}catch(e){d=e}if(d)throw d;let p=u.json,{error:m,error_description:h}=p,g=f(p,[`error`,`error_description`]),{headers:_,ok:v}=u,b;if(c&&(b=_[Je],b&&await c.setNonce(b)),!v){let u=h||`HTTP error. Unable to fetch ${e}`;if(m===`mfa_required`)throw new ae(m,u,g.mfa_token,g.mfa_requirements);if(m===`missing_refresh_token`)throw new oe(n,r);if(m===`use_dpop_nonce`){if(!c||!b||l)throw new ce(b);return nt(e,t,n,r,i,a,o,s,c,!0)}throw new y(m||`request_error`,u)}return g}async function rt(e,t){var{baseUrl:n,timeout:r,audience:i,scope:a,auth0Client:o,useFormData:s,useMrrt:c,dpop:l}=e,u=f(e,[`baseUrl`,`timeout`,`audience`,`scope`,`auth0Client`,`useFormData`,`useMrrt`,`dpop`]);let d=u.grant_type===`urn:ietf:params:oauth:grant-type:token-exchange`,p=u.grant_type===`refresh_token`&&c,m=Object.assign(Object.assign(Object.assign(Object.assign({},u),d&&i&&{audience:i}),d&&a&&{scope:a}),p&&{audience:i,scope:a}),h=s?he(m):JSON.stringify(m),_=(y=u.grant_type,Ye.includes(y));var y;return await nt(`${n}/oauth/token`,r,i||v,a,{method:`POST`,body:h,headers:{"Content-Type":s?`application/x-www-form-urlencoded`:`application/json`,"Auth0-Client":btoa(JSON.stringify(me(o||g)))}},t,s,c,_?l:void 0)}var it=function(){return(e=[...arguments].filter(Boolean).join(` `).trim().split(/\s+/),Array.from(new Set(e))).join(` `);var e},at=(e,t,n)=>{let r;return n&&(r=e[n]),r||=e[v],it(r,t)},ot=`@@auth0spajs@@`,st=`@@user@@`,C=class e{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ot,n=arguments.length>2?arguments[2]:void 0;this.prefix=t,this.suffix=n,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience}toKey(){return[this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join(`::`)}static fromKey(t){let[n,r,i,a]=t.split(`::`);return new e({clientId:r,scope:a,audience:i},n)}static fromCacheEntry(t){let{scope:n,audience:r,client_id:i}=t;return new e({scope:n,audience:r,clientId:i})}},ct=class{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch{return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter(e=>e.startsWith(ot))}},lt=class{constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){let n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}},ut=class{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||_}async setIdToken(e,t,n){let r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await this.keyManifest?.add(r)}async getIdToken(e){let t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){let t=await this.get(e);return!t||!t.id_token||!t.decodedToken?void 0:{id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return{id_token:t.id_token,decodedToken:t.decodedToken}}async get(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=await this.cache.get(e.toKey()),a=e;if(!i){let t=await this.getCacheKeys();if(!t)return;let o=this.matchExistingCacheKey(e,t);if(o&&(i=await this.cache.get(o),a=C.fromKey(o)),!i&&n&&r!==`cache-only`)return this.getEntryWithRefreshToken(e,t)}if(!i)return;let o=await this.nowProvider(),s=Math.floor(o/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,a):(await this.cache.remove(a.toKey()),void await this.keyManifest?.remove(a.toKey())):i.body}async modifiedCachedEntry(e,t){let n={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},r={body:n,expiresAt:e.expiresAt};return await this.cache.set(t.toKey(),r),{refresh_token:n.refresh_token,audience:n.audience,scope:n.scope}}async set(e){let t=new C({clientId:e.client_id,scope:e.scope,audience:e.audience}),n=await this.wrapCacheEntry(e);await this.cache.set(t.toKey(),n),await this.keyManifest?.add(t.toKey())}async remove(e,t,n){let r=new C({clientId:e,scope:n,audience:t});await this.cache.remove(r.toKey())}async stripRefreshToken(e){let t=await this.getCacheKeys();if(t)for(let n of t){let t=await this.cache.get(n);t?.body?.refresh_token===e&&(delete t.body.refresh_token,await this.cache.set(n,t))}}async clear(e){let t=await this.getCacheKeys();t&&(await t.filter(t=>!e||t.includes(e)).reduce(async(e,t)=>{await e,await this.cache.remove(t)},Promise.resolve()),await this.keyManifest?.clear())}async wrapCacheEntry(e){let t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){return this.keyManifest?(await this.keyManifest.get())?.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new C({clientId:e},ot,st).toKey()}matchExistingCacheKey(e,t){return t.filter(t=>{let n=C.fromKey(t),r=new Set(n.scope&&n.scope.split(` `)),i=e.scope?.split(` `)||[],a=n.scope&&i.reduce((e,t)=>e&&r.has(t),!0);return n.prefix===ot&&n.clientId===e.clientId&&n.audience===e.audience&&a})[0]}async getEntryWithRefreshToken(e,t){for(let n of t){let t=C.fromKey(n);if(t.prefix===ot&&t.clientId===e.clientId){let e=await this.cache.get(n);if(e?.body?.refresh_token)return{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}}}async getRefreshTokensByAudience(e,t){var n;let r=await this.getCacheKeys();if(!r)return[];let i=new Set;for(let a of r){let r=C.fromKey(a);if(r.prefix===ot&&r.clientId===t&&r.audience===e){let e=await this.cache.get(a);(n=e?.body)!=null&&n.refresh_token&&i.add(e.body.refresh_token)}}return Array.from(i)}async updateEntry(e,t){let n=await this.getCacheKeys();if(n)for(let r of n){let n=await this.cache.get(r);n?.body?.refresh_token===e&&(n.body.refresh_token=t,await this.cache.set(r,n))}}},dt=class{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey=`a0.spajs.txs.${this.clientId}`}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain})}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain})}},ft=e=>typeof e==`number`,pt=`iss.aud.exp.nbf.iat.jti.azp.nonce.auth_time.at_hash.c_hash.acr.amr.sub_jwk.cnf.sip_from_tag.sip_date.sip_callid.sip_cseq_num.sip_via_branch.orig.dest.mky.events.toe.txn.rph.sid.vot.vtm`.split(`.`),mt=e=>{if(!e.id_token)throw Error(`ID token is required but missing`);let t=(e=>{let t=e.split(`.`),[n,r,i]=t;if(t.length!==3||!n||!r||!i)throw Error(`ID token could not be decoded`);let a=JSON.parse(_e(r)),o={__raw:e},s={};return Object.keys(a).forEach(e=>{o[e]=a[e],pt.includes(e)||(s[e]=a[e])}),{encoded:{header:n,payload:r,signature:i},header:JSON.parse(_e(n)),claims:o,user:s}})(e.id_token);if(!t.claims.iss)throw Error(`Issuer (iss) claim must be a string present in the ID token`);if(t.claims.iss!==e.iss)throw Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw Error(`Subject (sub) claim must be a string present in the ID token`);if(t.header.alg!==`RS256`)throw Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||typeof t.claims.aud!=`string`&&!Array.isArray(t.claims.aud))throw Error(`Audience (aud) claim must be a string or array of strings present in the ID token`);if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but was not one of "${t.claims.aud.join(`, `)}"`);if(t.claims.aud.length>1){if(!t.claims.azp)throw Error(`Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values`);if(t.claims.azp!==e.aud)throw Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but found "${t.claims.aud}"`);if(e.nonce){if(!t.claims.nonce)throw Error(`Nonce (nonce) claim must be a string present in the ID token`);if(t.claims.nonce!==e.nonce)throw Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!ft(t.claims.auth_time))throw Error(`Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified`);if(t.claims.exp==null||!ft(t.claims.exp))throw Error(`Expiration Time (exp) claim must be a number present in the ID token`);if(!ft(t.claims.iat))throw Error(`Issued At (iat) claim must be a number present in the ID token`);let n=e.leeway||60,r=new Date(e.now||Date.now()),i=new Date(0);if(i.setUTCSeconds(t.claims.exp+n),r>i)throw Error(`Expiration Time (exp) claim error in the ID token; current time (${r}) is after expiration time (${i})`);if(t.claims.nbf!=null&&ft(t.claims.nbf)){let e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),r<e)throw Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${r}) is before ${e}`)}if(t.claims.auth_time!=null&&ft(t.claims.auth_time)){let i=new Date(0);if(i.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),r>i)throw Error(`Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${r}) is after last auth at ${i}`)}if(e.organization){let n=e.organization.trim();if(n.startsWith(`org_`)){let e=n;if(!t.claims.org_id)throw Error(`Organization ID (org_id) claim must be a string present in the ID token`);if(e!==t.claims.org_id)throw Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else{let e=n.toLowerCase();if(!t.claims.org_name)throw Error(`Organization Name (org_name) claim must be a string present in the ID token`);if(e!==t.claims.org_name)throw Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t},ht=ye&&ye.__assign||function(){return ht=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},ht.apply(this,arguments)};function gt(e,t){if(!t)return``;var n=`; `+e;return!0===t?n:n+`=`+t}function _t(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,`%28`).replace(/\)/g,`%29`)+`=`+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if(typeof e.expires==`number`){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return gt(`Expires`,e.expires?e.expires.toUTCString():``)+gt(`Domain`,e.domain)+gt(`Path`,e.path)+gt(`Secure`,e.secure)+gt(`SameSite`,e.sameSite)}(n)}function vt(){return function(e){for(var t={},n=e?e.split(`; `):[],r=/(%[\dA-F]{2})+/gi,i=0;i<n.length;i++){var a=n[i].split(`=`),o=a.slice(1).join(`=`);o.charAt(0)===`"`&&(o=o.slice(1,-1));try{t[a[0].replace(r,decodeURIComponent)]=o.replace(r,decodeURIComponent)}catch{}}return t}(document.cookie)}var yt=function(e){return vt()[e]};function bt(e,t,n){document.cookie=_t(e,t,ht({path:`/`},n))}var xt=bt,St=function(e,t){bt(e,``,ht(ht({},t),{expires:-1}))},Ct={get(e){let t=yt(e);if(t!==void 0)return JSON.parse(t)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0,sameSite:`none`}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),xt(e,JSON.stringify(t),r)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),St(e,n)}},wt=`_legacy_`,Tt={get(e){return Ct.get(e)||Ct.get(`${wt}${e}`)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),xt(`${wt}${e}`,JSON.stringify(t),r),Ct.save(e,t,n)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),St(e,n),Ct.remove(e,t),Ct.remove(`${wt}${e}`,t)}},Et={get(e){if(typeof sessionStorage>`u`)return;let t=sessionStorage.getItem(e);return t==null?void 0:JSON.parse(t)},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}},Dt;(function(e){e.Code=`code`,e.ConnectCode=`connect_code`})(Dt||={});function Ot(e,t,n){var r=t===void 0?null:t,i=function(e,t){var n=atob(e);if(t){for(var r=new Uint8Array(n.length),i=0,a=n.length;i<a;++i)r[i]=n.charCodeAt(i);return String.fromCharCode.apply(null,new Uint16Array(r.buffer))}return n}(e,n!==void 0&&n),a=i.indexOf(`
`,10)+1,o=i.substring(a)+(r?`//# sourceMappingURL=`+r:``),s=new Blob([o],{type:`application/javascript`});return URL.createObjectURL(s)}var kt,At,jt,Mt,Nt=(kt=`Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOm99PXQ7cmV0dXJuIG5ldyBlKHIsbyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUsbyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKG8pLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1vLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtyZXR1cm4gZSYmIShhcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W10pLmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IG89ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIG8gaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxvKSYmdC5pbmRleE9mKG8pPDAmJihyW29dPWVbb10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgcz0wO2ZvcihvPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7czxvLmxlbmd0aDtzKyspdC5pbmRleE9mKG9bc10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLG9bc10pJiYocltvW3NdXT1lW29bc11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIodD0+dm9pZCAwIT09ZVt0XSkucmVkdWNlKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkse30pKShPYmplY3QuYXNzaWduKHtjbGllbnRfaWQ6dH0scikpKS50b1N0cmluZygpfTtsZXQgcz17fSxuPW51bGw7Y29uc3QgaT0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCksYT0oZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpLGM9ZT0+e09iamVjdC5lbnRyaWVzKHMpLmZvckVhY2godD0+e2xldFtyLG9dPXQ7bz09PWUmJmRlbGV0ZSBzW3JdfSl9LGw9ZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKGUsdCk9PntyW3RdPWV9KSxyfSxmPWFzeW5jIGU9PntsZXQgcixuLHtkYXRhOnt0aW1lb3V0OmMsYXV0aDpmLGZldGNoVXJsOnUsZmV0Y2hPcHRpb25zOmgsdXNlRm9ybURhdGE6ZCx1c2VNcnJ0OnB9LHBvcnRzOltnXX09ZSx5PXt9O2NvbnN0e2F1ZGllbmNlOmIsc2NvcGU6T309Znx8e307dHJ5e2NvbnN0IGU9ZD9sKGguYm9keSk6SlNPTi5wYXJzZShoLmJvZHkpO2lmKCFlLnJlZnJlc2hfdG9rZW4mJiJyZWZyZXNoX3Rva2VuIj09PWUuZ3JhbnRfdHlwZSl7aWYobj0oKGUsdCk9PnNbaShlLHQpXSkoYixPKSwhbiYmcCl7Y29uc3QgZT1zLmxhdGVzdF9yZWZyZXNoX3Rva2VuLHQ9KChlLHQpPT4hIU9iamVjdC5rZXlzKHMpLmZpbmQocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBvPWEodCxyKSxzPXIuc3BsaXQoInwiKVsxXS5zcGxpdCgiICIpLG49ZS5zcGxpdCgiICIpLmV2ZXJ5KGU9PnMuaW5jbHVkZXMoZSkpO3JldHVybiBvJiZufX0pKShPLGIpO2UmJiF0JiYobj1lKX1pZighbil0aHJvdyBuZXcgdChiLE8pO2guYm9keT1kP28oT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LGUpLHtyZWZyZXNoX3Rva2VuOm59KSk6SlNPTi5zdHJpbmdpZnkoT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LGUpLHtyZWZyZXNoX3Rva2VuOm59KSl9bGV0IGYsdzsiZnVuY3Rpb24iPT10eXBlb2YgQWJvcnRDb250cm9sbGVyJiYoZj1uZXcgQWJvcnRDb250cm9sbGVyLGguc2lnbmFsPWYuc2lnbmFsKTt0cnl7dz1hd2FpdCBQcm9taXNlLnJhY2UoWyhtPWMsbmV3IFByb21pc2UoZT0+c2V0VGltZW91dChlLG0pKSksZmV0Y2godSxPYmplY3QuYXNzaWduKHt9LGgpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIGcucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCF3KXJldHVybiBmJiZmLmFib3J0KCksdm9pZCBnLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189dy5oZWFkZXJzLHk9Wy4uLl9dLnJlZHVjZSgoZSx0KT0+e2xldFtyLG9dPXQ7cmV0dXJuIGVbcl09byxlfSx7fSkscj1hd2FpdCB3Lmpzb24oKSxyLnJlZnJlc2hfdG9rZW4/KHAmJihzLmxhdGVzdF9yZWZyZXNoX3Rva2VuPXIucmVmcmVzaF90b2tlbixrPW4saj1yLnJlZnJlc2hfdG9rZW4sT2JqZWN0LmVudHJpZXMocykuZm9yRWFjaChlPT57bGV0W3Qscl09ZTtyPT09ayYmKHNbdF09ail9KSksKChlLHQscik9PntzW2kodCxyKV09ZX0pKHIucmVmcmVzaF90b2tlbixiLE8pLGRlbGV0ZSByLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBzW2koZSx0KV19KShiLE8pLGcucG9zdE1lc3NhZ2Uoe29rOncub2ssanNvbjpyLGhlYWRlcnM6eX0pfWNhdGNoKGUpe2cucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOnl9KX12YXIgayxqLF8sbX0sdT1hc3luYyBlPT57bGV0e2RhdGE6e3RpbWVvdXQ6dCxhdXRoOnIsZmV0Y2hVcmw6bixmZXRjaE9wdGlvbnM6aSx1c2VGb3JtRGF0YTpmfSxwb3J0czpbdV19PWU7Y29uc3R7YXVkaWVuY2U6aH09cnx8e307dHJ5e2NvbnN0IGU9KGU9Pntjb25zdCB0PW5ldyBTZXQ7cmV0dXJuIE9iamVjdC5lbnRyaWVzKHMpLmZvckVhY2gocj0+e2xldFtvLHNdPXI7YShlLG8pJiZ0LmFkZChzKX0pLEFycmF5LmZyb20odCl9KShoKTtpZigwPT09ZS5sZW5ndGgpcmV0dXJuIHZvaWQgdS5wb3N0TWVzc2FnZSh7b2s6ITB9KTtjb25zdCByPWY/bChpLmJvZHkpOkpTT04ucGFyc2UoaS5ib2R5KTtmb3IoY29uc3QgcyBvZiBlKXtjb25zdCBlPWY/byhPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse3Rva2VuOnN9KSk6SlNPTi5zdHJpbmdpZnkoT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LHIpLHt0b2tlbjpzfSkpO2xldCBhLGwsaCxkOyJmdW5jdGlvbiI9PXR5cGVvZiBBYm9ydENvbnRyb2xsZXImJihhPW5ldyBBYm9ydENvbnRyb2xsZXIsbD1hLnNpZ25hbCk7dHJ5e2Q9YXdhaXQgUHJvbWlzZS5yYWNlKFtuZXcgUHJvbWlzZShlPT57aD1zZXRUaW1lb3V0KGUsdCl9KSxmZXRjaChuLE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxpKSx7Ym9keTplLHNpZ25hbDpsfSkpXSkuZmluYWxseSgoKT0+Y2xlYXJUaW1lb3V0KGgpKX1jYXRjaChlKXtyZXR1cm4gdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjplLm1lc3NhZ2V9KX1pZighZClyZXR1cm4gYSYmYS5hYm9ydCgpLHZvaWQgdS5wb3N0TWVzc2FnZSh7ZXJyb3I6IlRpbWVvdXQgd2hlbiBleGVjdXRpbmcgJ2ZldGNoJyJ9KTtpZighZC5vayl7bGV0IGU7dHJ5e2NvbnN0e2Vycm9yX2Rlc2NyaXB0aW9uOnR9PUpTT04ucGFyc2UoYXdhaXQgZC50ZXh0KCkpO2U9dH1jYXRjaChlKXt9cmV0dXJuIHZvaWQgdS5wb3N0TWVzc2FnZSh7ZXJyb3I6ZXx8IkhUVFAgZXJyb3IgIi5jb25jYXQoZC5zdGF0dXMpfSl9YyhzKX11LnBvc3RNZXNzYWdlKHtvazohMH0pfWNhdGNoKGUpe3UucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZXx8IlVua25vd24gZXJyb3IgZHVyaW5nIHRva2VuIHJldm9jYXRpb24ifSl9fSxoPShlLHQpPT57aWYoIW4pcmV0dXJuITE7dHJ5e2NvbnN0IHI9bmV3IFVSTChuKS5vcmlnaW4sbz1uZXcgVVJMKGUuZmV0Y2hVcmwpO3JldHVybiBvLm9yaWdpbj09PXImJm8ucGF0aG5hbWU9PT10fWNhdGNoKGUpe3JldHVybiExfX07YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZT0+e2NvbnN0e2RhdGE6dCxwb3J0czpyfT1lLFtvXT1yO2lmKCEoInR5cGUiaW4gdCl8fCJpbml0IiE9PXQudHlwZSlyZXR1cm4idHlwZSJpbiB0JiYiY2xlYXIiPT09dC50eXBlPyhzPXt9LHZvaWQobnVsbD09b3x8by5wb3N0TWVzc2FnZSh7b2s6ITB9KSkpOiJ0eXBlImluIHQmJiJyZXZva2UiPT09dC50eXBlP2godCwiL29hdXRoL3Jldm9rZSIpP3ZvaWQgdShlKTp2b2lkKG51bGw9PW98fG8ucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOiJpbnZhbGlkX2ZldGNoX3VybCIsZXJyb3JfZGVzY3JpcHRpb246IlVuYXV0aG9yaXplZCBmZXRjaCBVUkwifSxoZWFkZXJzOnt9fSkpOnZvaWQoImZldGNoVXJsImluIHQmJmgodCwiL29hdXRoL3Rva2VuIik/ZihlKTpudWxsPT1vfHxvLnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjoiaW52YWxpZF9mZXRjaF91cmwiLGVycm9yX2Rlc2NyaXB0aW9uOiJVbmF1dGhvcml6ZWQgZmV0Y2ggVVJMIn0saGVhZGVyczp7fX0pKTtpZihudWxsPT09bil0cnl7bmV3IFVSTCh0LmFsbG93ZWRCYXNlVXJsKSxuPXQuYWxsb3dlZEJhc2VVcmx9Y2F0Y2goZSl7cmV0dXJufX0pfSgpOwoK`,At=null,jt=!1,function(e){return Mt||=Ot(kt,At,jt),new Worker(Mt,e)}),Pt={},Ft=class{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){let t=new Set((await this.cache.get(this.manifestKey))?.keys||[]);t.add(e),await this.cache.set(this.manifestKey,{keys:[...t]})}async remove(e){let t=await this.cache.get(this.manifestKey);if(t){let n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return`${ot}::${e}`}},It=`auth0.is.authenticated`,Lt={memory:()=>new lt().enclosedCache,localstorage:()=>new ct},Rt=e=>Lt[e],zt=e=>{let{openUrl:t,onRedirect:n}=e,r=f(e,[`openUrl`,`onRedirect`]);return Object.assign(Object.assign({},r),{openUrl:!1===t||t?t:n})},Bt=(e,t)=>{let n=t?.split(` `)||[];return(e?.split(` `)||[]).every(e=>n.includes(e))},Vt={NONCE:`nonce`,KEYPAIR:`keypair`},Ht=class{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){let e=window.indexedDB.open(`auth0-spa-js`,this.getVersion());return new Promise((t,n)=>{e.onupgradeneeded=()=>Object.values(Vt).forEach(t=>e.result.createObjectStore(t)),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}async getDbHandle(){return this.dbHandle||=await this.createDbHandle(),this.dbHandle}async executeDbRequest(e,t,n){let r=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}buildKey(e){let t=e?`_${e}`:`auth0`;return`${this.clientId}::${t}`}setNonce(e,t){return this.save(Vt.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Vt.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,`readwrite`,e=>e.put(n,t))}findNonce(e){return this.find(Vt.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Vt.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,`readonly`,e=>e.get(t))}async deleteBy(e,t){(await this.executeDbRequest(e,`readonly`,e=>e.getAllKeys()))?.filter(t).map(t=>this.executeDbRequest(e,`readwrite`,e=>e.delete(t)))}deleteByClientId(e,t){return this.deleteBy(e,e=>typeof e==`string`&&e.startsWith(`${t}::`))}clearNonces(){return this.deleteByClientId(Vt.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Vt.KEYPAIR,this.clientId)}},Ut=class{constructor(e){this.storage=new Ht(e)}getNonce(e){return this.storage.findNonce(e)}setNonce(e,t){return this.storage.setNonce(e,t)}async getOrGenerateKeyPair(){let e=await this.storage.findKeyPair();return e||(e=await Xe(),await this.storage.setKeyPair(e)),e}async generateProof(e){let t=await this.getOrGenerateKeyPair();return Qe(Object.assign({keyPair:t},e))}async calculateThumbprint(){return Ze(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}},Wt;(function(e){e.Bearer=`Bearer`,e.DPoP=`DPoP`})(Wt||={});var Gt=class{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||(typeof window>`u`?fetch:window.fetch.bind(window))})}isAbsoluteUrl(e){return/^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return`${e.replace(/\/?\/$/,``)}/${t.replace(/^\/+/,``)}`}throw TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(e){return this.config.getAccessToken?this.config.getAccessToken(e):this.hooks.getAccessToken(e)}extractUrl(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);let n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),r=e instanceof Request?new Request(n,e):n;return new Request(r,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Wt.Bearer;e.headers.set(`authorization`,`${n} ${t}`)}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;let n=await this.hooks.getDpopNonce(),r=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set(`dpop`,r)}async prepareRequest(e,t){let n=await this.getAccessToken(t),r,i;typeof n==`string`?(r=this.config.dpopNonceId?Wt.DPoP:Wt.Bearer,i=n):(r=n.token_type,i=n.access_token),this.setAuthorizationHeader(e,i,r),r===Wt.DPoP&&await this.setDpopProofHeader(e,i)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||``:typeof e.get==`function`?e.get(t)||``:e[t]||``}hasUseDpopNonceError(e){if(e.status!==401)return!1;let t=this.getHeader(e.headers,`www-authenticate`);return t.includes(`invalid_dpop_nonce`)||t.includes(`use_dpop_nonce`)}async handleResponse(e,t){let n=this.getHeader(e.headers,Je);if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new ce(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,r){let i=this.buildBaseRequest(e,t);await this.prepareRequest(i,r);let a=await this.config.fetch(i);return this.handleResponse(a,n)}fetchWithAuth(e,t,n){let r={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},r),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,r,n)}},Kt=class{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/connect`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/complete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});return this._handleResponse(t)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t)}catch(n){throw new qt({type:`invalid_json`,status:e.status,title:`Invalid JSON response`,detail:t||String(n)})}if(e.ok)return t;throw new qt(t)}},qt=class e extends Error{constructor(t){let{type:n,status:r,title:i,detail:a,validation_errors:o}=t;super(a),this.name=`MyAccountApiError`,this.type=n,this.status=r,this.title=i,this.detail=a,this.validation_errors=o,Object.setPrototypeOf(this,e.prototype)}},Jt={otp:{authenticatorTypes:[`otp`]},sms:{authenticatorTypes:[`oob`],oobChannels:[`sms`]},email:{authenticatorTypes:[`oob`],oobChannels:[`email`]},push:{authenticatorTypes:[`oob`],oobChannels:[`auth0`]},voice:{authenticatorTypes:[`oob`],oobChannels:[`voice`]}},Yt=`http://auth0.com/oauth/grant-type/mfa-otp`,Xt=`http://auth0.com/oauth/grant-type/mfa-oob`,Zt=`http://auth0.com/oauth/grant-type/mfa-recovery-code`;function Qt(e,t){this.v=e,this.k=t}function w(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function $t(e){return new Qt(e,0)}function en(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function T(e,t){return e.get(w(e,t))}function E(e,t,n){en(e,t),t.set(e,n)}function D(e,t,n){return e.set(w(e,t),n),n}function O(e,t,n){return(t=function(e){var t=function(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}(e,`string`);return typeof t==`symbol`?t:t+``}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function k(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?tn(Object(n),!0).forEach(function(t){O(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function nn(e,t){if(e==null)return{};var n,r,i=function(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function rn(e){return function(){return new an(e.apply(this,arguments))}}function an(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof Qt;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}var on,sn,cn;an.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},an.prototype.next=function(e){return this._invoke(`next`,e)},an.prototype.throw=function(e){return this._invoke(`throw`,e)},an.prototype.return=function(e){return this._invoke(`return`,e)},(typeof navigator>`u`||(on=navigator.userAgent)==null||(sn=on.startsWith)==null||!sn.call(on,`Mozilla/5.0 `))&&(cn=`oauth4webapi/v3.8.5`);function ln(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var A=`ERR_INVALID_ARG_VALUE`,j=`ERR_INVALID_ARG_TYPE`;function M(e,t,n){let r=TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var N=Symbol(),un=Symbol(),dn=Symbol(),P=Symbol(),fn=Symbol(),pn=Symbol(),mn=new TextEncoder,hn=new TextDecoder;function gn(e){return typeof e==`string`?mn.encode(e):hn.decode(e)}var _n,vn;if(Uint8Array.prototype.toBase64)_n=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;_n=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(``)).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}}function yn(e){return typeof e==`string`?vn(e):_n(e)}vn=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:`base64url`})}catch(e){throw M(`The input to be decoded is not correctly encoded.`,A,e)}}:e=>{try{let t=atob(e.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){throw M(`The input to be decoded is not correctly encoded.`,A,e)}};var F=class extends Error{constructor(e,t){var n;super(e,t),O(this,`code`,void 0),this.name=this.constructor.name,this.code=gr,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},bn=class extends Error{constructor(e,t){var n;super(e,t),O(this,`code`,void 0),this.name=this.constructor.name,t!=null&&t.code&&(this.code=t?.code),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};function I(e,t,n){return new bn(e,{code:t,cause:n})}function xn(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw M(`${t} must be a CryptoKey`,j)}(e,t),e.type!==`private`)throw M(`${t} must be a private CryptoKey`,A)}function Sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cn(e){ln(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(cn&&!t.has(`user-agent`)&&t.set(`user-agent`,cn),t.has(`authorization`))throw M(`"options.headers" must not include the "authorization" header name`,A);return t}function wn(e,t){if(t!==void 0){if(typeof t==`function`&&(t=t(e.href)),!(t instanceof AbortSignal))throw M(`"options.signal" must return or be an instance of AbortSignal`,j);return t}}function Tn(e){return e.includes(`//`)?e.replace(`//`,`/`):e}async function En(e,t){return async function(e,t,n,r){if(!(e instanceof URL))throw M(`"${t}" must be an instance of URL`,j);Ln(e,!0!==r?.[N]);let i=n(new URL(e.href)),a=Cn(r?.headers);return a.set(`accept`,`application/json`),(r?.[P]||fetch)(i.href,{body:void 0,headers:Object.fromEntries(a.entries()),method:`GET`,redirect:`manual`,signal:wn(i,r?.signal)})}(e,`issuerIdentifier`,e=>{switch(t?.algorithm){case void 0:case`oidc`:(function(e,t){e.pathname=Tn(`${e.pathname}/${t}`)})(e,`.well-known/openid-configuration`);break;case`oauth2`:(function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];e.pathname===`/`?e.pathname=t:e.pathname=Tn(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,``)}`)})(e,`.well-known/oauth-authorization-server`);break;default:throw M(`"options.algorithm" must be "oidc" (default), or "oauth2"`,A)}return e},t)}function Dn(e,t,n,r,i){try{if(typeof e!=`number`||!Number.isFinite(e))throw M(`${n} must be a number`,j,i);if(e>0)return;if(t){if(e!==0)throw M(`${n} must be a non-negative number`,A,i);return}throw M(`${n} must be a positive number`,A,i)}catch(e){throw r?I(e.message,r,i):e}}function L(e,t,n,r){try{if(typeof e!=`string`)throw M(`${t} must be a string`,j,r);if(e.length===0)throw M(`${t} must not be empty`,A,r)}catch(e){throw n?I(e.message,n,r):e}}function On(e){(function(e,t){if(Qn(e)!==t)throw function(e){let t=`"response" content-type must be `;var n=[...arguments].slice(1);if(n.length>2){let e=n.pop();t+=`${n.join(`, `)}, or ${e}`}else n.length===2?t+=`${n[0]} or ${n[1]}`:t+=n[0];return I(t,yr,e)}(e,t)})(e,`application/json`)}function kn(){return yn(crypto.getRandomValues(new Uint8Array(32)))}function An(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){switch(e.algorithm.hash.name){case`SHA-256`:return`PS256`;case`SHA-384`:return`PS384`;case`SHA-512`:return`PS512`;default:throw new F(`unsupported RsaHashedKeyAlgorithm hash name`,{cause:e})}}(e);case`RSASSA-PKCS1-v1_5`:return function(e){switch(e.algorithm.hash.name){case`SHA-256`:return`RS256`;case`SHA-384`:return`RS384`;case`SHA-512`:return`RS512`;default:throw new F(`unsupported RsaHashedKeyAlgorithm hash name`,{cause:e})}}(e);case`ECDSA`:return function(e){switch(e.algorithm.namedCurve){case`P-256`:return`ES256`;case`P-384`:return`ES384`;case`P-521`:return`ES512`;default:throw new F(`unsupported EcKeyAlgorithm namedCurve`,{cause:e})}}(e);case`Ed25519`:case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return e.algorithm.name;case`EdDSA`:return`Ed25519`;default:throw new F(`unsupported CryptoKey algorithm name`,{cause:e})}}function jn(e){let t=e?.[un];return typeof t==`number`&&Number.isFinite(t)?t:0}function Mn(e){let t=e?.[dn];return typeof t==`number`&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Nn(){return Math.floor(Date.now()/1e3)}function R(e){if(typeof e!=`object`||!e)throw M(`"as" must be an object`,j);L(e.issuer,`"as.issuer"`)}function z(e){if(typeof e!=`object`||!e)throw M(`"client" must be an object`,j);L(e.client_id,`"client.client_id"`)}function Pn(e){return L(e,`"clientSecret"`),(t,n,r,i)=>{r.set(`client_id`,n.client_id),r.set(`client_secret`,e)}}function Fn(e,t){let{key:n,kid:r}=(i=e)instanceof CryptoKey?{key:i}:i?.key instanceof CryptoKey?(i.kid!==void 0&&L(i.kid,`"kid"`),{key:i.key,kid:i.kid}):{};var i;return xn(n,`"clientPrivateKey.key"`),async(e,i,a,o)=>{var s;let c={alg:An(n),kid:r},l=function(e,t){let n=Nn()+jn(t);return{jti:kn(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,i);t==null||(s=t[fn])==null||s.call(t,c,l),a.set(`client_id`,i.client_id),a.set(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),a.set(`client_assertion`,await async function(e,t,n){if(!n.usages.includes(`sign`))throw M(`CryptoKey instances used for signing assertions must include "sign" in their "usages"`,A);let r=`${yn(gn(JSON.stringify(e)))}.${yn(gn(JSON.stringify(t)))}`;return`${r}.${yn(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:Ar(e)};case`RSA-PSS`:switch(kr(e),e.algorithm.hash.name){case`SHA-256`:case`SHA-384`:case`SHA-512`:return{name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new F(`unsupported RSA-PSS hash name`,{cause:e})}case`RSASSA-PKCS1-v1_5`:return kr(e),e.algorithm.name;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:case`Ed25519`:return e.algorithm.name}throw new F(`unsupported CryptoKey algorithm name`,{cause:e})}(n),n,gn(r)))}`}(c,l,n))}}var In=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function Ln(e,t){if(t&&e.protocol!==`https:`)throw I(`only requests to HTTPS are allowed`,xr,e);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw I(`only HTTP and HTTPS requests are allowed`,Sr,e)}function Rn(e,t,n,r){let i;if(typeof e!=`string`||!(i=In(e)))throw I(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Er:Dr,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return Ln(i,r),i}function zn(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Rn(e.mtls_endpoint_aliases[t],t,n,r):Rn(e[t],t,n,r)}var Bn=class extends Error{constructor(e,t){var n;super(e,t),O(this,`cause`,void 0),O(this,`code`,void 0),O(this,`error`,void 0),O(this,`status`,void 0),O(this,`error_description`,void 0),O(this,`response`,void 0),this.name=this.constructor.name,this.code=hr,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,`response`,{enumerable:!1,value:t.response}),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},Vn=class extends Error{constructor(e,t){var n;super(e,t),O(this,`cause`,void 0),O(this,`code`,void 0),O(this,`error`,void 0),O(this,`error_description`,void 0),this.name=this.constructor.name,this.code=_r,this.cause=t.cause,this.error=t.cause.get(`error`),this.error_description=t.cause.get(`error_description`)??void 0,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},Hn=class extends Error{constructor(e,t){var n;super(e,t),O(this,`cause`,void 0),O(this,`code`,void 0),O(this,`response`,void 0),O(this,`status`,void 0),this.name=this.constructor.name,this.code=mr,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,`response`,{enumerable:!1}),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},Un="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Wn=`(`+Un+`)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"`,Gn=`(`+Un+")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)",Kn=RegExp(`^[,\\s]*(`+Un+`)`),qn=RegExp(`^[,\\s]*`+Wn+`[,\\s]*(.*)`),Jn=RegExp(`^[,\\s]*`+Gn+`[,\\s]*(.*)`),Yn=RegExp(`^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)`);async function Xn(e,t,n){if(e.status!==t){let t;throw function(e){let t;if(t=function(e){if(!ln(e,Response))throw M(`"response" must be an instance of Response`,j);let t=e.headers.get(`www-authenticate`);if(t===null)return;let n=[],r=t;for(;r;){let e=r.match(Kn),t=e?.[1].toLowerCase();if(!t)return;let i=r.substring(e[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),o=!!a;r=a?a[1]:void 0;let s={},c;if(o)for(;r;){let t,n;if(e=r.match(qn)){if([,t,n,r]=e,n.includes(`\\`))try{n=JSON.parse(`"${n}"`)}catch{}s[t.toLowerCase()]=n}else{if(!(e=r.match(Jn))){if(e=r.match(Yn)){if(Object.keys(s).length)break;[,c,r]=e;break}return}[,t,n,r]=e,s[t.toLowerCase()]=n}}else r=i||void 0;let l={scheme:t,parameters:s};c&&(l.token68=c),n.push(l)}return n.length?n:void 0}(e))throw new Hn(`server responded with a challenge in the WWW-Authenticate HTTP Header`,{cause:t,response:e})}(e),(t=await async function(e){if(e.status>399&&e.status<500){Or(e),On(e);try{let t=await e.clone().json();if(Sn(t)&&typeof t.error==`string`&&t.error.length)return t}catch{}}}(e))?(await e.body?.cancel(),new Bn(`server responded with an error in the response body`,{cause:t,response:e})):I(`"response" is not a conform ${n} response (unexpected HTTP status code)`,br,e)}}function Zn(e){if(!sr.has(e))throw M(`"options.DPoP" is not a valid DPoPHandle`,A)}function Qn(e){return e.headers.get(`content-type`)?.split(`;`)[0]}async function $n(e,t,n,r,i,a,o){return await n(e,t,i,a),a.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`),(o?.[P]||fetch)(r.href,{body:i,headers:Object.fromEntries(a.entries()),method:`POST`,redirect:`manual`,signal:wn(r,o?.signal)})}async function er(e,t,n,r,i,a){var o;let s=zn(e,`token_endpoint`,t.use_mtls_endpoint_aliases,!0!==a?.[N]);i.set(`grant_type`,r);let c=Cn(a?.headers);c.set(`accept`,`application/json`),a?.DPoP!==void 0&&(Zn(a.DPoP),await a.DPoP.addProof(s,c,`POST`));let l=await $n(e,t,n,s,i,c,a);return a==null||(o=a.DPoP)==null||o.cacheNonce(l,s),l}var tr=new WeakMap,nr=new WeakMap;function rr(e){if(!e.id_token)return;let t=tr.get(e);if(!t)throw M(`"ref" was already garbage collected or did not resolve from the proper sources`,A);return t}async function ir(e,t,n,r,i,a){if(R(e),z(t),!ln(n,Response))throw M(`"response" must be an instance of Response`,j);await Xn(n,200,`Token Endpoint`),Or(n);let o=await Lr(n);if(L(o.access_token,`"response" body "access_token" property`,B,{body:o}),L(o.token_type,`"response" body "token_type" property`,B,{body:o}),o.token_type=o.token_type.toLowerCase(),o.expires_in!==void 0){let e=typeof o.expires_in==`number`?o.expires_in:parseFloat(o.expires_in);Dn(e,!0,`"response" body "expires_in" property`,B,{body:o}),o.expires_in=e}if(o.refresh_token!==void 0&&L(o.refresh_token,`"response" body "refresh_token" property`,B,{body:o}),o.scope!==void 0&&typeof o.scope!=`string`)throw I(`"response" body "scope" property must be a string`,B,{body:o});if(o.id_token!==void 0){L(o.id_token,`"response" body "id_token" property`,B,{body:o});let a=[`aud`,`exp`,`iat`,`iss`,`sub`];!0===t.require_auth_time&&a.push(`auth_time`),t.default_max_age!==void 0&&(Dn(t.default_max_age,!0,`"client.default_max_age"`),a.push(`auth_time`)),r!=null&&r.length&&a.push(...r);let{claims:s,jwt:c}=await async function(e,t,n,r,i){let a,o,{0:s,1:c,length:l}=e.split(`.`);if(l===5){if(i===void 0)throw new F(`JWE decryption is not configured`,{cause:e});e=await i(e),{0:s,1:c,length:l}=e.split(`.`)}if(l!==3)throw I(`Invalid JWT`,B,e);try{a=JSON.parse(gn(yn(s)))}catch(e){throw I(`failed to parse JWT Header body as base64url encoded JSON`,vr,e)}if(!Sn(a))throw I(`JWT Header must be a top level object`,B,e);if(t(a),a.crit!==void 0)throw new F(`no JWT "crit" header parameter extensions are supported`,{cause:{header:a}});try{o=JSON.parse(gn(yn(c)))}catch(e){throw I(`failed to parse JWT Payload body as base64url encoded JSON`,vr,e)}if(!Sn(o))throw I(`JWT Payload must be a top level object`,B,e);let u=Nn()+n;if(o.exp!==void 0){if(typeof o.exp!=`number`)throw I(`unexpected JWT "exp" (expiration time) claim type`,B,{claims:o});if(o.exp<=u-r)throw I(`unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp`,Cr,{claims:o,now:u,tolerance:r,claim:`exp`})}if(o.iat!==void 0&&typeof o.iat!=`number`)throw I(`unexpected JWT "iat" (issued at) claim type`,B,{claims:o});if(o.iss!==void 0&&typeof o.iss!=`string`)throw I(`unexpected JWT "iss" (issuer) claim type`,B,{claims:o});if(o.nbf!==void 0){if(typeof o.nbf!=`number`)throw I(`unexpected JWT "nbf" (not before) claim type`,B,{claims:o});if(o.nbf>u+r)throw I(`unexpected JWT "nbf" (not before) claim value`,Cr,{claims:o,now:u,tolerance:r,claim:`nbf`})}if(o.aud!==void 0&&typeof o.aud!=`string`&&!Array.isArray(o.aud))throw I(`unexpected JWT "aud" (audience) claim type`,B,{claims:o});return{header:a,claims:o,jwt:e}}(o.id_token,Mr.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,`RS256`),jn(t),Mn(t),i).then(ur.bind(void 0,a)).then(or.bind(void 0,e)).then(ar.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&s.aud.length!==1){if(s.azp===void 0)throw I(`ID Token "aud" (audience) claim includes additional untrusted audiences`,wr,{claims:s,claim:`aud`});if(s.azp!==t.client_id)throw I(`unexpected ID Token "azp" (authorized party) claim value`,wr,{expected:t.client_id,claims:s,claim:`azp`})}s.auth_time!==void 0&&Dn(s.auth_time,!0,`ID Token "auth_time" (authentication time)`,B,{claims:s}),nr.set(n,c),tr.set(o,s)}if(a?.[o.token_type]!==void 0)a[o.token_type](n,o);else if(o.token_type!==`dpop`&&o.token_type!==`bearer`)throw new F("unsupported `token_type` value",{cause:{body:o}});return o}function ar(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw I(`unexpected JWT "aud" (audience) claim value`,wr,{expected:e,claims:t.claims,claim:`aud`})}else if(t.claims.aud!==e)throw I(`unexpected JWT "aud" (audience) claim value`,wr,{expected:e,claims:t.claims,claim:`aud`});return t}function or(e,t){let n=e[zr]?.call(e,t)??e.issuer;if(t.claims.iss!==n)throw I(`unexpected JWT "iss" (issuer) claim value`,wr,{expected:n,claims:t.claims,claim:`iss`});return t}var sr=new WeakSet,cr=Symbol(),lr={aud:`audience`,c_hash:`code hash`,client_id:`client id`,exp:`expiration time`,iat:`issued at`,iss:`issuer`,jti:`jwt id`,nonce:`nonce`,s_hash:`state hash`,sub:`subject`,ath:`access token hash`,htm:`http method`,htu:`http uri`,cnf:`confirmation`,auth_time:`authentication time`};function ur(e,t){for(let n of e)if(t.claims[n]===void 0)throw I(`JWT "${n}" (${lr[n]}) claim missing`,B,{claims:t.claims});return t}var dr=Symbol(),fr=Symbol();async function pr(e,t,n,r){return typeof r?.expectedNonce==`string`||typeof r?.maxAge==`number`||r!=null&&r.requireIdToken?async function(e,t,n,r,i,a,o){let s=[];switch(r){case void 0:r=dr;break;case dr:break;default:L(r,`"expectedNonce" argument`),s.push(`nonce`)}switch(i??=t.default_max_age,i){case void 0:i=fr;break;case fr:break;default:Dn(i,!0,`"maxAge" argument`),s.push(`auth_time`)}let c=await ir(e,t,n,s,a,o);L(c.id_token,`"response" body "id_token" property`,B,{body:c});let l=rr(c);if(i!==fr){let e=Nn()+jn(t),n=Mn(t);if(l.auth_time+i<e-n)throw I(`too much time has elapsed since the last End-User authentication`,Cr,{claims:l,now:e,tolerance:n,claim:`auth_time`})}if(r===dr){if(l.nonce!==void 0)throw I(`unexpected ID Token "nonce" claim value`,wr,{expected:void 0,claims:l,claim:`nonce`})}else if(l.nonce!==r)throw I(`unexpected ID Token "nonce" claim value`,wr,{expected:r,claims:l,claim:`nonce`});return c}(e,t,n,r.expectedNonce,r.maxAge,r[pn],r.recognizedTokenTypes):async function(e,t,n,r,i){let a=await ir(e,t,n,void 0,r,i),o=rr(a);if(o){if(t.default_max_age!==void 0){Dn(t.default_max_age,!0,`"client.default_max_age"`);let e=Nn()+jn(t),n=Mn(t);if(o.auth_time+t.default_max_age<e-n)throw I(`too much time has elapsed since the last End-User authentication`,Cr,{claims:o,now:e,tolerance:n,claim:`auth_time`})}if(o.nonce!==void 0)throw I(`unexpected ID Token "nonce" claim value`,wr,{expected:void 0,claims:o,claim:`nonce`})}return a}(e,t,n,r?.[pn],r?.recognizedTokenTypes)}var mr=`OAUTH_WWW_AUTHENTICATE_CHALLENGE`,hr=`OAUTH_RESPONSE_BODY_ERROR`,gr=`OAUTH_UNSUPPORTED_OPERATION`,_r=`OAUTH_AUTHORIZATION_RESPONSE_ERROR`,vr=`OAUTH_PARSE_ERROR`,B=`OAUTH_INVALID_RESPONSE`,yr=`OAUTH_RESPONSE_IS_NOT_JSON`,br=`OAUTH_RESPONSE_IS_NOT_CONFORM`,xr=`OAUTH_HTTP_REQUEST_FORBIDDEN`,Sr=`OAUTH_REQUEST_PROTOCOL_FORBIDDEN`,Cr=`OAUTH_JWT_TIMESTAMP_CHECK_FAILED`,wr=`OAUTH_JWT_CLAIM_COMPARISON_FAILED`,Tr=`OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED`,Er=`OAUTH_MISSING_SERVER_METADATA`,Dr=`OAUTH_INVALID_SERVER_METADATA`;function Or(e){if(e.bodyUsed)throw M(`"response" body has been used already`,A)}function kr(e){let{algorithm:t}=e;if(typeof t.modulusLength!=`number`||t.modulusLength<2048)throw new F(`unsupported ${t.name} modulusLength`,{cause:e})}function Ar(e){let{algorithm:t}=e;switch(t.namedCurve){case`P-256`:return`SHA-256`;case`P-384`:return`SHA-384`;case`P-521`:return`SHA-512`;default:throw new F(`unsupported ECDSA namedCurve`,{cause:e})}}async function jr(e){if(e.method!==`POST`)throw M(`form_post responses are expected to use the POST method`,A,{cause:e});if(Qn(e)!==`application/x-www-form-urlencoded`)throw M(`form_post responses are expected to use the application/x-www-form-urlencoded content-type`,A,{cause:e});return async function(e){if(e.bodyUsed)throw M(`form_post Request instances must contain a readable body`,A,{cause:e});return e.text()}(e)}function Mr(e,t,n,r){if(e===void 0)if(Array.isArray(t)){if(!t.includes(r.alg))throw I(`unexpected JWT "alg" header parameter`,B,{header:r,expected:t,reason:`authorization server metadata`})}else{if(n===void 0)throw I(`missing client or server configuration to verify used JWT "alg" header parameter`,void 0,{client:e,issuer:t,fallback:n});if(typeof n==`string`?r.alg!==n:typeof n==`function`?!n(r.alg):!n.includes(r.alg))throw I(`unexpected JWT "alg" header parameter`,B,{header:r,expected:n,reason:`default value`})}else if(typeof e==`string`?r.alg!==e:!e.includes(r.alg))throw I(`unexpected JWT "alg" header parameter`,B,{header:r,expected:e,reason:`client configuration`})}function Nr(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw I(`"${t}" parameter must be provided only once`,B);return n}var Pr=Symbol(),Fr=Symbol();function Ir(e,t,n,r){if(R(e),z(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw M(`"parameters" must be an instance of URLSearchParams, or URL`,j);if(Nr(n,`response`))throw I(`"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()`,B,{parameters:n});let i=Nr(n,`iss`),a=Nr(n,`state`);if(!i&&e.authorization_response_iss_parameter_supported)throw I(`response parameter "iss" (issuer) missing`,B,{parameters:n});if(i&&i!==e.issuer)throw I(`unexpected "iss" (issuer) response parameter value`,B,{expected:e.issuer,parameters:n});switch(r){case void 0:case Fr:if(a!==void 0)throw I(`unexpected "state" response parameter encountered`,B,{expected:void 0,parameters:n});break;case Pr:break;default:if(L(r,`"expectedState" argument`),a!==r)throw I(a===void 0?`response parameter "state" missing`:`unexpected "state" response parameter value`,B,{expected:r,parameters:n})}if(Nr(n,`error`))throw new Vn(`authorization response from the server is an error`,{cause:n});let o=Nr(n,`id_token`),s=Nr(n,`token`);if(o!==void 0||s!==void 0)throw new F(`implicit and hybrid flows are not supported`);return c=new URLSearchParams(n),sr.add(c),c;var c}async function Lr(e){let t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:On;try{t=await e.json()}catch(t){throw n(e),I(`failed to parse "response" body as JSON`,vr,t)}if(!Sn(t))throw I(`"response" body must be a top level object`,B,{body:t});return t}var Rr=Symbol(),zr=Symbol(),Br=new TextEncoder,Vr=new TextDecoder;function Hr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Ur(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Wr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:Vr.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=Vr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Ur(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var Gr=function(e){return TypeError(`CryptoKey does not support this operation, its ${arguments.length>1&&arguments[1]!==void 0?arguments[1]:`algorithm.name`} must be ${e}`)},Kr=(e,t)=>e.name===t;function qr(e,t){var n;if((n=e.hash,parseInt(n.name.slice(4),10))!==t)throw Gr(`SHA-${t}`,`algorithm.hash`)}function Jr(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!Kr(e.algorithm,`HMAC`))throw Gr(`HMAC`);qr(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!Kr(e.algorithm,`RSASSA-PKCS1-v1_5`))throw Gr(`RSASSA-PKCS1-v1_5`);qr(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!Kr(e.algorithm,`RSA-PSS`))throw Gr(`RSA-PSS`);qr(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!Kr(e.algorithm,`Ed25519`))throw Gr(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!Kr(e.algorithm,t))throw Gr(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!Kr(e.algorithm,`ECDSA`))throw Gr(`ECDSA`);let n=function(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}(t);if(e.algorithm.namedCurve!==n)throw Gr(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}(function(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)})(e,n)}function Yr(e,t){var n=[...arguments].slice(2);if((n=n.filter(Boolean)).length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;if(t==null)e+=` Received ${t}`;else if(typeof t==`function`&&t.name)e+=` Received function ${t.name}`;else if(typeof t==`object`&&t){var r;(r=t.constructor)!=null&&r.name&&(e+=` Received an instance of ${t.constructor.name}`)}return e}var Xr=function(e,t){var n=[...arguments].slice(2);return Yr(`Key for the ${e} algorithm must be `,t,...n)},V=class extends Error{constructor(e,t){var n;super(e,t),O(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};O(V,`code`,`ERR_JOSE_GENERIC`);var H=class extends V{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),O(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),O(this,`claim`,void 0),O(this,`reason`,void 0),O(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}};O(H,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`);var Zr=class extends V{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),O(this,`code`,`ERR_JWT_EXPIRED`),O(this,`claim`,void 0),O(this,`reason`,void 0),O(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}};O(Zr,`code`,`ERR_JWT_EXPIRED`);var Qr=class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}};O(Qr,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`);var U=class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}};O(U,`code`,`ERR_JOSE_NOT_SUPPORTED`),O(class extends V{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,arguments.length>1?arguments[1]:void 0),O(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),O(class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`);var W=class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JWS_INVALID`)}};O(W,`code`,`ERR_JWS_INVALID`);var $r=class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JWT_INVALID`)}};O($r,`code`,`ERR_JWT_INVALID`),O(class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`);var ei=class extends V{constructor(){super(...arguments),O(this,`code`,`ERR_JWKS_INVALID`)}};O(ei,`code`,`ERR_JWKS_INVALID`);var ti=class extends V{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,arguments.length>1?arguments[1]:void 0),O(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}};O(ti,`code`,`ERR_JWKS_NO_MATCHING_KEY`);var ni=class extends V{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,arguments.length>1?arguments[1]:void 0),O(this,Symbol.asyncIterator,void 0),O(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}};O(ni,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`);var ri=class extends V{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,arguments.length>1?arguments[1]:void 0),O(this,`code`,`ERR_JWKS_TIMEOUT`)}};O(ri,`code`,`ERR_JWKS_TIMEOUT`);var ii=class extends V{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,arguments.length>1?arguments[1]:void 0),O(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}};O(ii,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var ai=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},oi=e=>e?.[Symbol.toStringTag]===`KeyObject`,si=e=>ai(e)||oi(e);function ci(e,t,n){try{return Wr(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function li(e){if(typeof(t=e)!=`object`||t===null||Object.prototype.toString.call(e)!==`[object Object]`)return!1;var t;if(Object.getPrototypeOf(e)===null)return!0;let n=e;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}var ui=e=>li(e)&&typeof e.kty==`string`;async function di(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(function(e){return Yr(`Key must be `,e,...[...arguments].slice(1))}(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Jr(t,e,n),t}async function fi(e,t,n,r){let i=await di(e,t,`verify`);(function(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,i);let a=function(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new U(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}var pi=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;async function mi(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=function(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new U(pi)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new U(pi)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new U(pi)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new U(pi)}break;default:throw new U(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}(e),r=k({},e);return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??(!e.d&&!e.priv),e.key_ops??n)}var hi=`given KeyObject instance cannot be used for this algorithm`,gi,_i=async function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];gi||=new WeakMap;let i=gi.get(e);if(i!=null&&i[n])return i[n];let a=await mi(k(k({},t),{},{alg:n}));return r&&Object.freeze(e),i?i[n]=a:gi.set(e,{[n]:a}),a};async function vi(e,t){if(e instanceof Uint8Array||ai(e))return e;if(oi(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return((e,t)=>{gi||=new WeakMap;let n=gi.get(e);if(n!=null&&n[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(hi)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(hi);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(hi);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(hi)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(hi);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(hi);return n?n[t]=a:gi.set(e,{[t]:a}),a})(e,t)}catch(e){if(e instanceof TypeError)throw e}return _i(e,e.export({format:`jwk`}),t)}if(ui(e))return e.k?Wr(e.k):_i(e,e,t,!0);throw Error(`unreachable`)}var yi=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},bi=e=>{let t=e.data[e.pos++];if(128&t){let n=127&t,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},xi=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},Si=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Ci=e=>{let t=(e=>(xi(e,6,`Expected algorithm OID`),Si(e,bi(e))))(e);if(yi(t,[43,101,110]))return`X25519`;if(!yi(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);xi(e,6,`Expected curve OID`);let n=Si(e,bi(e));for(let{name:e,oid:t}of[{name:`P-256`,oid:[42,134,72,206,61,3,1,7]},{name:`P-384`,oid:[43,129,4,0,34]},{name:`P-521`,oid:[43,129,4,0,35]}])if(yi(n,t))return e;throw Error(`Unsupported named curve`)},wi=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new U(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new U(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},Ti=(e,t,n)=>{var r;let i=((e,t)=>Ur(e.replace(t,``)))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),a=n;return t!=null&&(r=t.startsWith)!=null&&r.call(t,`ECDH-ES`)&&(a||={},a.getNamedCurve=e=>{let t={data:e,pos:0};return function(e){xi(e,48,`Invalid PKCS#8 structure`),bi(e),xi(e,2,`Expected version field`);let t=bi(e);e.pos+=t,xi(e,48,`Expected algorithm identifier`),bi(e),e.pos}(t),Ci(t)}),wi(`pkcs8`,i,t,a)},Ei=e=>e?.[Symbol.toStringTag],Di=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){var r,i;let a;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):a=n;break;case e.startsWith(`PBES2`):a=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):a=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):a=`wrapKey`;break;case n===`decrypt`:a=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`}if(a&&!1===((r=t.key_ops)==null||(i=r.includes)==null?void 0:i.call(r,a)))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${a}" when present`)}return!0};function Oi(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:((e,t,n)=>{if(!(t instanceof Uint8Array)){if(ui(t)){if((e=>e.kty===`oct`&&typeof e.k==`string`)(t)&&Di(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!si(t))throw TypeError(Xr(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${Ei(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,n);break;default:((e,t,n)=>{if(ui(t))switch(n){case`decrypt`:case`sign`:if((e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`))(t)&&Di(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if((e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0)(t)&&Di(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!si(t))throw TypeError(Xr(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${Ei(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${Ei(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${Ei(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${Ei(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${Ei(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,n)}}var ki,Ai,ji,Mi;(typeof navigator>`u`||(ki=navigator.userAgent)==null||(Ai=ki.startsWith)==null||!Ai.call(ki,`Mozilla/5.0 `))&&(Mi=`openid-client/v6.8.3`,ji={"user-agent":Mi});var G=e=>Ni.get(e),Ni,Pi;function Fi(e){return e===void 0?(Pi||=new WeakMap,(e,t,n,r)=>{let i;return(i=Pi.get(t))||(function(e,t){if(typeof e!=`string`)throw zi(`${t} must be a string`,Ri);if(e.length===0)throw zi(`${t} must not be empty`,Li)}(t.client_secret,`"metadata.client_secret"`),i=Pn(t.client_secret),Pi.set(t,i)),i(e,t,n,r)}):Pn(e)}var Ii=P,Li=`ERR_INVALID_ARG_VALUE`,Ri=`ERR_INVALID_ARG_TYPE`;function zi(e,t,n){let r=TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function Bi(e){return async function(e){return L(e,`codeVerifier`),yn(await crypto.subtle.digest(`SHA-256`,gn(e)))}(e)}function Vi(){return kn()}var Hi=class extends Error{constructor(e,t){var n;super(e,t),O(this,`code`,void 0),this.name=this.constructor.name,this.code=t?.code,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};function K(e,t,n){return new Hi(e,{cause:t,code:n})}function q(e){if(e instanceof TypeError||e instanceof Hi||e instanceof Bn||e instanceof Vn||e instanceof Hn)throw e;if(e instanceof bn)switch(e.code){case xr:throw K(`only requests to HTTPS are allowed`,e,e.code);case Sr:throw K(`only requests to HTTP or HTTPS are allowed`,e,e.code);case br:throw K(`unexpected HTTP response status code`,e.cause,e.code);case yr:throw K(`unexpected response content-type`,e.cause,e.code);case vr:throw K(`parsing error occured`,e,e.code);case B:throw K(`invalid response encountered`,e,e.code);case wr:throw K(`unexpected JWT claim value encountered`,e,e.code);case Tr:throw K(`unexpected JSON attribute value encountered`,e,e.code);case Cr:throw K(`JWT timestamp claim value failed validation`,e,e.code);default:throw K(e.message,e,e.code)}if(e instanceof F)throw K(`unsupported operation`,e,e.code);if(e instanceof DOMException)switch(e.name){case`OperationError`:throw K(`runtime operation error`,e,gr);case`NotSupportedError`:throw K(`runtime unsupported operation`,e,gr);case`TimeoutError`:throw K(`operation timed out`,e,`OAUTH_TIMEOUT`);case`AbortError`:throw K(`operation aborted`,e,`OAUTH_ABORT`)}throw new Hi(`something went wrong`,{cause:e})}async function Ui(e,t,n,r,i){let a=new Gi(await async function(e,t){var n;if(!(e instanceof URL))throw zi(`"server" must be an instance of URL`,Ri);let r=!e.href.includes(`/.well-known/`),i=t?.timeout??30,a=AbortSignal.timeout(1e3*i),o=await(r?En(e,{algorithm:t?.algorithm,[P]:t?.[Ii],[N]:t==null||(n=t.execute)==null?void 0:n.includes(Zi),signal:a,headers:new Headers(ji)}):(t?.[Ii]||fetch)((Ln(e,t==null||(s=t.execute)==null||!s.includes(Zi)),e.href),{headers:Object.fromEntries(new Headers(k({accept:`application/json`},ji)).entries()),body:void 0,method:`GET`,redirect:`manual`,signal:a})).then(e=>async function(e,t){let n=e;if(!(n instanceof URL)&&n!==Rr)throw M(`"expectedIssuerIdentifier" must be an instance of URL`,j);if(!ln(t,Response))throw M(`"response" must be an instance of Response`,j);if(t.status!==200)throw I(`"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)`,br,t);Or(t);let r=await Lr(t);if(L(r.issuer,`"response" body "issuer" property`,B,{body:r}),n!==Rr&&new URL(r.issuer).href!==n.href)throw I(`"response" body "issuer" property does not match the expected value`,Tr,{expected:n.href,body:r,attribute:`issuer`});return r}(Rr,e)).catch(q);var s;return r&&new URL(o.issuer).href!==e.href&&(function(e,t,n){return!(e.origin!==`https://login.microsoftonline.com`||n!=null&&n.algorithm&&n.algorithm!==`oidc`||(t[Wi]=!0,0))}(e,o,t)||function(e,t){return!(!e.hostname.endsWith(`.b2clogin.com`)||t!=null&&t.algorithm&&t.algorithm!==`oidc`)}(e,t)||(()=>{throw new Hi(`discovered metadata issuer does not match the expected issuer`,{code:Tr,cause:{expected:e.href,body:o,attribute:`issuer`}})})()),o}(e,i),t,n,r),o=G(a);if(i!=null&&i[Ii]&&(o.fetch=i[Ii]),i!=null&&i.timeout&&(o.timeout=i.timeout),i!=null&&i.execute)for(let e of i.execute)e(a);return a}new TextDecoder;var Wi=Symbol(),Gi=class{constructor(e,t,n,r){if(typeof t!=`string`||!t.length)throw zi(`"clientId" must be a non-empty string`,Ri);if(typeof n==`string`&&(n={client_secret:n}),n?.client_id!==void 0&&t!==n.client_id)throw zi(`"clientId" and "metadata.client_id" must be the same`,Li);let i=k(k({},structuredClone(n)),{},{client_id:t}),a;i[un]=n?.[un]??0,i[dn]=n?.[dn]??30,a=r||(typeof i.client_secret==`string`&&i.client_secret.length?Fi(i.client_secret):(e,t,n,r)=>{n.set(`client_id`,t.client_id)});let o=Object.freeze(i),s=structuredClone(e);Wi in e&&(s[zr]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace(`{tenantid}`,n)});let c=Object.freeze(s);Ni||=new WeakMap,Ni.set(this,{__proto__:null,as:c,c:o,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let e=structuredClone(G(this).as);return function(e){Object.defineProperties(e,function(e){return{supportsPKCE:{__proto__:null,value(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`S256`;return!0===e.code_challenge_methods_supported?.includes(t)}}}}(e))}(e),e}clientMetadata(){return structuredClone(G(this).c)}get timeout(){return G(this).timeout}set timeout(e){G(this).timeout=e}get[Ii](){return G(this).fetch}set[Ii](e){G(this).fetch=e}};function Ki(e){Object.defineProperties(e,function(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return rr(this)}catch{return}}}}}(e))}async function qi(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=e.headers.get(`retry-after`)?.trim();if(i===void 0)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else{let e=new Date(i);if(Number.isFinite(e.getTime())){let t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3))}}if(r&&!Number.isFinite(a))throw new bn(`invalid Retry-After header value`,{cause:e});a>t&&await Ji(a-t,n)}function Ji(e,t){return new Promise((n,r)=>{let i=e=>{try{t.throwIfAborted()}catch(e){r(e);return}if(e<=0)return void n();let a=Math.min(e,5);setTimeout(()=>i(e-a),1e3*a)};i(e)})}async function Yi(e,t){ra(e);let{as:n,c:r,auth:i,fetch:a,tlsOnly:o,timeout:s}=G(e);return async function(e,t,n,r,i){R(e),z(t);let a=zn(e,`backchannel_authentication_endpoint`,t.use_mtls_endpoint_aliases,!0!==i?.[N]),o=new URLSearchParams(r);o.set(`client_id`,t.client_id);let s=Cn(i?.headers);return s.set(`accept`,`application/json`),$n(e,t,n,a,o,s,i)}(n,r,i,t,{[P]:a,[N]:!o,headers:new Headers(ji),signal:ia(s)}).then(e=>async function(e,t,n){if(R(e),z(t),!ln(n,Response))throw M(`"response" must be an instance of Response`,j);await Xn(n,200,`Backchannel Authentication Endpoint`),Or(n);let r=await Lr(n);L(r.auth_req_id,`"response" body "auth_req_id" property`,B,{body:r});let i=typeof r.expires_in==`number`?r.expires_in:parseFloat(r.expires_in);return Dn(i,!0,`"response" body "expires_in" property`,B,{body:r}),r.expires_in=i,r.interval!==void 0&&Dn(r.interval,!1,`"response" body "interval" property`,B,{body:r}),r}(n,r,e)).catch(q)}async function Xi(e,t,n,r){ra(e),n=new URLSearchParams(n);let i=t.interval??5,a=r?.signal??AbortSignal.timeout(1e3*t.expires_in);try{await Ji(i,a)}catch(e){q(e)}let{as:o,c:s,auth:c,fetch:l,tlsOnly:u,nonRepudiation:d,timeout:f,decrypt:p}=G(e),m=(i,o)=>Xi(e,k(k({},t),{},{interval:i}),n,k(k({},r),{},{signal:a,flag:o})),h=await async function(e,t,n,r,i){R(e),z(t),L(r,`"authReqId"`);let a=new URLSearchParams(i?.additionalParameters);return a.set(`auth_req_id`,r),er(e,t,n,`urn:openid:params:grant-type:ciba`,a,i)}(o,s,c,t.auth_req_id,{[P]:l,[N]:!u,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(ji),signal:a.aborted?a:ia(f)}).catch(q);if(h.status===503&&h.headers.has(`retry-after`))return await qi(h,i,a,!0),await h.body?.cancel(),m(i);let g=async function(e,t,n,r){return ir(e,t,n,void 0,r?.[pn],r?.recognizedTokenTypes)}(o,s,h,{[pn]:p}),_;try{_=await g}catch(e){if(aa(e,r))return m(i,oa);if(e instanceof Bn)switch(e.error){case`slow_down`:i+=5;case`authorization_pending`:return await qi(e.response,i,a),m(i)}q(e)}return _.id_token&&await d?.(h),Ki(_),_}function Zi(e){G(e).tlsOnly=!1}async function Qi(e,t,n,r,i){if(ra(e),!(i?.flag===oa||t instanceof URL||function(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}(t,`Request`)))throw zi(`"currentUrl" must be an instance of URL, or Request`,Ri);let a,o,{as:s,c,auth:l,fetch:u,tlsOnly:d,jarm:f,hybrid:p,nonRepudiation:m,timeout:h,decrypt:g,implicit:_}=G(e);if(i?.flag===oa)a=i.authResponse,o=i.redirectUri;else{if(!(t instanceof URL)){let e=t;switch(t=new URL(t.url),e.method){case`GET`:break;case`POST`:let n=new URLSearchParams(await jr(e));if(p)t.hash=n.toString();else for(let[e,r]of n.entries())t.searchParams.append(e,r);break;default:throw zi(`unexpected Request HTTP method`,Li)}}switch(o=function(e){return(e=new URL(e)).search=``,e.hash=``,e.href}(t),!0){case!!f:a=await f(t,n?.expectedState);break;case!!p:a=await p(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!_:throw TypeError(`authorizationCodeGrant() cannot be used by response_type=id_token clients`);default:try{a=Ir(s,c,t.searchParams,n?.expectedState)}catch(e){q(e)}}}let v=await async function(e,t,n,r,i,a,o){if(R(e),z(t),!sr.has(r))throw M(`"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()`,A);L(i,`"redirectUri"`);let s=Nr(r,`code`);if(!s)throw I(`no authorization code in "callbackParameters"`,B);let c=new URLSearchParams(o?.additionalParameters);return c.set(`redirect_uri`,i),c.set(`code`,s),a!==cr&&(L(a,`"codeVerifier"`),c.set(`code_verifier`,a)),er(e,t,n,`authorization_code`,c,o)}(s,c,l,a,o,n?.pkceCodeVerifier||cr,{additionalParameters:r,[P]:u,[N]:!d,DPoP:i?.DPoP,headers:new Headers(ji),signal:ia(h)}).catch(q);typeof n?.expectedNonce!=`string`&&typeof n?.maxAge!=`number`||(n.idTokenExpected=!0);let y=pr(s,c,v,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[pn]:g}),b;try{b=await y}catch(t){if(aa(t,i))return Qi(e,void 0,n,r,k(k({},i),{},{flag:oa,authResponse:a,redirectUri:o}));q(t)}return b.id_token&&await m?.(v),Ki(b),b}async function $i(e,t,n,r){ra(e),n=new URLSearchParams(n);let{as:i,c:a,auth:o,fetch:s,tlsOnly:c,nonRepudiation:l,timeout:u,decrypt:d}=G(e),f=await async function(e,t,n,r,i){R(e),z(t),L(r,`"refreshToken"`);let a=new URLSearchParams(i?.additionalParameters);return a.set(`refresh_token`,r),er(e,t,n,`refresh_token`,a,i)}(i,a,o,t,{[P]:s,[N]:!c,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(ji),signal:ia(u)}).catch(q),p=async function(e,t,n,r){return ir(e,t,n,void 0,r?.[pn],r?.recognizedTokenTypes)}(i,a,f,{[pn]:d}),m;try{m=await p}catch(i){if(aa(i,r))return $i(e,t,n,k(k({},r),{},{flag:oa}));q(i)}return m.id_token&&await l?.(f),Ki(m),m}async function ea(e,t,n){ra(e),t=new URLSearchParams(t);let{as:r,c:i,auth:a,fetch:o,tlsOnly:s,timeout:c}=G(e),l=async function(e,t,n,r){return ir(e,t,n,void 0,r?.[pn],r?.recognizedTokenTypes)}(r,i,await async function(e,t,n,r,i){return R(e),z(t),er(e,t,n,`client_credentials`,new URLSearchParams(r),i)}(r,i,a,t,{[P]:o,[N]:!s,DPoP:n?.DPoP,headers:new Headers(ji),signal:ia(c)}).catch(q)),u;try{u=await l}catch(r){if(aa(r,n))return ea(e,t,k(k({},n),{},{flag:oa}));q(r)}return Ki(u),u}function ta(e,t){ra(e);let{as:n,c:r,tlsOnly:i,hybrid:a,jarm:o,implicit:s}=G(e),c=zn(n,`authorization_endpoint`,!1,i);if((t=new URLSearchParams(t)).has(`client_id`)||t.set(`client_id`,r.client_id),!t.has(`request_uri`)&&!t.has(`request`)){if(t.has(`response_type`)||t.set(`response_type`,a?`code id_token`:s?`id_token`:`code`),s&&!t.has(`nonce`))throw zi(`response_type=id_token clients must provide a nonce parameter in their authorization request parameters`,Li);o&&t.set(`response_mode`,`jwt`)}for(let[e,n]of t.entries())c.searchParams.append(e,n);return c}async function na(e,t,n){ra(e);let r=ta(e,t),{as:i,c:a,auth:o,fetch:s,tlsOnly:c,timeout:l}=G(e),u=async function(e,t,n){if(R(e),z(t),!ln(n,Response))throw M(`"response" must be an instance of Response`,j);await Xn(n,201,`Pushed Authorization Request Endpoint`),Or(n);let r=await Lr(n);L(r.request_uri,`"response" body "request_uri" property`,B,{body:r});let i=typeof r.expires_in==`number`?r.expires_in:parseFloat(r.expires_in);return Dn(i,!0,`"response" body "expires_in" property`,B,{body:r}),r.expires_in=i,r}(i,a,await async function(e,t,n,r,i){var a;R(e),z(t);let o=zn(e,`pushed_authorization_request_endpoint`,t.use_mtls_endpoint_aliases,!0!==i?.[N]),s=new URLSearchParams(r);s.set(`client_id`,t.client_id);let c=Cn(i?.headers);c.set(`accept`,`application/json`),i?.DPoP!==void 0&&(Zn(i.DPoP),await i.DPoP.addProof(o,c,`POST`));let l=await $n(e,t,n,o,s,c,i);return i==null||(a=i.DPoP)==null||a.cacheNonce(l,o),l}(i,a,o,r.searchParams,{[P]:s,[N]:!c,DPoP:n?.DPoP,headers:new Headers(ji),signal:ia(l)}).catch(q)),d;try{d=await u}catch(r){if(aa(r,n))return na(e,t,k(k({},n),{},{flag:oa}));q(r)}return ta(e,{request_uri:d.request_uri})}function ra(e){if(!(e instanceof Gi))throw zi(`"config" must be an instance of Configuration`,Ri);if(Object.getPrototypeOf(e)!==Gi.prototype)throw zi(`subclassing Configuration is not allowed`,Li)}function ia(e){return e?AbortSignal.timeout(1e3*e):void 0}function aa(e,t){return!(t==null||!t.DPoP||t.flag===oa)&&function(e){if(e instanceof Hn){let{0:t,length:n}=e.cause;return n===1&&t.scheme===`dpop`&&t.parameters.error===`use_dpop_nonce`}return e instanceof Bn&&e.error===`use_dpop_nonce`}(e)}Object.freeze(Gi.prototype);var oa=Symbol();async function sa(e,t,n,r){ra(e);let{as:i,c:a,auth:o,fetch:s,tlsOnly:c,timeout:l,decrypt:u}=G(e),d=await async function(e,t,n,r,i,a){return R(e),z(t),L(r,`"grantType"`),er(e,t,n,r,new URLSearchParams(i),a)}(i,a,o,t,new URLSearchParams(n),{[P]:s,[N]:!c,DPoP:r?.DPoP,headers:new Headers(ji),signal:ia(l)}).then(e=>{let n;return t===`urn:ietf:params:oauth:grant-type:token-exchange`&&(n={n_a:()=>{}}),async function(e,t,n,r){return ir(e,t,n,void 0,r?.[pn],r?.recognizedTokenTypes)}(i,a,e,{[pn]:u,recognizedTokenTypes:n})}).catch(q);return Ki(d),d}async function ca(e,t,n){if(!li(e))throw new W(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new W(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new W(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new W(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new W(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!li(e.header))throw new W(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=Wr(e.protected);r=JSON.parse(Vr.decode(t))}catch{throw new W(`JWS Protected Header is invalid`)}if(!function(){let e=[...arguments].filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(let n of e){let e=Object.keys(n);if(t&&t.size!==0)for(let n of e){if(t.has(n))return!1;t.add(n)}else t=new Set(e)}return!0}(r,e.header))throw new W(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i=k(k({},r),e.header),a=function(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new U(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}(W,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new W(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new W(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&function(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Qr(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new W(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new W(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),Oi(s,t,`verify`);let u=function(){var e=[...arguments];let t=e.reduce((e,t)=>{let{length:n}=t;return e+n},0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}(e.protected===void 0?new Uint8Array:Hr(e.protected),Hr(`.`),typeof e.payload==`string`?o?Hr(e.payload):Br.encode(e.payload):e.payload),d=ci(e.signature,`signature`,W),f=await vi(t,s);if(!await fi(s,f,d,u))throw new ii;let p;p=o?ci(e.payload,`payload`,W):typeof e.payload==`string`?Br.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?k(k({},m),{},{key:f}):m}var la=86400,ua=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function da(e){let t=ua.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r;switch(t[3].toLowerCase()){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:r=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:r=Math.round(60*n);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:r=Math.round(3600*n);break;case`day`:case`days`:case`d`:r=Math.round(n*la);break;case`week`:case`weeks`:case`w`:r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return t[1]===`-`||t[4]===`ago`?-r:r}var fa=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`;function pa(e,t){let n,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};try{n=JSON.parse(Vr.decode(t))}catch{}if(!li(n))throw new $r(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=r;if(i&&(typeof e.typ!=`string`||fa(e.typ)!==fa(i)))throw new H(`unexpected "typ" JWT header value`,n,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=r,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in n))throw new H(`missing required "${e}" claim`,n,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new H(`unexpected "iss" claim value`,n,`iss`,`check_failed`);if(s&&n.sub!==s)throw new H(`unexpected "sub" claim value`,n,`sub`,`check_failed`);if(c&&(d=n.aud,f=typeof c==`string`?[c]:c,!(typeof d==`string`?f.includes(d):Array.isArray(d)&&f.some(Set.prototype.has.bind(new Set(d))))))throw new H(`unexpected "aud" claim value`,n,`aud`,`check_failed`);var d,f;let p;switch(typeof r.clockTolerance){case`string`:p=da(r.clockTolerance);break;case`number`:p=r.clockTolerance;break;case`undefined`:p=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:m}=r,h=(g=m||new Date,Math.floor(g.getTime()/1e3));var g;if((n.iat!==void 0||l)&&typeof n.iat!=`number`)throw new H(`"iat" claim must be a number`,n,`iat`,`invalid`);if(n.nbf!==void 0){if(typeof n.nbf!=`number`)throw new H(`"nbf" claim must be a number`,n,`nbf`,`invalid`);if(n.nbf>h+p)throw new H(`"nbf" claim timestamp check failed`,n,`nbf`,`check_failed`)}if(n.exp!==void 0){if(typeof n.exp!=`number`)throw new H(`"exp" claim must be a number`,n,`exp`,`invalid`);if(n.exp<=h-p)throw new Zr(`"exp" claim timestamp check failed`,n,`exp`,`check_failed`)}if(l){let e=h-n.iat;if(e-p>(typeof l==`number`?l:da(l)))throw new Zr(`"iat" claim timestamp check failed (too far in the past)`,n,`iat`,`check_failed`);if(e<0-p)throw new H(`"iat" claim timestamp check failed (it should be in the past)`,n,`iat`,`check_failed`)}return n}async function ma(e,t,n){var r;let i=await async function(e,t,n){if(e instanceof Uint8Array&&(e=Vr.decode(e)),typeof e!=`string`)throw new W(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new W(`Invalid Compact JWS`);let s=await ca({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?k(k({},c),{},{key:s.key}):c}(e,t,n);if((r=i.protectedHeader.crit)!=null&&r.includes(`b64`)&&!1===i.protectedHeader.b64)throw new $r(`JWTs MUST NOT use unencoded payload`);let a={payload:pa(i.protectedHeader,i.payload,n),protectedHeader:i.protectedHeader};return typeof t==`function`?k(k({},a),{},{key:i.key}):a}function ha(e){return li(e)}var ga,_a,va=new WeakMap,ya=new WeakMap,ba=class{constructor(e){if(E(this,va,void 0),E(this,ya,new WeakMap),!function(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(ha)}(e))throw new ei(`JSON Web Key Set malformed`);D(va,this,structuredClone(e))}jwks(){return T(va,this)}async getKey(e,t){let{alg:n,kid:r}=k(k({},e),t?.header),i=function(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new U(`Unsupported "alg" value for a JSON Web Key Set`)}}(n),a=T(va,this).keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),!t||typeof e.alg!=`string`&&i!==`AKP`||(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`}return t}),{0:o,length:s}=a;if(s===0)throw new ti;if(s!==1){let e=new ni,t=T(ya,this);throw e[Symbol.asyncIterator]=rn(function*(){for(let e of a)try{yield yield $t(xa(t,e,n))}catch{}}),e}return xa(T(ya,this),o,n)}};async function xa(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await async function(e,t,n){if(!li(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return Wr(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new U(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return mi(k(k({},e),{},{alg:t,ext:r}));case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return mi(k(k({},e),{},{ext:r}));case`EC`:case`OKP`:return mi(k(k({},e),{},{alg:t,ext:r}));default:throw new U(`Unsupported "kty" (Key Type) Parameter value`)}}(k(k({},t),{},{ext:!0}),n);if(e instanceof Uint8Array||e.type!==`public`)throw new ei(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Sa(e){let t=new ba(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}var Ca;(typeof navigator>`u`||(ga=navigator.userAgent)==null||(_a=ga.startsWith)==null||!_a.call(ga,`Mozilla/5.0 `))&&(Ca=`jose/v6.2.2`);var wa=Symbol(),Ta=Symbol(),Ea=new WeakMap,Da=new WeakMap,Oa=new WeakMap,ka=new WeakMap,Aa=new WeakMap,ja=new WeakMap,Ma=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Fa=new WeakMap,Ia=class{constructor(e,t){if(E(this,Ea,void 0),E(this,Da,void 0),E(this,Oa,void 0),E(this,ka,void 0),E(this,Aa,void 0),E(this,ja,void 0),E(this,Ma,void 0),E(this,Na,void 0),E(this,Pa,void 0),E(this,Fa,void 0),!(e instanceof URL))throw TypeError(`url must be an instance of URL`);var n,r;D(Ea,this,new URL(e.href)),D(Da,this,typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3),D(Oa,this,typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4),D(ka,this,typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5),D(Ma,this,new Headers(t?.headers)),Ca&&!T(Ma,this).has(`User-Agent`)&&T(Ma,this).set(`User-Agent`,Ca),T(Ma,this).has(`accept`)||(T(Ma,this).set(`accept`,`application/json`),T(Ma,this).append(`accept`,`application/jwk-set+json`)),D(Na,this,t?.[wa]),t?.[Ta]!==void 0&&(D(Fa,this,t?.[Ta]),n=t?.[Ta],r=T(ka,this),typeof n==`object`&&n&&`uat`in n&&typeof n.uat==`number`&&!(Date.now()-n.uat>=r)&&`jwks`in n&&li(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,li)&&(D(Aa,this,T(Fa,this).uat),D(Pa,this,Sa(T(Fa,this).jwks))))}pendingFetch(){return!!T(ja,this)}coolingDown(){return typeof T(Aa,this)==`number`&&Date.now()<T(Aa,this)+T(Oa,this)}fresh(){return typeof T(Aa,this)==`number`&&Date.now()<T(Aa,this)+T(ka,this)}jwks(){return T(Pa,this)?.jwks()}async getKey(e,t){T(Pa,this)&&this.fresh()||await this.reload();try{return await T(Pa,this).call(this,e,t)}catch(n){if(n instanceof ti&&!1===this.coolingDown())return await this.reload(),T(Pa,this).call(this,e,t);throw n}}async reload(){T(ja,this)&&(typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`)&&D(ja,this,void 0),T(ja,this)||D(ja,this,async function(e,t,n){let r=await(arguments.length>3&&arguments[3]!==void 0?arguments[3]:fetch)(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new ri:e});if(r.status!==200)throw new V(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await r.json()}catch{throw new V(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}(T(Ea,this).href,T(Ma,this),AbortSignal.timeout(T(Da,this)),T(Na,this)).then(e=>{D(Pa,this,Sa(e)),T(Fa,this)&&(T(Fa,this).uat=Date.now(),T(Fa,this).jwks=e),D(Aa,this,Date.now()),D(ja,this,void 0)}).catch(e=>{throw D(ja,this,void 0),e})),await T(ja,this)}},La=[`mfaToken`],Ra=[`mfaToken`],za,Ba,Va,J,Ha,Ua,Y,Wa,Ga,X,Ka,qa,Ja,Ya,Xa,Z,Za=class extends Error{constructor(e,t){super(t),O(this,`code`,void 0),this.name=`NotSupportedError`,this.code=e}},Qa=class extends Error{constructor(e,t,n){super(t),O(this,`cause`,void 0),O(this,`code`,void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},$a=class extends Qa{constructor(e,t){super(`token_by_code_error`,e,t),this.name=`TokenByCodeError`}},eo=class extends Qa{constructor(e,t){super(`token_by_client_credentials_error`,e,t),this.name=`TokenByClientCredentialsError`}},to=class extends Qa{constructor(e,t){super(`token_by_refresh_token_error`,e,t),this.name=`TokenByRefreshTokenError`}},no=class extends Qa{constructor(e,t){super(`token_by_password_error`,e,t),this.name=`TokenByPasswordError`}},ro=class extends Qa{constructor(e,t){super(`token_for_connection_error`,e,t),this.name=`TokenForConnectionErrorCode`}},io=class extends Qa{constructor(e,t){super(`token_exchange_error`,e,t),this.name=`TokenExchangeError`}},ao=class extends Error{constructor(e){super(e),O(this,`code`,`verify_logout_token_error`),this.name=`VerifyLogoutTokenError`}},oo=class extends Qa{constructor(e){super(`backchannel_authentication_error`,`There was an error when trying to use Client-Initiated Backchannel Authentication.`,e),O(this,`code`,`backchannel_authentication_error`),this.name=`BackchannelAuthenticationError`}},so=class extends Qa{constructor(e){super(`build_authorization_url_error`,`There was an error when trying to build the authorization URL.`,e),this.name=`BuildAuthorizationUrlError`}},co=class extends Qa{constructor(e){super(`build_link_user_url_error`,`There was an error when trying to build the Link User URL.`,e),this.name=`BuildLinkUserUrlError`}},lo=class extends Qa{constructor(e){super(`build_unlink_user_url_error`,`There was an error when trying to build the Unlink User URL.`,e),this.name=`BuildUnlinkUserUrlError`}},uo=class extends Error{constructor(){super(`The client secret or client assertion signing key must be provided.`),O(this,`code`,`missing_client_auth_error`),this.name=`MissingClientAuthError`}};function fo(e){return Object.entries(e).filter(e=>{let[,t]=e;return t!==void 0}).reduce((e,t)=>k(k({},e),{},{[t[0]]:t[1]}),{})}var po=class extends Error{constructor(e,t,n){super(t),O(this,`cause`,void 0),O(this,`code`,void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},mo=class extends po{constructor(e,t){super(`mfa_list_authenticators_error`,e,t),this.name=`MfaListAuthenticatorsError`}},ho=class extends po{constructor(e,t){super(`mfa_enrollment_error`,e,t),this.name=`MfaEnrollmentError`}},go=class extends po{constructor(e,t){super(`mfa_delete_authenticator_error`,e,t),this.name=`MfaDeleteAuthenticatorError`}},_o=class extends po{constructor(e,t){super(`mfa_challenge_error`,e,t),this.name=`MfaChallengeError`}};function vo(e){return{id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var yo=(za=new WeakMap,Ba=new WeakMap,Va=new WeakMap,class{constructor(e){E(this,za,void 0),E(this,Ba,void 0),E(this,Va,void 0),D(za,this,`https://${e.domain}`),D(Ba,this,e.clientId),D(Va,this,e.customFetch??function(){return fetch(...arguments)})}async listAuthenticators(e){let t=`${T(za,this)}/mfa/authenticators`,{mfaToken:n}=e,r=await T(Va,this).call(this,t,{method:`GET`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`}});if(!r.ok){let e=await r.json();throw new mo(e.error_description||`Failed to list authenticators`,e)}return(await r.json()).map(vo)}async enrollAuthenticator(e){let t=`${T(za,this)}/mfa/associate`,{mfaToken:n}=e,r=nn(e,La),i={authenticator_types:r.authenticatorTypes};`oobChannels`in r&&(i.oob_channels=r.oobChannels),`phoneNumber`in r&&r.phoneNumber&&(i.phone_number=r.phoneNumber),`email`in r&&r.email&&(i.email=r.email);let a=await T(Va,this).call(this,t,{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok){let e=await a.json();throw new ho(e.error_description||`Failed to enroll authenticator`,e)}return function(e){if(e.authenticator_type===`otp`)return{authenticatorType:`otp`,secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if(e.authenticator_type===`oob`)return{authenticatorType:`oob`,oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes};throw Error(`Unexpected authenticator type: ${e.authenticator_type}`)}(await a.json())}async deleteAuthenticator(e){let{authenticatorId:t,mfaToken:n}=e,r=`${T(za,this)}/mfa/authenticators/${encodeURIComponent(t)}`,i=await T(Va,this).call(this,r,{method:`DELETE`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`}});if(!i.ok){let e=await i.json();throw new go(e.error_description||`Failed to delete authenticator`,e)}}async challengeAuthenticator(e){let t=`${T(za,this)}/mfa/challenge`,{mfaToken:n}=e,r=nn(e,Ra),i={mfa_token:n,client_id:T(Ba,this),challenge_type:r.challengeType};r.authenticatorId&&(i.authenticator_id=r.authenticatorId);let a=await T(Va,this).call(this,t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok){let e=await a.json();throw new _o(e.error_description||`Failed to challenge authenticator`,e)}return function(e){let t={challengeType:e.challenge_type};return e.oob_code!==void 0&&(t.oobCode=e.oob_code),e.binding_method!==void 0&&(t.bindingMethod=e.binding_method),t}(await a.json())}}),bo=class e{constructor(e,t,n,r,i,a,o){O(this,`accessToken`,void 0),O(this,`idToken`,void 0),O(this,`refreshToken`,void 0),O(this,`expiresAt`,void 0),O(this,`scope`,void 0),O(this,`claims`,void 0),O(this,`authorizationDetails`,void 0),O(this,`tokenType`,void 0),O(this,`issuedTokenType`,void 0),this.accessToken=e,this.idToken=n,this.refreshToken=r,this.expiresAt=t,this.scope=i,this.claims=a,this.authorizationDetails=o}static fromTokenEndpointResponse(t){let n=t.id_token?t.claims():void 0,r=new e(t.access_token,Math.floor(Date.now()/1e3)+Number(t.expires_in),t.id_token,t.refresh_token,t.scope,n,t.authorization_details);return r.tokenType=t.token_type,r.issuedTokenType=t.issued_token_type,r}},xo=(J=new WeakMap,Ha=new WeakMap,Ua=new WeakMap,class{constructor(e,t){E(this,J,new Map),E(this,Ha,void 0),E(this,Ua,void 0),D(Ua,this,Math.max(1,Math.floor(e))),D(Ha,this,Math.max(0,Math.floor(t)))}get(e){let t=T(J,this).get(e);if(t){if(!(Date.now()>=t.expiresAt))return T(J,this).delete(e),T(J,this).set(e,t),t.value;T(J,this).delete(e)}}set(e,t){for(T(J,this).has(e)&&T(J,this).delete(e),T(J,this).set(e,{value:t,expiresAt:Date.now()+T(Ha,this)});T(J,this).size>T(Ua,this);){let e=T(J,this).keys().next().value;if(e===void 0)break;T(J,this).delete(e)}}}),So=new Map;function Co(e){return{ttlMs:1e3*(typeof e?.ttl==`number`?e.ttl:600),maxEntries:typeof e?.maxEntries==`number`&&e.maxEntries>0?e.maxEntries:100}}var wo=class{static createDiscoveryCache(e){let t=(n=e.maxEntries,r=e.ttlMs,`${n}:${r}`);var n,r;let i=(a=t,So.get(a));var a;return i||(i=new xo(e.maxEntries,e.ttlMs),So.set(t,i)),i}static createJwksCache(){return{}}},To=`openid profile email offline_access`,Eo=Object.freeze(new Set([`grant_type`,`client_id`,`client_secret`,`client_assertion`,`client_assertion_type`,`subject_token`,`subject_token_type`,`requested_token_type`,`actor_token`,`actor_token_type`,`audience`,`aud`,`resource`,`resources`,`resource_indicator`,`scope`,`connection`,`login_hint`,`organization`,`assertion`]));function Do(e){if(e==null)throw new io(`subject_token is required`);if(typeof e!=`string`)throw new io(`subject_token must be a string`);if(e.trim().length===0)throw new io(`subject_token cannot be blank or whitespace`);if(e!==e.trim())throw new io(`subject_token must not include leading or trailing whitespace`);if(/^bearer\s+/i.test(e))throw new io(`subject_token must not include the 'Bearer ' prefix`)}function Oo(e,t){if(t){for(let[n,r]of Object.entries(t))if(!Eo.has(n))if(Array.isArray(r)){if(r.length>20)throw new io(`Parameter '${n}' exceeds maximum array size of 20`);r.forEach(t=>{e.append(n,t)})}else e.append(n,r)}}var ko=`urn:ietf:params:oauth:token-type:access_token`,Ao=(Y=new WeakMap,Wa=new WeakMap,Ga=new WeakMap,X=new WeakMap,Ka=new WeakMap,qa=new WeakMap,Ja=new WeakMap,Ya=new WeakMap,Xa=new WeakMap,Z=new WeakSet,class{constructor(e){var t;if(function(e,t){en(e,t),t.add(e)}(this,Z),E(this,Y,void 0),E(this,Wa,void 0),E(this,Ga,void 0),E(this,X,void 0),E(this,Ka,void 0),E(this,qa,void 0),E(this,Ja,void 0),E(this,Ya,void 0),E(this,Xa,void 0),O(this,`mfa`,void 0),D(X,this,e),e.useMtls&&!e.customFetch)throw new Za(`mtls_without_custom_fetch_not_supported`,`Using mTLS without a custom fetch implementation is not supported`);D(Ka,this,function(e,t){if(!1===t.enabled)return e;let n={name:t.name,version:t.version},r=btoa(JSON.stringify(n));return async(t,n)=>{let i=t instanceof Request?new Headers(t.headers):new Headers;return n!=null&&n.headers&&new Headers(n.headers).forEach((e,t)=>{i.set(t,e)}),i.set(`Auth0-Client`,r),e(t,k(k({},n),{},{headers:i}))}}(e.customFetch??function(){return fetch(...arguments)},!1===(t=e.telemetry)?.enabled?t:{enabled:!0,name:t?.name??`@auth0/auth0-auth-js`,version:t?.version??`1.6.0`}));let n=Co(e.discoveryCache);D(Ja,this,wo.createDiscoveryCache(n)),D(Ya,this,new Map),D(Xa,this,wo.createJwksCache()),this.mfa=new yo({domain:T(X,this).domain,clientId:T(X,this).clientId,customFetch:T(Ka,this)})}async getServerMetadata(){let{serverMetadata:e}=await w(Z,this,Q).call(this);return e}async buildAuthorizationUrl(e){let{serverMetadata:t}=await w(Z,this,Q).call(this);if(e!=null&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new Za(`par_not_supported_error`,`The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par`);try{return await w(Z,this,Io).call(this,e)}catch(e){throw new so(e)}}async buildLinkUserUrl(e){try{let t=await w(Z,this,Io).call(this,{authorizationParams:k(k({},e.authorizationParams),{},{requested_connection:e.connection,requested_connection_scope:e.connectionScope,scope:`openid link_account offline_access`,id_token_hint:e.idToken})});return{linkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new co(e)}}async buildUnlinkUserUrl(e){try{let t=await w(Z,this,Io).call(this,{authorizationParams:k(k({},e.authorizationParams),{},{requested_connection:e.connection,scope:`openid unlink_account`,id_token_hint:e.idToken})});return{unlinkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new lo(e)}}async backchannelAuthentication(e){let{configuration:t,serverMetadata:n}=await w(Z,this,Q).call(this),r=fo(k(k({},T(X,this).authorizationParams),e?.authorizationParams)),i=new URLSearchParams(k(k({scope:To},r),{},{client_id:T(X,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:`iss_sub`,iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&i.append(`requested_expiry`,e.requestedExpiry.toString()),e.authorizationDetails&&i.append(`authorization_details`,JSON.stringify(e.authorizationDetails));try{let e=await Xi(t,await Yi(t,i));return bo.fromTokenEndpointResponse(e)}catch(e){throw new oo(e)}}async initiateBackchannelAuthentication(e){let{configuration:t,serverMetadata:n}=await w(Z,this,Q).call(this),r=fo(k(k({},T(X,this).authorizationParams),e?.authorizationParams)),i=new URLSearchParams(k(k({scope:To},r),{},{client_id:T(X,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:`iss_sub`,iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&i.append(`requested_expiry`,e.requestedExpiry.toString()),e.authorizationDetails&&i.append(`authorization_details`,JSON.stringify(e.authorizationDetails));try{let e=await Yi(t,i);return{authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new oo(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e,{configuration:n}=await w(Z,this,Q).call(this),r=new URLSearchParams({auth_req_id:t});try{let e=await sa(n,`urn:openid:params:grant-type:ciba`,r);return bo.fromTokenEndpointResponse(e)}catch(e){throw new oo(e)}}async getTokenForConnection(e){if(e.refreshToken&&e.accessToken)throw new ro(`Either a refresh or access token should be specified, but not both.`);let t=e.accessToken??e.refreshToken;if(!t)throw new ro(`Either a refresh or access token must be specified.`);try{return await this.exchangeToken({connection:e.connection,subjectToken:t,subjectTokenType:e.accessToken?ko:`urn:ietf:params:oauth:token-type:refresh_token`,loginHint:e.loginHint})}catch(e){throw e instanceof io?new ro(e.message,e.cause):e}}async exchangeToken(e){return`connection`in e?w(Z,this,No).call(this,e):w(Z,this,Po).call(this,e)}async getTokenByCode(e,t){let{configuration:n}=await w(Z,this,Q).call(this);try{let r=await Qi(n,e,{pkceCodeVerifier:t.codeVerifier});return bo.fromTokenEndpointResponse(r)}catch(e){throw new $a(`There was an error while trying to request a token.`,e)}}async getTokenByRefreshToken(e){let{configuration:t}=await w(Z,this,Q).call(this),n=new URLSearchParams;e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope);try{let r=await $i(t,e.refreshToken,n);return bo.fromTokenEndpointResponse(r)}catch(e){throw new to(`The access token has expired and there was an error while trying to refresh it.`,e)}}async getTokenByPassword(e){let{configuration:t}=await w(Z,this,Q).call(this),n=new URLSearchParams({username:e.username,password:e.password});e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope),e.realm&&n.append(`realm`,e.realm);let r=t;if(e.auth0ForwardedFor){let n=await w(Z,this,Fo).call(this);r=new Gi(t.serverMetadata(),T(X,this).clientId,T(X,this).clientSecret,n),r[Ii]=(t,n)=>T(Ka,this).call(this,t,k(k({},n),{},{headers:k(k({},n.headers),{},{"auth0-forwarded-for":e.auth0ForwardedFor})}))}try{let e=await sa(r,`password`,n);return bo.fromTokenEndpointResponse(e)}catch(e){throw new no(`There was an error while trying to request a token.`,e)}}async getTokenByClientCredentials(e){let{configuration:t}=await w(Z,this,Q).call(this);try{let n=new URLSearchParams({audience:e.audience});e.organization&&n.append(`organization`,e.organization);let r=await ea(t,n);return bo.fromTokenEndpointResponse(r)}catch(e){throw new eo(`There was an error while trying to request a token.`,e)}}async buildLogoutUrl(e){let{configuration:t,serverMetadata:n}=await w(Z,this,Q).call(this);if(!n.end_session_endpoint){let t=new URL(`https://${T(X,this).domain}/v2/logout`);return t.searchParams.set(`returnTo`,e.returnTo),t.searchParams.set(`client_id`,T(X,this).clientId),t}return function(e,t){ra(e);let{as:n,c:r,tlsOnly:i}=G(e),a=zn(n,`end_session_endpoint`,!1,i);(t=new URLSearchParams(t)).has(`client_id`)||t.set(`client_id`,r.client_id);for(let[e,n]of t.entries())a.searchParams.append(e,n);return a}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){let{serverMetadata:t}=await w(Z,this,Q).call(this),n=Co(T(X,this).discoveryCache),r=t.jwks_uri;T(qa,this)||D(qa,this,function(e,t){let n=new Ia(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}(new URL(r),{cacheMaxAge:n.ttlMs,[wa]:T(Ka,this),[Ta]:T(Xa,this)}));let{payload:i}=await ma(e.logoutToken,T(qa,this),{issuer:t.issuer,audience:T(X,this).clientId,algorithms:[`RS256`],requiredClaims:[`iat`]});if(!(`sid`in i)&&!(`sub`in i))throw new ao(`either "sid" or "sub" (or both) claims must be present`);if(`sid`in i&&typeof i.sid!=`string`)throw new ao(`"sid" claim must be a string`);if(`sub`in i&&typeof i.sub!=`string`)throw new ao(`"sub" claim must be a string`);if(`nonce`in i)throw new ao(`"nonce" claim is prohibited`);if(!(`events`in i))throw new ao(`"events" claim is missing`);if(typeof i.events!=`object`||i.events===null)throw new ao(`"events" claim must be an object`);if(!(`http://schemas.openid.net/event/backchannel-logout`in i.events))throw new ao(`"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim`);if(typeof i.events[`http://schemas.openid.net/event/backchannel-logout`]!=`object`)throw new ao(`"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object`);return{sid:i.sid,sub:i.sub}}});function jo(){return`${T(X,this).domain.toLowerCase()}|mtls:${T(X,this).useMtls?`1`:`0`}`}async function Mo(e){let t=await w(Z,this,Fo).call(this),n=new Gi(e,T(X,this).clientId,T(X,this).clientSecret,t);return n[Ii]=T(Ka,this),n}async function Q(){if(T(Y,this)&&T(Wa,this))return{configuration:T(Y,this),serverMetadata:T(Wa,this)};let e=w(Z,this,jo).call(this),t=T(Ja,this).get(e);if(t)return D(Wa,this,t.serverMetadata),D(Y,this,await w(Z,this,Mo).call(this,t.serverMetadata)),{configuration:T(Y,this),serverMetadata:T(Wa,this)};let n=T(Ya,this).get(e);if(n){let e=await n;return D(Wa,this,e.serverMetadata),D(Y,this,await w(Z,this,Mo).call(this,e.serverMetadata)),{configuration:T(Y,this),serverMetadata:T(Wa,this)}}let r=(async()=>{let t=await w(Z,this,Fo).call(this),n=await Ui(new URL(`https://${T(X,this).domain}`),T(X,this).clientId,{use_mtls_endpoint_aliases:T(X,this).useMtls},t,{[Ii]:T(Ka,this)}),r=n.serverMetadata();return T(Ja,this).set(e,{serverMetadata:r}),{configuration:n,serverMetadata:r}})(),i=r.then(e=>{let{serverMetadata:t}=e;return{serverMetadata:t}});i.catch(()=>{}),T(Ya,this).set(e,i);try{let{configuration:e,serverMetadata:t}=await r;D(Y,this,e),D(Wa,this,t),T(Y,this)[Ii]=T(Ka,this)}finally{T(Ya,this).delete(e)}return{configuration:T(Y,this),serverMetadata:T(Wa,this)}}async function No(e){let{configuration:t}=await w(Z,this,Q).call(this);if(`audience`in e||`resource`in e)throw new io(`audience and resource parameters are not supported for Token Vault exchanges`);Do(e.subjectToken);let n=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType??ko,requested_token_type:e.requestedTokenType??`http://auth0.com/oauth/token-type/federated-connection-access-token`});e.loginHint&&n.append(`login_hint`,e.loginHint),e.scope&&n.append(`scope`,e.scope),Oo(n,e.extra);try{let e=await sa(t,`urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token`,n);return bo.fromTokenEndpointResponse(e)}catch(t){throw new io(`Failed to exchange token for connection '${e.connection}'.`,t)}}async function Po(e){let{configuration:t}=await w(Z,this,Q).call(this);Do(e.subjectToken);let n=new URLSearchParams({subject_token_type:e.subjectTokenType,subject_token:e.subjectToken});e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope),e.requestedTokenType&&n.append(`requested_token_type`,e.requestedTokenType),e.organization&&n.append(`organization`,e.organization),Oo(n,e.extra);try{let e=await sa(t,`urn:ietf:params:oauth:grant-type:token-exchange`,n);return bo.fromTokenEndpointResponse(e)}catch(t){throw new io(`Failed to exchange token of type '${e.subjectTokenType}'${e.audience?` for audience '${e.audience}'`:``}.`,t)}}async function Fo(){return T(Ga,this)||D(Ga,this,(async()=>{if(!T(X,this).clientSecret&&!T(X,this).clientAssertionSigningKey&&!T(X,this).useMtls)throw new uo;if(T(X,this).useMtls)return(e,t,n,r)=>{n.set(`client_id`,t.client_id)};let e=T(X,this).clientAssertionSigningKey;return!e||e instanceof CryptoKey||(e=await async function(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return Ti(e,t,n)}(e,T(X,this).clientAssertionSigningAlg||`RS256`)),e?function(e,t){return Fn(e,t)}(e):Fi(T(X,this).clientSecret)})().catch(e=>{throw D(Ga,this,void 0),e})),T(Ga,this)}async function Io(e){let{configuration:t}=await w(Z,this,Q).call(this),n=Vi(),r=await Bi(n),i=fo(k(k({},T(X,this).authorizationParams),e?.authorizationParams)),a=new URLSearchParams(k(k({scope:To},i),{},{client_id:T(X,this).clientId,code_challenge:r,code_challenge_method:`S256`}));return{authorizationUrl:e!=null&&e.pushedAuthorizationRequests?await na(t,a):await ta(t,a),codeVerifier:n}}var Lo=class e extends y{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}static fromPayload(t){let{error:n,error_description:r}=t;return new e(n,r)}},Ro=class e extends Lo{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},zo=class e extends Lo{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Bo=class e extends Lo{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Vo=class e extends Lo{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Ho=class e extends Lo{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Uo=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:6e5;this.contexts=new Map,this.ttlMs=e}set(e,t){this.cleanup(),this.contexts.set(e,Object.assign(Object.assign({},t),{createdAt:Date.now()}))}get(e){let t=this.contexts.get(e);if(t){if(!(Date.now()-t.createdAt>this.ttlMs))return t;this.contexts.delete(e)}}remove(e){this.contexts.delete(e)}cleanup(){let e=Date.now();for(let[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t)}get size(){return this.contexts.size}},Wo=class{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new Uo}setMFAAuthDetails(e,t,n,r){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:r})}async getAuthenticators(e){let t=this.contextManager.get(e);if(!t?.mfaRequirements?.challenge||t.mfaRequirements.challenge.length===0)throw new Ro(`invalid_request`,`challengeType is required and must contain at least one challenge type, please check mfa_required error payload`);let n=t.mfaRequirements.challenge.map(e=>e.type);try{return(await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter(e=>!!e.type&&n.includes(e.type))}catch(e){throw e instanceof mo?new Ro(e.cause?.error,e.message):e}}async enroll(e){let t=function(e){let t=Jt[e.factorType];return Object.assign(Object.assign(Object.assign({mfaToken:e.mfaToken,authenticatorTypes:t.authenticatorTypes},t.oobChannels&&{oobChannels:t.oobChannels}),`phoneNumber`in e&&{phoneNumber:e.phoneNumber}),`email`in e&&{email:e.email})}(e);try{return await this.authJsMfaClient.enrollAuthenticator(t)}catch(e){throw e instanceof ho?new zo(e.cause?.error,e.message):e}}async challenge(e){try{let t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){throw e instanceof _o?new Bo(e.cause?.error,e.message):e}}async getEnrollmentFactors(e){let t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new Ho(`mfa_context_not_found`,`MFA context not found for this MFA token. Please retry the original request to get a new MFA token.`);return t.mfaRequirements.enroll&&t.mfaRequirements.enroll.length!==0?t.mfaRequirements.enroll:[]}async verify(e){let t=this.contextManager.get(e.mfaToken);if(!t)throw new Vo(`mfa_context_not_found`,`MFA context not found for this MFA token. Please retry the original request to get a new MFA token.`);let n=function(e){return`otp`in e&&e.otp?Yt:`oobCode`in e&&e.oobCode?Xt:`recoveryCode`in e&&e.recoveryCode?Zt:void 0}(e);if(!n)throw new Vo(`invalid_request`,`Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.`);let r=t.scope,i=t.audience;try{let t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:r,audience:i,otp:e.otp,oob_code:e.oobCode,binding_code:e.bindingCode,recovery_code:e.recoveryCode});return this.contextManager.remove(e.mfaToken),t}catch(e){if(e instanceof ae)this.setMFAAuthDetails(e.mfa_token,r,i,e.mfa_requirements);else if(e instanceof Vo)throw new Vo(e.error,e.error_description);throw e}}},Go=class{constructor(e){let t,n;if(this.userCache=new lt().enclosedCache,this.defaultOptions={authorizationParams:{scope:`openid profile email`},useRefreshTokensFallback:!1,useFormData:!0},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),typeof window<`u`&&(()=>{if(!ue())throw Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(ue().subtle===void 0)throw Error(`
      auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.
    `)})(),this.lockManager=(Ne||=Me(),Ne),e.cache&&e.cacheLocation&&console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`."),e.cache)n=e.cache;else{if(t=e.cacheLocation||h,!Rt(t))throw Error(`Invalid cache location "${t}"`);n=Rt(t)()}var r;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:m,this.cookieStorage=!1===e.legacySameSiteCookie?Ct:Tt,this.orgHintCookieName=(r=this.options.clientId,`auth0.${r}.organization_hint`),this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;let i=e.useCookiesForTransactions?this.cookieStorage:Et;var a;this.scope=function(e,t){var n=[...arguments].slice(2);if(typeof e!=`object`)return{[v]:it(t,e,...n)};let r={[v]:it(t,...n)};return Object.keys(e).forEach(i=>{let a=e[i];r[i]=it(t,a,...n)}),r}(this.options.authorizationParams.scope,`openid`,this.options.useRefreshTokens?`offline_access`:``),this.transactionManager=new dt(i,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||_,this.cacheManager=new ut(n,n.allKeys?void 0:new Ft(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ut(this.options.clientId):void 0,this.domainUrl=(a=this.options.domain,/^https?:\/\//.test(a)?a:`https://${a}`),this.tokenIssuer=((e,t)=>e?e.startsWith(`https://`)?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl);let o=`${this.domainUrl}/me/`,s=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:`__auth0_my_account_api__`}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:`create:me:connected_accounts`,audience:o},detailedResponse:!0})}));this.myAccountApi=new Kt(s,o),this.authJsClient=new Ao({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new Wo(this.authJsClient.mfa,this),typeof window<`u`&&window.Worker&&this.options.useRefreshTokens&&t===h&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new Nt,this.worker.postMessage({type:`init`,allowedBaseUrl:this.domainUrl}))}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){let t=me(this.options.auth0Client||g,!0),n=encodeURIComponent(btoa(JSON.stringify(t)));return`${this.domainUrl}${e}&auth0Client=${n}`}_authorizeUrl(e){return this._url(`/authorize?${he(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return mt({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(i=this.options.authorizationParams.max_age,typeof i==`string`?parseInt(i,10)||void 0:i),now:r});var i}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain})}_extractSessionTransferToken(e){return new URLSearchParams(window.location.search).get(e)||void 0}_clearSessionTransferTokenFromUrl(e){try{let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState({},``,t.toString()))}catch{}}_applySessionTransferToken(e){let t=this.options.sessionTransferTokenQueryParamName;if(!t||e.session_transfer_token)return e;let n=this._extractSessionTransferToken(t);return n?(this._clearSessionTransferTokenFromUrl(t),Object.assign(Object.assign({},e),{session_transfer_token:n})):e}async _prepareAuthorizeUrl(e,t,n){let r=fe(de()),i=fe(de()),a=de(),o=ve(await ge(a)),s=await this.dpop?.calculateThumbprint(),c=((e,t,n,r,i,a,o,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:at(t,n.scope,n.audience),response_type:`code`,response_mode:s||`query`,state:r,nonce:i,redirect_uri:o||e.authorizationParams.redirect_uri,code_challenge:a,code_challenge_method:`S256`,dpop_jkt:c}))(this.options,this.scope,e,r,i,o,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,t?.response_mode,s),l=this._authorizeUrl(c);return{nonce:i,code_verifier:a,scope:c.scope,audience:c.audience||v,redirect_uri:c.redirect_uri,state:r,url:l}}async loginWithPopup(e,t){if(e||={},!(t||={}).popup&&(t.popup=(e=>{let t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,`auth0:authorize:popup`,`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(``),!t.popup))throw new ie;let n=this._applySessionTransferToken(e.authorizationParams||{}),r=await this._prepareAuthorizeUrl(n,{response_mode:`web_message`},window.location.origin);t.popup.location.href=r.url;let i=await((e,t)=>new Promise((n,r)=>{let i,a=setInterval(()=>{e.popup&&e.popup.closed&&(clearInterval(a),clearTimeout(o),window.removeEventListener(`message`,i,!1),r(new re(e.popup)))},1e3),o=setTimeout(()=>{clearInterval(a),r(new ne(e.popup)),window.removeEventListener(`message`,i,!1)},1e3*(e.timeoutInSeconds||60));i=function(s){if(s.origin===t&&s.data&&s.data.type===`authorization_response`){if(clearTimeout(o),clearInterval(a),window.removeEventListener(`message`,i,!1),!1!==e.closePopup&&e.popup.close(),s.data.response.error)return r(y.fromPayload(s.data.response));n(s.data.response)}},window.addEventListener(`message`,i)}))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}),new URL(r.url).origin);if(r.state!==i.state)throw new y(`state_mismatch`,`Invalid state`);let a=e.authorizationParams?.organization||this.options.authorizationParams.organization;await this._requestToken({audience:r.audience,scope:r.scope,code_verifier:r.code_verifier,grant_type:`authorization_code`,code:i.code,redirect_uri:r.redirect_uri},{nonceIn:r.nonce,organization:a})}async getUser(){return(await this._getIdTokenFromCache())?.decodedToken?.user}async getIdTokenClaims(){return(await this._getIdTokenFromCache())?.decodedToken?.claims}async loginWithRedirect(){let e=zt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),{openUrl:t,fragment:n,appState:r}=e,i=f(e,[`openUrl`,`fragment`,`appState`]),a=i.authorizationParams?.organization||this.options.authorizationParams.organization,o=this._applySessionTransferToken(i.authorizationParams||{}),s=await this._prepareAuthorizeUrl(o),{url:c}=s,l=f(s,[`url`]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:r,response_type:Dt.Code}),a&&{organization:a}));let u=n?`${c}#${n}`:c;t?await t(u):window.location.assign(u)}async handleRedirectCallback(){let e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.location.href).split(`?`).slice(1);if(e.length===0)throw Error(`There are no query params available for parsing.`);let t=this.transactionManager.get();if(!t)throw new y(`missing_transaction`,`Invalid state`);this.transactionManager.remove();let n=(e=>{e.indexOf(`#`)>-1&&(e=e.substring(0,e.indexOf(`#`)));let t=new URLSearchParams(e);return{state:t.get(`state`),code:t.get(`code`)||void 0,connect_code:t.get(`connect_code`)||void 0,error:t.get(`error`)||void 0,error_description:t.get(`error_description`)||void 0}})(e.join(``));return t.response_type===Dt.ConnectCode?this._handleConnectAccountRedirectCallback(n,t):this._handleLoginRedirectCallback(n,t)}async _handleLoginRedirectCallback(e,t){let{code:n,state:r,error:i,error_description:a}=e;if(i)throw new b(i,a||i,r,t.appState);if(!t.code_verifier||t.state&&t.state!==r)throw new y(`state_mismatch`,`Invalid state`);let o=t.organization,s=t.nonce,c=t.redirect_uri;return await this._requestToken(Object.assign({audience:t.audience,scope:t.scope,code_verifier:t.code_verifier,grant_type:`authorization_code`,code:n},c?{redirect_uri:c}:{}),{nonceIn:s,organization:o}),{appState:t.appState,response_type:Dt.Code}}async _handleConnectAccountRedirectCallback(e,t){let{connect_code:n,state:r,error:i,error_description:a}=e;if(i)throw new ee(i,a||i,t.connection,r,t.appState);if(!n)throw new y(`missing_connect_code`,`Missing connect code`);if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===r))throw new y(`state_mismatch`,`Invalid state`);let o=await this.myAccountApi.completeAccount({auth_session:t.auth_session,connect_code:n,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},o),{appState:t.appState,response_type:Dt.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get(It))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(It)}try{await this.getTokenSilently(e)}catch{}}async getTokenSilently(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Object.assign(Object.assign({cacheMode:`on`},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:at(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=Pt[t];return n||(n=e().finally(()=>{delete Pt[t],n=null}),Pt[t]=n),n})(()=>this._getTokenSilently(t),`${this.options.clientId}::${t.authorizationParams.audience}::${t.authorizationParams.scope}`);return e.detailedResponse?n:n?.access_token}async _getTokenSilently(e){let{cacheMode:t}=e,n=f(e,[`cacheMode`]);if(t!==`off`){let e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||v,clientId:this.options.clientId,cacheMode:t});if(e)return e}if(t===`cache-only`)return;let r=(i=this.options.clientId,a=n.authorizationParams.audience||`default`,`auth0.lock.getTokenSilently.${i}.${a}`);var i,a;try{return await this.lockManager.runWithLock(r,5e3,async()=>{if(t!==`off`){let e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||v,clientId:this.options.clientId});if(e)return e}let{id_token:e,token_type:r,access_token:i,oauthTokenScope:a,expires_in:o}=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(n):await this._getTokenFromIFrame(n);return Object.assign(Object.assign({id_token:e,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:o})})}catch(e){if(this._isInteractiveError(e)&&this.options.interactiveErrorHandler===`popup`)return await this._handleInteractiveErrorWithPopup(n);throw e}}_isInteractiveError(e){return e instanceof ae||e instanceof y&&this._isIframeMfaError(e)}_isIframeMfaError(e){return e.error===`login_required`&&e.error_description===`Multifactor authentication required`}async _handleInteractiveErrorWithPopup(e){try{await this.loginWithPopup({authorizationParams:e.authorizationParams});let t=await this._getEntryFromCache({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||v,clientId:this.options.clientId});if(!t)throw new y(`interactive_handler_cache_miss`,`Token not found in cache after interactive authentication`);return t}catch(e){throw e}}async getTokenWithPopup(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:at(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},p),t),await this.loginWithPopup(n,t),(await this.cacheManager.get(new C({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||v,clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){e.clientId===null?delete e.clientId:e.clientId=e.clientId||this.options.clientId;let t=e.logoutParams||{},{federated:n}=t,r=f(t,[`federated`]),i=n?`&federated`:``;return this._url(`/v2/logout?${he(Object.assign({clientId:e.clientId},r))}`)+i}async revokeRefreshToken(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this.options.useRefreshTokens)return;let t=e.audience||this.options.authorizationParams.audience||v,n=await this.cacheManager.getRefreshTokensByAudience(t,this.options.clientId);await async function(e,t){let{baseUrl:n,timeout:r,auth0Client:i,useFormData:a,refreshTokens:o,audience:s,client_id:c,onRefreshTokenRevoked:l}=e,u=r||m,d=`refresh_token`,f=`${n}/oauth/revoke`,p={"Content-Type":a?`application/x-www-form-urlencoded`:`application/json`,"Auth0-Client":btoa(JSON.stringify(me(i||g)))};if(t){let e={client_id:c,token_type_hint:d},n=a?he(e):JSON.stringify(e);try{return await $e({type:`revoke`,timeout:u,fetchUrl:f,fetchOptions:{method:`POST`,body:n,headers:p},useFormData:a,auth:{audience:s??v}},t)}catch(e){throw new y(`revoke_error`,e.message)}}for(let e of o){let t={client_id:c,token_type_hint:d,token:e},n=await et(f,{method:`POST`,body:a?he(t):JSON.stringify(t),headers:p},u);if(!n.ok){let e,t;try{({error:e,error_description:t}=JSON.parse(await n.text()))}catch{}throw new y(e||`revoke_error`,t||`HTTP error ${n.status}`)}await l?.(e)}}({baseUrl:this.domainUrl,timeout:this.httpTimeoutMs,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,client_id:this.options.clientId,refreshTokens:n,audience:t,onRefreshTokenRevoked:e=>this.cacheManager.stripRefreshToken(e)},this.worker)}async logout(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=zt(e),{openUrl:n}=t,r=f(t,[`openUrl`]);if(e.clientId===null?await this.cacheManager.clear():await this.cacheManager.clear(e.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove(st),await this.dpop?.clear(),this.worker)try{await $e({type:`clear`},this.worker)}catch{}let i=this._buildLogoutUrl(r);n?await n(i):!1!==n&&window.location.assign(i)}async _getTokenFromIFrame(e){let t=(n=this.options.clientId,`auth0.lock.getTokenFromIFrame.${n}`);var n;try{return await this.lockManager.runWithLock(t,5e3,async()=>{let t=Object.assign(Object.assign({},e.authorizationParams),{prompt:`none`}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);let{url:r,state:i,nonce:a,code_verifier:o,redirect_uri:s,scope:c,audience:l}=await this._prepareAuthorizeUrl(t,{response_mode:`web_message`},window.location.origin);if(window.crossOriginIsolated)throw new y(`login_required`,`The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.`);let u=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds,d;try{d=new URL(this.domainUrl).origin}catch{d=this.domainUrl}let f=await function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:60;return new Promise((r,i)=>{let a=window.document.createElement(`iframe`);a.setAttribute(`width`,`0`),a.setAttribute(`height`,`0`),a.style.display=`none`;let o=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener(`message`,s,!1))},s,c=setTimeout(()=>{i(new te),o()},1e3*n);s=function(e){if(e.origin!=t||!e.data||e.data.type!==`authorization_response`)return;let n=e.source;n&&n.close(),e.data.response.error?i(y.fromPayload(e.data.response)):r(e.data.response),clearTimeout(c),window.removeEventListener(`message`,s,!1),setTimeout(o,2e3)},window.addEventListener(`message`,s,!1),window.document.body.appendChild(a),a.setAttribute(`src`,e)})}(r,d,u);if(i!==f.state)throw new y(`state_mismatch`,`Invalid state`);let p=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:o,code:f.code,grant_type:`authorization_code`,redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},p),{scope:c,oauthTokenScope:p.scope,audience:l})})}catch(e){throw e.error===`login_required`&&(e instanceof y&&this._isIframeMfaError(e)&&this.options.interactiveErrorHandler===`popup`||this.logout({openUrl:!1})),e}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new C({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||v,clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(t&&t.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new oe(e.authorizationParams.audience||v,e.authorizationParams.scope)}let n=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,r=typeof e.timeoutInSeconds==`number`?1e3*e.timeoutInSeconds:null,i=((e,t,n,r)=>{if(e&&n&&r){if(t.audience!==n)return t.scope;let e=r.split(` `),i=t.scope?.split(` `)||[],a=i.every(t=>e.includes(t));return e.length>=i.length&&a?r:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,t?.audience,t?.scope);try{let l=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:`refresh_token`,refresh_token:t&&t.refresh_token,redirect_uri:n}),r&&{timeout:r}),{scopesToRequest:i});if(l.refresh_token&&t!=null&&t.refresh_token&&await this.cacheManager.updateEntry(t.refresh_token,l.refresh_token),this.options.useMrrt&&(a=t?.audience,o=t?.scope,s=e.authorizationParams.audience,c=e.authorizationParams.scope,(a!==s||!Bt(c,o))&&!Bt(i,l.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);let t=((e,t)=>{let n=e?.split(` `)||[],r=t?.split(` `)||[];return n.filter(e=>r.indexOf(e)==-1).join(`,`)})(i,l.scope);throw new se(e.authorizationParams.audience||`default`,t)}return Object.assign(Object.assign({},l),{scope:e.authorizationParams.scope,oauthTokenScope:l.scope,audience:e.authorizationParams.audience||v})}catch(t){if(t.message){if(t.message.includes(`user is blocked`))throw await this.logout({openUrl:!1}),t;if((t.message.includes(`Missing Refresh Token`)||t.message.includes(`invalid refresh token`))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw t instanceof ae&&this.mfa.setMFAAuthDetails(t.mfa_token,e.authorizationParams?.scope,e.authorizationParams?.audience,t.mfa_requirements),t}var a,o,s,c}async _saveEntryInCache(e){let{id_token:t,decodedToken:n}=e,r=f(e,[`id_token`,`decodedToken`]);this.userCache.set(st,{id_token:t,decodedToken:n}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(r)}async _getIdTokenFromCache(){let e=this.options.authorizationParams.audience||v,t=this.scope[e],n=await this.cacheManager.getIdToken(new C({clientId:this.options.clientId,audience:e,scope:t})),r=this.userCache.get(st);return n&&n.id_token===r?.id_token?r:(this.userCache.set(st,n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:r,cacheMode:i}=e,a=await this.cacheManager.get(new C({scope:t,audience:n,clientId:r}),60,this.options.useMrrt,i);if(a&&a.access_token){let{token_type:e,access_token:t,oauthTokenScope:n,expires_in:r}=a,i=await this._getIdTokenFromCache();return i&&Object.assign(Object.assign({id_token:i.id_token,token_type:e||`Bearer`,access_token:t},n?{scope:n}:null),{expires_in:r})}}async _requestToken(e,t){var n;let{nonceIn:r,organization:i,scopesToRequest:a}=t||{},o=await rt(Object.assign(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,useMrrt:this.options.useMrrt,dpop:this.dpop},e),{scope:a||e.scope}),this.worker),s=await this._verifyIdToken(o.id_token,r,i);if(e.grant_type===`authorization_code`){let e=await this._getIdTokenFromCache();(n=e?.decodedToken?.claims)!=null&&n.sub&&e.decodedToken.claims.sub!==s.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove(st))}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},o),{decodedToken:s,scope:e.scope,audience:e.audience||v}),o.scope?{oauthTokenScope:o.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||s.claims.org_id),Object.assign(Object.assign({},o),{decodedToken:s})}async loginWithCustomTokenExchange(e){return this._requestToken(Object.assign(Object.assign({},e),{grant_type:`urn:ietf:params:oauth:grant-type:token-exchange`,subject_token:e.subject_token,subject_token_type:e.subject_token_type,scope:at(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization}))}async exchangeToken(e){return this.loginWithCustomTokenExchange(e)}_assertDpop(e){if(!e)throw Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return new Gt(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>this.getTokenSilently({authorizationParams:{scope:(e?.scope)?.join(` `),audience:e?.audience},detailedResponse:!0}),getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){let{openUrl:t,appState:n,connection:r,scopes:i,authorization_params:a,redirectUri:o=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!r)throw Error(`connection is required`);let s=fe(de()),c=de(),l=ve(await ge(c)),{connect_uri:u,connect_params:d,auth_session:f}=await this.myAccountApi.connectAccount({connection:r,scopes:i,redirect_uri:o,state:s,code_challenge:l,code_challenge_method:`S256`,authorization_params:a});this.transactionManager.create({state:s,code_verifier:c,auth_session:f,redirect_uri:o,appState:n,connection:r,response_type:Dt.ConnectCode});let p=new URL(u);p.searchParams.set(`ticket`,d.ticket),t?await t(p.toString()):window.location.assign(p)}async _requestTokenForMfa(e,t){let{mfaToken:n}=e,r=f(e,[`mfaToken`]);return this._requestToken(Object.assign(Object.assign({},r),{mfa_token:n}),t)}},Ko={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},$=function(){throw Error(`You forgot to wrap your component in <Auth0Provider>.`)},qo=s(s({},Ko),{buildAuthorizeUrl:$,buildLogoutUrl:$,getAccessTokenSilently:$,getAccessTokenWithPopup:$,getIdTokenClaims:$,loginWithCustomTokenExchange:$,exchangeToken:$,loginWithRedirect:$,loginWithPopup:$,connectAccountWithRedirect:$,logout:$,handleRedirectCallback:$,getDpopNonce:$,setDpopNonce:$,generateDpopProof:$,createFetcher:$,getConfiguration:$,mfa:{getAuthenticators:$,enroll:$,challenge:$,verify:$,getEnrollmentFactors:$}}),Jo=(0,i.createContext)(qo),Yo=function(e){o(t,e);function t(n,r){var i=e.call(this,r??n)||this;return i.error=n,i.error_description=r,Object.setPrototypeOf(i,t.prototype),i}return t}(Error),Xo=/[?&](?:connect_)?code=[^&]+/,Zo=/[?&]state=[^&]+/,Qo=/[?&]error=[^&]+/,$o=function(e){return e===void 0&&(e=window.location.search),(Xo.test(e)||Qo.test(e))&&Zo.test(e)},es=function(e){return function(t){if(t instanceof Error)return t;if(typeof t==`object`&&t&&`error`in t&&typeof t.error==`string`){if(`error_description`in t&&typeof t.error_description==`string`){var n=t;return new Yo(n.error,n.error_description)}return new Yo(t.error)}return Error(e)}},ts=es(`Login failed`),ns=es(`Get access token failed`),rs=function(e){e?.redirectUri&&(console.warn("Using `redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `redirectUri` will be no longer supported in a future version"),e.authorizationParams=e.authorizationParams??{},e.authorizationParams.redirect_uri=e.redirectUri,delete e.redirectUri),e?.authorizationParams?.redirectUri&&(console.warn("Using `authorizationParams.redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `authorizationParams.redirectUri` will be removed in a future version"),e.authorizationParams.redirect_uri=e.authorizationParams.redirectUri,delete e.authorizationParams.redirectUri)},is=function(e,t){switch(t.type){case`LOGIN_POPUP_STARTED`:return s(s({},e),{isLoading:!0});case`LOGIN_POPUP_COMPLETE`:case`INITIALISED`:return s(s({},e),{isAuthenticated:!!t.user,user:t.user,isLoading:!1,error:void 0});case`HANDLE_REDIRECT_COMPLETE`:case`GET_ACCESS_TOKEN_COMPLETE`:return e.user===t.user?e:s(s({},e),{isAuthenticated:!!t.user,user:t.user});case`LOGOUT`:return s(s({},e),{isAuthenticated:!1,user:void 0});case`ERROR`:return s(s({},e),{isLoading:!1,error:t.error})}},as=function(e){return rs(e),s(s({},e),{auth0Client:{name:`auth0-react`,version:`2.16.2`}})},os=function(e){window.history.replaceState({},document.title,e.returnTo??window.location.pathname)},ss=function(e){var t=e,n=t.children,r=t.skipRedirectCallback,a=t.onRedirectCallback,o=a===void 0?os:a,f=t.context,p=f===void 0?Jo:f,m=t.client,h=c(t,[`children`,`skipRedirectCallback`,`onRedirectCallback`,`context`,`client`]);m&&(h.domain||h.clientId)&&console.warn("Auth0Provider: the `client` prop takes precedence over `domain`/`clientId` and other configuration options. Remove `domain`, `clientId`, and any other Auth0Client configuration props when using the `client` prop.");var g=(0,i.useState)(function(){return m??new Go(as(h))})[0],_=(0,i.useReducer)(is,Ko),v=_[0],y=_[1],b=(0,i.useRef)(!1),ee=(0,i.useCallback)(function(e){return y({type:`ERROR`,error:e}),e},[]);(0,i.useEffect)(function(){b.current||(b.current=!0,(function(){return l(void 0,void 0,void 0,function(){var e,t,n,i,a,s,l;return u(this,function(u){switch(u.label){case 0:return u.trys.push([0,7,,8]),e=void 0,$o()&&!r?[4,g.handleRedirectCallback()]:[3,3];case 1:return t=u.sent(),n=t.appState,i=n===void 0?{}:n,a=t.response_type,s=c(t,[`appState`,`response_type`]),[4,g.getUser()];case 2:return e=u.sent(),i.response_type=a,a===Dt.ConnectCode&&(i.connectedAccount=s),o(i,e),[3,6];case 3:return[4,g.checkSession()];case 4:return u.sent(),[4,g.getUser()];case 5:e=u.sent(),u.label=6;case 6:return y({type:`INITIALISED`,user:e}),[3,8];case 7:return l=u.sent(),ee(ts(l)),[3,8];case 8:return[2]}})})})())},[g,o,r,ee]);var te=(0,i.useCallback)(function(e){return rs(e),g.loginWithRedirect(e)},[g]),ne=(0,i.useCallback)(function(e,t){return l(void 0,void 0,void 0,function(){var n,r;return u(this,function(i){switch(i.label){case 0:y({type:`LOGIN_POPUP_STARTED`}),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,g.loginWithPopup(e,t)];case 2:return i.sent(),[3,4];case 3:return n=i.sent(),ee(ts(n)),[2];case 4:return[4,g.getUser()];case 5:return r=i.sent(),y({type:`LOGIN_POPUP_COMPLETE`,user:r}),[2]}})})},[g,ee]),re=(0,i.useCallback)(function(){return l(void 0,d([],[...arguments],!0),void 0,function(e){return e===void 0&&(e={}),u(this,function(t){switch(t.label){case 0:return[4,g.logout(e)];case 1:return t.sent(),(e.openUrl||e.openUrl===!1)&&y({type:`LOGOUT`}),[2]}})})},[g]),ie=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.getTokenSilently(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),ns(n);case 3:return r=y,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),ae=(0,i.useCallback)(function(e,t){return l(void 0,void 0,void 0,function(){var n,r,i,a;return u(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,3,5]),[4,g.getTokenWithPopup(e,t)];case 1:return n=o.sent(),[3,5];case 2:throw r=o.sent(),ns(r);case 3:return i=y,a={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return i.apply(void 0,[(a.user=o.sent(),a)]),[7];case 5:return[2,n]}})})},[g]),oe=(0,i.useCallback)(function(e){return g.connectAccountWithRedirect(e)},[g]),se=(0,i.useCallback)(function(){return g.getIdTokenClaims()},[g]),ce=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.loginWithCustomTokenExchange(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),ns(n);case 3:return r=y,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),le=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){return u(this,function(t){return[2,ce(e)]})})},[ce]),ue=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r;return u(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,g.handleRedirectCallback(e)];case 1:return[2,i.sent()];case 2:throw t=i.sent(),ns(t);case 3:return n=y,r={type:`HANDLE_REDIRECT_COMPLETE`},[4,g.getUser()];case 4:return n.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2]}})})},[g]),de=(0,i.useCallback)(function(e){return g.getDpopNonce(e)},[g]),fe=(0,i.useCallback)(function(e,t){return g.setDpopNonce(e,t)},[g]),pe=(0,i.useCallback)(function(e){return g.generateDpopProof(e)},[g]),me=(0,i.useCallback)(function(e){return g.createFetcher(e)},[g]),he=(0,i.useCallback)(function(){return g.getConfiguration()},[g]),ge=(0,i.useMemo)(function(){return g.mfa},[g]),_e=(0,i.useMemo)(function(){return s(s({},v),{getAccessTokenSilently:ie,getAccessTokenWithPopup:ae,getIdTokenClaims:se,loginWithCustomTokenExchange:ce,exchangeToken:le,loginWithRedirect:te,loginWithPopup:ne,connectAccountWithRedirect:oe,logout:re,handleRedirectCallback:ue,getDpopNonce:de,setDpopNonce:fe,generateDpopProof:pe,createFetcher:me,getConfiguration:he,mfa:ge})},[v,ie,ae,se,ce,le,te,ne,oe,re,ue,de,fe,pe,me,he,ge]);return i.createElement(p.Provider,{value:_e},n)},cs=function(e){return e===void 0&&(e=Jo),(0,i.useContext)(e)};export{cs as n,ss as t};