@auth0/auth0-react 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).reactAuth0={},e.React)}(this,(function(e,t){"use strict";var n=function(e,t){return n=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])},n(e,t)};var o=function(){return o=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)};function r(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function i(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((o=o.apply(e,t||[])).next())}))}function a(e,t){var n,o,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){i.label=s[1];break}if(6===s[0]&&i.label<r[1]){i.label=r[1],r=s;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(s);break}r[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],o=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function s(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}"function"==typeof SuppressedError&&SuppressedError,"function"==typeof SuppressedError&&SuppressedError;const c={timeoutInSeconds:60},u={name:"auth0-spa-js",version:"2.16.0"},l=()=>Date.now();class d extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,d.prototype)}static fromPayload(e){let{error:t,error_description:n}=e;return new d(t,n)}}class h extends d{constructor(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,h.prototype)}}class p extends d{constructor(e,t,n,o){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;super(e,t),this.connection=n,this.state=o,this.appState=r,Object.setPrototypeOf(this,p.prototype)}}class f extends d{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,f.prototype)}}class m extends f{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,m.prototype)}}class y extends d{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,y.prototype)}}class w extends d{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,w.prototype)}}class g extends d{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,g.prototype)}}class v extends d{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(k(e,["default"]),"', scope: '").concat(k(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,v.prototype)}}class b extends d{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(k(e,["default"]),"', missing scope: '").concat(k(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,b.prototype)}}class _ extends d{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,_.prototype)}}function k(e){return e&&!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).includes(e)?e:""}const S=()=>window.crypto,E=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(S().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%66])),t},T=e=>btoa(e),A=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],P=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object.keys(e).reduce(((n,o)=>{if(t&&"env"===o)return n;const r=A.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},R=e=>{var{clientId:t}=e,n=s(e,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:t},n))).toString()},I=async e=>{const t=S().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},O=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),C=e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))};var x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},j={},D={};Object.defineProperty(D,"__esModule",{value:!0});var L=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();D.default=function(){return L.getInstance()};var U=x&&x.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){e.done?r(e.value):new n((function(t){t(e.value)})).then(a,s)}c((o=o.apply(e,t||[])).next())}))},K=x&&x.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},N=x;Object.defineProperty(j,"__esModule",{value:!0});var W=D,z={key:function(e){return U(N,void 0,void 0,(function(){return K(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return U(N,void 0,void 0,(function(){return K(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return U(N,void 0,void 0,(function(){return K(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return U(N,void 0,void 0,(function(){return K(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return U(N,void 0,void 0,(function(){return K(this,(function(e){throw new 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 H(e){return new Promise((function(t){return setTimeout(t,e)}))}function M(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++)n+=t[Math.floor(61*Math.random())];return n}var J=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+M(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),U(this,void 0,void 0,(function(){var o,r,i,a,s,c,u;return K(this,(function(l){switch(l.label){case 0:o=Date.now()+M(4),r=Date.now()+n,i="browser-tabs-lock-key-"+t,a=void 0===this.storageHandler?z:this.storageHandler,l.label=1;case 1:return Date.now()<r?[4,H(30)]:[3,8];case 2:return l.sent(),null!==a.getItemSync(i)?[3,5]:(s=this.id+"-"+t+"-"+o,[4,H(Math.floor(25*Math.random()))]);case 3:return l.sent(),a.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,H(30)];case 4:return l.sent(),null!==(c=a.getItemSync(i))&&(u=JSON.parse(c)).id===this.id&&u.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?z:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:l.sent(),l.label=7;case 7:return o=Date.now()+M(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return U(this,void 0,void 0,(function(){var n=this;return K(this,(function(o){return setTimeout((function(){return U(n,void 0,void 0,(function(){var n,o,r;return K(this,(function(i){switch(i.label){case 0:return[4,W.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?z:this.storageHandler,null===(o=n.getItemSync(e))?(W.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),W.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(W.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return U(this,void 0,void 0,(function(){return K(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){var o=!1,r=Date.now(),i=!1;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=!0),!o){o=!0;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return U(this,void 0,void 0,(function(){return K(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 U(this,void 0,void 0,(function(){var n,o,r,i;return K(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?z:this.storageHandler,o="browser-tabs-lock-key-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,W.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),W.default().unlock(i.iat),e.notifyWaiters(),a.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],i=0;;){var a=o.keySync(i);if(null===a)break;r.push(a),i++}for(var s=!1,c=0;c<r.length;c++){var u=r[c];if(u.includes("browser-tabs-lock-key")){var l=o.getItemSync(u);if(null!==l){var d=JSON.parse(l);(void 0===d.timeRefreshed&&d.timeAcquired<n||void 0!==d.timeRefreshed&&d.timeRefreshed<n)&&(o.removeItemSync(u),s=!0)}}}s&&e.notifyWaiters()},e.waiters=void 0,e}(),V=j.default=J;class F{async runWithLock(e,t,n){const o=new AbortController,r=setTimeout((()=>o.abort()),t);try{return await navigator.locks.request(e,{mode:"exclusive",signal:o.signal},(async e=>{if(clearTimeout(r),!e)throw new Error("Lock not available");return await n()}))}catch(e){if(clearTimeout(r),"AbortError"===(null==e?void 0:e.name))throw new f;throw e}}}class G{constructor(){this.activeLocks=new Set,this.lock=new V,this.pagehideHandler=()=>{this.activeLocks.forEach((e=>this.lock.releaseLock(e))),this.activeLocks.clear()}}async runWithLock(e,t,n){let o=!1;for(let n=0;n<10&&!o;n++)o=await this.lock.acquireLock(e,t);if(!o)throw new f;this.activeLocks.add(e),1===this.activeLocks.size&&"undefined"!=typeof window&&window.addEventListener("pagehide",this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),0===this.activeLocks.size&&"undefined"!=typeof window&&window.removeEventListener("pagehide",this.pagehideHandler)}}}let Z=null;const q=new TextEncoder,B=new TextDecoder;function X(e){return"string"==typeof e?q.encode(e):B.decode(e)}function Y(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new te(`${e.name} modulusLength must be at least 2048 bits`)}let Q;if(Uint8Array.prototype.toBase64)Q=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;Q=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}function $(e){return Q(e)}class ee extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class te extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}function ne(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return"PS256";throw new ee("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return"RS256";throw new ee("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return"ES256";throw new ee("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return"Ed25519";default:throw new ee("unsupported CryptoKey algorithm name")}}function oe(e){return e instanceof CryptoKey}function re(e){return oe(e)&&"public"===e.type}async function ie(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!oe(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!re(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(!0!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw new TypeError('"additional" must be an object');return async function(e,t,n){if(!1===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${$(X(JSON.stringify(e)))}.${$(X(JSON.stringify(t)))}`;return`${o}.${$(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Y(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Y(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new ee}(n),n,X(o)))}`}({alg:ne(a),typ:"dpop+jwt",jwk:await ae(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?$(await crypto.subtle.digest("SHA-256",X(r))):void 0}),a)}async function ae(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:a,e:n,n:o,x:r,y:i}}const se=["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"];const ce=async(e,t)=>{const n=await fetch(e,t);return{ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,t)=>{let[n,o]=t;return e[n]=o,e}),{}))};var o},ue=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4;return r?(async(e,t,n,o,r,i,a,s)=>((e,t)=>new Promise((function(n,o){const r=new MessageChannel;r.port1.onmessage=function(e){e.data.error?o(new Error(e.data.error)):n(e.data),r.port1.close()},t.postMessage(e,[r.port2])})))({auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a,useMrrt:s},i))(e,t,n,o,a,r,i,arguments.length>7?arguments[7]:void 0):(async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([ce(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"))}),n)}))]).finally((()=>{clearTimeout(r)}))})(e,o,a)};async function le(e,t,n,o,r,i,a,c,u,l){if(u){const t=await u.generateProof({url:e,method:r.method||"GET",nonce:await u.getNonce()});r.headers=Object.assign(Object.assign({},r.headers),{dpop:t})}let h,p=null;for(let s=0;s<3;s++)try{h=await ue(e,n,o,r,i,a,t,c),p=null;break}catch(e){p=e}if(p)throw p;const f=h.json,{error:m,error_description:y}=f,w=s(f,["error","error_description"]),{headers:b,ok:k}=h;let S;if(u&&(S=b["dpop-nonce"],S&&await u.setNonce(S)),!k){const s=y||"HTTP error. Unable to fetch ".concat(e);if("mfa_required"===m)throw new g(m,s,w.mfa_token,w.mfa_requirements);if("missing_refresh_token"===m)throw new v(n,o);if("use_dpop_nonce"===m){if(!u||!S||l)throw new _(S);return le(e,t,n,o,r,i,a,c,u,!0)}throw new d(m||"request_error",s)}return w}async function de(e,t){var{baseUrl:n,timeout:o,audience:r,scope:i,auth0Client:a,useFormData:c,useMrrt:l,dpop:d}=e,h=s(e,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const p="urn:ietf:params:oauth:grant-type:token-exchange"===h.grant_type,f="refresh_token"===h.grant_type&&l,m=Object.assign(Object.assign(Object.assign(Object.assign({},h),p&&r&&{audience:r}),p&&i&&{scope:i}),f&&{audience:r,scope:i}),y=c?R(m):JSON.stringify(m),w=(g=h.grant_type,se.includes(g));var g;return await le("".concat(n,"/oauth/token"),o,r||"default",i,{method:"POST",body:y,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(P(a||u)))}},t,c,l,w?d:void 0)}const he=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(e=>Array.from(new Set(e)))(t.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ")},pe=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),he(o,t)};class fe{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"@@auth0spajs@@",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(e){const[t,n,o,r]=e.split("::");return new fe({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new fe({scope:t,audience:n,clientId:o})}}class me{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class ye{constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){const n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}}class we{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||l}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r))}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return{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&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3?arguments[3]:void 0;var r;let i=await this.cache.get(e.toKey());if(!i){const t=await this.getCacheKeys();if(!t)return;const r=this.matchExistingCacheKey(e,t);if(r&&(i=await this.cache.get(r)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!i)return;const a=await this.nowProvider(),s=Math.floor(a/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await(null===(r=this.keyManifest)||void 0===r?void 0:r.remove(e.toKey()))):i.body}async modifiedCachedEntry(e,t){return e.body={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},await this.cache.set(t.toKey(),e),{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}async set(e){var t;const n=new fe({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()))}async remove(e,t,n){const o=new fe({clientId:e,scope:n,audience:t});await this.cache.remove(o.toKey())}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t)}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()))}async wrapCacheEntry(e){const t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new fe({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=fe.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),!0);return"@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=fe.fromKey(o);if("@@auth0spajs@@"===t.prefix&&t.clientId===e.clientId){const t=await this.cache.get(o);if(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){var n;const o=await this.getCacheKeys();if(o)for(const r of o){const o=await this.cache.get(r);(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e&&(o.body.refresh_token=t,await this.cache.set(r,o))}}}class ge{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey="".concat("a0.spajs.txs",".").concat(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})}}const ve=e=>"number"==typeof e,be=["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"];var _e=x&&x.__assign||function(){return _e=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},_e.apply(this,arguments)};function ke(e,t){if(!t)return"";var n="; "+e;return!0===t?n:n+"="+t}var Se=function(e){return function(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent)}catch(e){}}return t}(document.cookie)[e]};function Ee(e,t,n){document.cookie=function(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("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return ke("Expires",e.expires?e.expires.toUTCString():"")+ke("Domain",e.domain)+ke("Path",e.path)+ke("Secure",e.secure)+ke("SameSite",e.sameSite)}(n)}(e,t,_e({path:"/"},n))}var Te=Ee,Ae=function(e,t){Ee(e,"",_e(_e({},t),{expires:-1}))};const Pe={get(e){const t=Se(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Te(e,JSON.stringify(t),o)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),Ae(e,n)}},Re={get:e=>Pe.get(e)||Pe.get("".concat("_legacy_").concat(e)),save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Te("".concat("_legacy_").concat(e),JSON.stringify(t),o),Pe.save(e,t,n)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),Ae(e,n),Pe.remove(e,t),Pe.remove("".concat("_legacy_").concat(e),t)}},Ie={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}};e.ResponseType=void 0,function(e){e.Code="code",e.ConnectCode="connect_code"}(e.ResponseType||(e.ResponseType={}));var Oe,Ce=function(e){return Oe=Oe||function(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtsZXQgdD1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W107cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCk7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jIGU9PntsZXQgcixjLHtkYXRhOnt0aW1lb3V0OmksYXV0aDphLGZldGNoVXJsOmYsZmV0Y2hPcHRpb25zOmwsdXNlRm9ybURhdGE6cCx1c2VNcnJ0Omh9LHBvcnRzOlt1XX09ZSxkPXt9O2NvbnN0e2F1ZGllbmNlOmcsc2NvcGU6eX09YXx8e307dHJ5e2NvbnN0IGU9cD8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShsLmJvZHkpOkpTT04ucGFyc2UobC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKGM9KChlLHQpPT5vW24oZSx0KV0pKGcseSksIWMmJmgpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxnKTtlJiYhdCYmKGM9ZSl9aWYoIWMpdGhyb3cgbmV3IHQoZyx5KTtsLmJvZHk9cD9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpfWxldCBhLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixsLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoaj1pLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsaikpKSksZmV0Y2goZixPYmplY3QuYXNzaWduKHt9LGwpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBhJiZhLmFib3J0KCksdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189ay5oZWFkZXJzLGQ9Wy4uLl9dLnJlZHVjZSgoKGUsdCk9PntsZXRbcixzXT10O3JldHVybiBlW3JdPXMsZX0pLHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKChlPT57bGV0W3Qscl09ZTtyPT09TyYmKG9bdF09Yil9KSkpLCgoZSx0LHIpPT57b1tuKHQscildPWV9KShyLnJlZnJlc2hfdG9rZW4sZyx5KSxkZWxldGUgci5yZWZyZXNoX3Rva2VuKTooKGUsdCk9PntkZWxldGUgb1tuKGUsdCldfSkoZyx5KSx1LnBvc3RNZXNzYWdlKHtvazprLm9rLGpzb246cixoZWFkZXJzOmR9KX1jYXRjaChlKXt1LnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczpkfSl9dmFyIE8sYixfLGp9KSl9KCk7Cgo=",null,false),new Worker(Oe,e)};const xe={};class je{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]})}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const 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"".concat("@@auth0spajs@@","::").concat(e)}}const De={memory:()=>(new ye).enclosedCache,localstorage:()=>new me},Le=e=>De[e],Ue=e=>{const{openUrl:t,onRedirect:n}=e,o=s(e,["openUrl","onRedirect"]);return Object.assign(Object.assign({},o),{openUrl:!1===t||t?t:n})},Ke=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},Ne={NONCE:"nonce",KEYPAIR:"keypair"};class We{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(Ne).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)}))}buildKey(e){const t=e?"_".concat(e):"auth0";return"".concat(this.clientId,"::").concat(t)}setNonce(e,t){return this.save(Ne.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Ne.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)))}findNonce(e){return this.find(Ne.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Ne.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))))}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith("".concat(t,"::"))))}clearNonces(){return this.deleteByClientId(Ne.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Ne.KEYPAIR,this.clientId)}}class ze{constructor(e){this.storage=new We(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 async function(e,t){var n;let o;return o={name:"ECDSA",namedCurve:"P-256"},crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}(0,{extractable:!1}),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return function(e){let{keyPair:t,url:n,method:o,nonce:r,accessToken:i}=e;const a=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(n);return ie(t,a,o,r,i)}(Object.assign({keyPair:t},e))}async calculateThumbprint(){return function(e){return async function(e){if(!re(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(!0!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await ae(e);let 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 ee("unsupported JWK kty")}return $(await crypto.subtle.digest({name:"SHA-256"},X(JSON.stringify(n))))}(e.publicKey)}(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}var He;!function(e){e.Bearer="Bearer",e.DPoP="DPoP"}(He||(He={}));class Me{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?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"".concat(e.replace(/\/?\/$/,""),"/").concat(t.replace(/^\/+/,""))}throw new 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"string"==typeof e?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),o=e instanceof Request?new Request(n,e):n;return new Request(o,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:He.Bearer;e.headers.set("authorization","".concat(n," ").concat(t))}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o)}async prepareRequest(e,t){const n=await this.getAccessToken(t);let o,r;"string"==typeof n?(o=this.config.dpopNonceId?He.DPoP:He.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===He.DPoP&&await this.setDpopProofHeader(e,r)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return!1;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new _(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,o);const i=await this.config.fetch(r);return this.handleResponse(i,n)}fetchWithAuth(e,t,n){const o={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},o),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,o,n)}}class Je{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/connect"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(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 Ve({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new Ve(t)}}class Ve extends Error{constructor(e){let{type:t,status:n,title:o,detail:r,validation_errors:i}=e;super(r),this.name="MyAccountApiError",this.type=t,this.status=n,this.title=o,this.detail=r,this.validation_errors=i,Object.setPrototypeOf(this,Ve.prototype)}}const Fe={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}};function Ge(e,t){this.v=e,this.k=t}function Ze(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function qe(e){return new Ge(e,0)}function Be(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Xe(e,t){return e.get(Ze(e,t))}function Ye(e,t,n){Be(e,t),t.set(e,n)}function Qe(e,t,n){return e.set(Ze(e,t),n),n}function $e(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function et(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function tt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?et(Object(n),!0).forEach((function(t){$e(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):et(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function nt(e,t){if(null==e)return{};var n,o,r=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function ot(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof Ge;Promise.resolve(s?a.v:a).then((function(n){if(s){var c="return"===t?"return":"next";if(!a.k||n.done)return o(c,n);n=e[c](n).value}r(i.done?"return":"normal",n)}),(function(e){o("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?o(t.key,t.arg):n=null}this._invoke=function(e,r){return new Promise((function(i,a){var s={key:e,arg:r,resolve:i,reject:a,next:null};n?n=n.next=s:(t=n=s,o(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}var rt,it;let at;if(ot.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ot.prototype.next=function(e){return this._invoke("next",e)},ot.prototype.throw=function(e){return this._invoke("throw",e)},ot.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(rt=navigator.userAgent)||void 0===rt||null===(it=rt.startsWith)||void 0===it||!it.call(rt,"Mozilla/5.0 ")){const e="v3.8.3";at="".concat("oauth4webapi","/").concat(e)}function st(e,t){if(null==e)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch(e){return!1}}function ct(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const ut=Symbol(),lt=Symbol(),dt=Symbol(),ht=Symbol(),pt=Symbol(),ft=Symbol(),mt=new TextEncoder,yt=new TextDecoder;function wt(e){return"string"==typeof e?mt.encode(e):yt.decode(e)}let gt,vt;if(Uint8Array.prototype.toBase64)gt=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;gt=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}function bt(e){return"string"==typeof e?vt(e):gt(e)}vt=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw ct("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}}:e=>{try{const 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 ct("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}};class _t extends Error{constructor(e,t){var n;super(e,t),$e(this,"code",void 0),this.name=this.constructor.name,this.code=wn,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}class kt extends Error{constructor(e,t){var n;super(e,t),$e(this,"code",void 0),this.name=this.constructor.name,null!=t&&t.code&&(this.code=null==t?void 0:t.code),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}function St(e,t,n){return new kt(e,{code:t,cause:n})}function Et(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Tt(e){st(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(at&&!t.has("user-agent")&&t.set("user-agent",at),t.has("authorization"))throw ct('"options.headers" must not include the "authorization" header name',"ERR_INVALID_ARG_VALUE");return t}function At(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw ct('"options.signal" must return or be an instance of AbortSignal',"ERR_INVALID_ARG_TYPE");return t}}function Pt(e){return e.includes("//")?e.replace("//","/"):e}function Rt(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw ct("".concat(n," must be a number"),"ERR_INVALID_ARG_TYPE",r);if(e>0)return;if(t){if(0!==e)throw ct("".concat(n," must be a non-negative number"),"ERR_INVALID_ARG_VALUE",r);return}throw ct("".concat(n," must be a positive number"),"ERR_INVALID_ARG_VALUE",r)}catch(e){if(o)throw St(e.message,o,r);throw e}}function It(e,t,n,o){try{if("string"!=typeof e)throw ct("".concat(t," must be a string"),"ERR_INVALID_ARG_TYPE",o);if(0===e.length)throw ct("".concat(t," must not be empty"),"ERR_INVALID_ARG_VALUE",o)}catch(e){if(n)throw St(e.message,n,o);throw e}}function Ot(e){!function(e,t){if($t(e)!==t)throw function(e){let t='"response" content-type must be ';for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];if(o.length>2){const e=o.pop();t+="".concat(o.join(", "),", or ").concat(e)}else 2===o.length?t+="".concat(o[0]," or ").concat(o[1]):t+=o[0];return St(t,_n,e)}(e,t)}(e,"application/json")}function Ct(){return bt(crypto.getRandomValues(new Uint8Array(32)))}function xt(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 _t("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 _t("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 _t("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 _t("unsupported CryptoKey algorithm name",{cause:e})}}function jt(e){const t=null==e?void 0:e[lt];return"number"==typeof t&&Number.isFinite(t)?t:0}function Dt(e){const t=null==e?void 0:e[dt];return"number"==typeof t&&Number.isFinite(t)&&-1!==Math.sign(t)?t:30}function Lt(){return Math.floor(Date.now()/1e3)}function Ut(e){if("object"!=typeof e||null===e)throw ct('"as" must be an object',"ERR_INVALID_ARG_TYPE");It(e.issuer,'"as.issuer"')}function Kt(e){if("object"!=typeof e||null===e)throw ct('"client" must be an object',"ERR_INVALID_ARG_TYPE");It(e.client_id,'"client.client_id"')}function Nt(e){return It(e,'"clientSecret"'),(t,n,o,r)=>{o.set("client_id",n.client_id),o.set("client_secret",e)}}function Wt(e,t){const{key:n,kid:o}=(r=e)instanceof CryptoKey?{key:r}:(null==r?void 0:r.key)instanceof CryptoKey?(void 0!==r.kid&&It(r.kid,'"kid"'),{key:r.key,kid:r.kid}):{};var r;return function(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw ct("".concat(t," must be a CryptoKey"),"ERR_INVALID_ARG_TYPE")}(e,t),"private"!==e.type)throw ct("".concat(t," must be a private CryptoKey"),"ERR_INVALID_ARG_VALUE")}(n,'"clientPrivateKey.key"'),async(e,r,i,a)=>{var s;const c={alg:xt(n),kid:o},u=function(e,t){const n=Lt()+jt(t);return{jti:Ct(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,r);null==t||null===(s=t[pt])||void 0===s||s.call(t,c,u),i.set("client_id",r.client_id),i.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),i.set("client_assertion",await async function(e,t,n){if(!n.usages.includes("sign"))throw ct('CryptoKey instances used for signing assertions must include "sign" in their "usages"',"ERR_INVALID_ARG_VALUE");const o="".concat(bt(wt(JSON.stringify(e))),".").concat(bt(wt(JSON.stringify(t)))),r=bt(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:xn(e)};case"RSA-PSS":switch(Cn(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 _t("unsupported RSA-PSS hash name",{cause:e})}case"RSASSA-PKCS1-v1_5":return Cn(e),e.algorithm.name;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":case"Ed25519":return e.algorithm.name}throw new _t("unsupported CryptoKey algorithm name",{cause:e})}(n),n,wt(o)));return"".concat(o,".").concat(r)}(c,u,n))}}const zt=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch(e){return null}};function Ht(e,t){if(t&&"https:"!==e.protocol)throw St("only requests to HTTPS are allowed",Sn,e);if("https:"!==e.protocol&&"http:"!==e.protocol)throw St("only HTTP and HTTPS requests are allowed",En,e)}function Mt(e,t,n,o){let r;if("string"!=typeof e||!(r=zt(e)))throw St("authorization server metadata does not contain a valid ".concat(n?'"as.mtls_endpoint_aliases.'.concat(t,'"'):'"as.'.concat(t,'"')),void 0===e?Rn:In,{attribute:n?"mtls_endpoint_aliases.".concat(t):t});return Ht(r,o),r}function Jt(e,t,n,o){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Mt(e.mtls_endpoint_aliases[t],t,n,o):Mt(e[t],t,n,o)}class Vt extends Error{constructor(e,t){var n;super(e,t),$e(this,"cause",void 0),$e(this,"code",void 0),$e(this,"error",void 0),$e(this,"status",void 0),$e(this,"error_description",void 0),$e(this,"response",void 0),this.name=this.constructor.name,this.code=yn,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}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}class Ft extends Error{constructor(e,t){var n,o;super(e,t),$e(this,"cause",void 0),$e(this,"code",void 0),$e(this,"error",void 0),$e(this,"error_description",void 0),this.name=this.constructor.name,this.code=gn,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=null!==(n=t.cause.get("error_description"))&&void 0!==n?n:void 0,null===(o=Error.captureStackTrace)||void 0===o||o.call(Error,this,this.constructor)}}class Gt extends Error{constructor(e,t){var n;super(e,t),$e(this,"cause",void 0),$e(this,"code",void 0),$e(this,"response",void 0),$e(this,"status",void 0),this.name=this.constructor.name,this.code=mn,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}const Zt=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),qt=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),Bt=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),Xt=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");async function Yt(e,t,n){if(e.status!==t){let t;var o;if(function(e){let t;if(t=function(e){if(!st(e,Response))throw ct('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");const t=e.headers.get("www-authenticate");if(null===t)return;const n=[];let o=t;for(;o;){var r;let t=o.match(Zt);const i=null===(r=t)||void 0===r?void 0:r[1].toLowerCase();if(!i)return;const a=o.substring(t[0].length);if(a&&!a.match(/^[\s,]/))return;const s=a.match(/^\s+(.*)$/),c=!!s;o=s?s[1]:void 0;const u={};let l;if(c)for(;o;){let n,r;if(t=o.match(qt)){if([,n,r,o]=t,r.includes("\\"))try{r=JSON.parse('"'.concat(r,'"'))}catch(e){}u[n.toLowerCase()]=r}else{if(!(t=o.match(Bt))){if(t=o.match(Xt)){if(Object.keys(u).length)break;[,l,o]=t;break}return}[,n,r,o]=t,u[n.toLowerCase()]=r}}else o=a||void 0;const d={scheme:i,parameters:u};l&&(d.token68=l),n.push(d)}return n.length?n:void 0}(e))throw new Gt("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){On(e),Ot(e);try{const t=await e.clone().json();if(Et(t)&&"string"==typeof t.error&&t.error.length)return t}catch(e){}}}(e))throw await(null===(o=e.body)||void 0===o?void 0:o.cancel()),new Vt("server responded with an error in the response body",{cause:t,response:e});throw St('"response" is not a conform '.concat(n," response (unexpected HTTP status code)"),kn,e)}}function Qt(e){if(!un.has(e))throw ct('"options.DPoP" is not a valid DPoPHandle',"ERR_INVALID_ARG_VALUE")}function $t(e){var t;return null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.split(";")[0]}async function en(e,t,n,o,r,i,a){return await n(e,t,r,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),((null==a?void 0:a[ht])||fetch)(o.href,{body:r,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:At(o,null==a?void 0:a.signal)})}async function tn(e,t,n,o,r,i){var a;const s=Jt(e,"token_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==i?void 0:i[ut]));r.set("grant_type",o);const c=Tt(null==i?void 0:i.headers);c.set("accept","application/json"),void 0!==(null==i?void 0:i.DPoP)&&(Qt(i.DPoP),await i.DPoP.addProof(s,c,"POST"));const u=await en(e,t,n,s,r,c,i);return null==i||null===(a=i.DPoP)||void 0===a||a.cacheNonce(u,s),u}const nn=new WeakMap,on=new WeakMap;function rn(e){if(!e.id_token)return;const t=nn.get(e);if(!t)throw ct('"ref" was already garbage collected or did not resolve from the proper sources',"ERR_INVALID_ARG_VALUE");return t}async function an(e,t,n,o,r,i){if(Ut(e),Kt(t),!st(n,Response))throw ct('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await Yt(n,200,"Token Endpoint"),On(n);const a=await Kn(n);if(It(a.access_token,'"response" body "access_token" property',bn,{body:a}),It(a.token_type,'"response" body "token_type" property',bn,{body:a}),a.token_type=a.token_type.toLowerCase(),void 0!==a.expires_in){let e="number"!=typeof a.expires_in?parseFloat(a.expires_in):a.expires_in;Rt(e,!0,'"response" body "expires_in" property',bn,{body:a}),a.expires_in=e}if(void 0!==a.refresh_token&&It(a.refresh_token,'"response" body "refresh_token" property',bn,{body:a}),void 0!==a.scope&&"string"!=typeof a.scope)throw St('"response" body "scope" property must be a string',bn,{body:a});if(void 0!==a.id_token){It(a.id_token,'"response" body "id_token" property',bn,{body:a});const i=["aud","exp","iat","iss","sub"];!0===t.require_auth_time&&i.push("auth_time"),void 0!==t.default_max_age&&(Rt(t.default_max_age,!0,'"client.default_max_age"'),i.push("auth_time")),null!=o&&o.length&&i.push(...o);const{claims:s,jwt:c}=await async function(e,t,n,o,r){let i,a,{0:s,1:c,length:u}=e.split(".");if(5===u){if(void 0===r)throw new _t("JWE decryption is not configured",{cause:e});e=await r(e),({0:s,1:c,length:u}=e.split("."))}if(3!==u)throw St("Invalid JWT",bn,e);try{i=JSON.parse(wt(bt(s)))}catch(e){throw St("failed to parse JWT Header body as base64url encoded JSON",vn,e)}if(!Et(i))throw St("JWT Header must be a top level object",bn,e);if(t(i),void 0!==i.crit)throw new _t('no JWT "crit" header parameter extensions are supported',{cause:{header:i}});try{a=JSON.parse(wt(bt(c)))}catch(e){throw St("failed to parse JWT Payload body as base64url encoded JSON",vn,e)}if(!Et(a))throw St("JWT Payload must be a top level object",bn,e);const l=Lt()+n;if(void 0!==a.exp){if("number"!=typeof a.exp)throw St('unexpected JWT "exp" (expiration time) claim type',bn,{claims:a});if(a.exp<=l-o)throw St('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Tn,{claims:a,now:l,tolerance:o,claim:"exp"})}if(void 0!==a.iat&&"number"!=typeof a.iat)throw St('unexpected JWT "iat" (issued at) claim type',bn,{claims:a});if(void 0!==a.iss&&"string"!=typeof a.iss)throw St('unexpected JWT "iss" (issuer) claim type',bn,{claims:a});if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw St('unexpected JWT "nbf" (not before) claim type',bn,{claims:a});if(a.nbf>l+o)throw St('unexpected JWT "nbf" (not before) claim value',Tn,{claims:a,now:l,tolerance:o,claim:"nbf"})}if(void 0!==a.aud&&"string"!=typeof a.aud&&!Array.isArray(a.aud))throw St('unexpected JWT "aud" (audience) claim type',bn,{claims:a});return{header:i,claims:a,jwt:e}}(a.id_token,jn.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),jt(t),Dt(t),r).then(hn.bind(void 0,i)).then(cn.bind(void 0,e)).then(sn.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&1!==s.aud.length){if(void 0===s.azp)throw St('ID Token "aud" (audience) claim includes additional untrusted audiences',An,{claims:s,claim:"aud"});if(s.azp!==t.client_id)throw St('unexpected ID Token "azp" (authorized party) claim value',An,{expected:t.client_id,claims:s,claim:"azp"})}void 0!==s.auth_time&&Rt(s.auth_time,!0,'ID Token "auth_time" (authentication time)',bn,{claims:s}),on.set(n,c),nn.set(a,s)}if(void 0!==(null==i?void 0:i[a.token_type]))i[a.token_type](n,a);else if("dpop"!==a.token_type&&"bearer"!==a.token_type)throw new _t("unsupported `token_type` value",{cause:{body:a}});return a}function sn(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw St('unexpected JWT "aud" (audience) claim value',An,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw St('unexpected JWT "aud" (audience) claim value',An,{expected:e,claims:t.claims,claim:"aud"});return t}function cn(e,t){var n,o;const r=null!==(n=null===(o=e[Wn])||void 0===o?void 0:o.call(e,t))&&void 0!==n?n:e.issuer;if(t.claims.iss!==r)throw St('unexpected JWT "iss" (issuer) claim value',An,{expected:r,claims:t.claims,claim:"iss"});return t}const un=new WeakSet,ln=Symbol(),dn={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 hn(e,t){for(const n of e)if(void 0===t.claims[n])throw St('JWT "'.concat(n,'" (').concat(dn[n],") claim missing"),bn,{claims:t.claims});return t}const pn=Symbol(),fn=Symbol();const mn="OAUTH_WWW_AUTHENTICATE_CHALLENGE",yn="OAUTH_RESPONSE_BODY_ERROR",wn="OAUTH_UNSUPPORTED_OPERATION",gn="OAUTH_AUTHORIZATION_RESPONSE_ERROR",vn="OAUTH_PARSE_ERROR",bn="OAUTH_INVALID_RESPONSE",_n="OAUTH_RESPONSE_IS_NOT_JSON",kn="OAUTH_RESPONSE_IS_NOT_CONFORM",Sn="OAUTH_HTTP_REQUEST_FORBIDDEN",En="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Tn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",An="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Pn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Rn="OAUTH_MISSING_SERVER_METADATA",In="OAUTH_INVALID_SERVER_METADATA";function On(e){if(e.bodyUsed)throw ct('"response" body has been used already',"ERR_INVALID_ARG_VALUE")}function Cn(e){const{algorithm:t}=e;if("number"!=typeof t.modulusLength||t.modulusLength<2048)throw new _t("unsupported ".concat(t.name," modulusLength"),{cause:e})}function xn(e){const{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 _t("unsupported ECDSA namedCurve",{cause:e})}}function jn(e,t,n,o){if(void 0===e)if(Array.isArray(t)){if(!t.includes(o.alg))throw St('unexpected JWT "alg" header parameter',bn,{header:o,expected:t,reason:"authorization server metadata"})}else{if(void 0===n)throw St('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n});if("string"==typeof n?o.alg!==n:"function"==typeof n?!n(o.alg):!n.includes(o.alg))throw St('unexpected JWT "alg" header parameter',bn,{header:o,expected:n,reason:"default value"})}else if("string"==typeof e?o.alg!==e:!e.includes(o.alg))throw St('unexpected JWT "alg" header parameter',bn,{header:o,expected:e,reason:"client configuration"})}function Dn(e,t){const{0:n,length:o}=e.getAll(t);if(o>1)throw St('"'.concat(t,'" parameter must be provided only once'),bn);return n}const Ln=Symbol(),Un=Symbol();async function Kn(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ot;try{t=await e.json()}catch(t){throw n(e),St('failed to parse "response" body as JSON',vn,t)}if(!Et(t))throw St('"response" body must be a top level object',bn,{body:t});return t}const Nn=Symbol(),Wn=Symbol(),zn=new TextEncoder,Hn=new TextDecoder;function Mn(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=o}return t}function Jn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Vn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:Hn.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=Hn.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Jn(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class Fn extends Error{constructor(e,t){var n;super(e,t),$e(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}$e(Fn,"code","ERR_JOSE_GENERIC");class Gn extends Fn{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),$e(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$e(this,"claim",void 0),$e(this,"reason",void 0),$e(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t}}$e(Gn,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Zn extends Fn{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),$e(this,"code","ERR_JWT_EXPIRED"),$e(this,"claim",void 0),$e(this,"reason",void 0),$e(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t}}$e(Zn,"code","ERR_JWT_EXPIRED");class qn extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}$e(qn,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Bn extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JOSE_NOT_SUPPORTED")}}$e(Bn,"code","ERR_JOSE_NOT_SUPPORTED"),$e(class extends Fn{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),$e(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),$e(class extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");class Xn extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JWS_INVALID")}}$e(Xn,"code","ERR_JWS_INVALID");class Yn extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JWT_INVALID")}}$e(Yn,"code","ERR_JWT_INVALID"),$e(class extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");class Qn extends Fn{constructor(){super(...arguments),$e(this,"code","ERR_JWKS_INVALID")}}$e(Qn,"code","ERR_JWKS_INVALID");class $n extends Fn{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),$e(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}$e($n,"code","ERR_JWKS_NO_MATCHING_KEY");class eo extends Fn{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),$e(this,Symbol.asyncIterator,void 0),$e(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}$e(eo,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class to extends Fn{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),$e(this,"code","ERR_JWKS_TIMEOUT")}}$e(to,"code","ERR_JWKS_TIMEOUT");class no extends Fn{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),$e(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}$e(no,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const oo=function(e){return new TypeError("CryptoKey does not support this operation, its ".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name"," must be ").concat(e))},ro=(e,t)=>e.name===t;function io(e){return parseInt(e.name.slice(4),10)}function ao(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if((o=o.filter(Boolean)).length>2){const t=o.pop();e+="one of type ".concat(o.join(", "),", or ").concat(t,".")}else 2===o.length?e+="one of type ".concat(o[0]," or ").concat(o[1],"."):e+="of type ".concat(o[0],".");if(null==t)e+=" Received ".concat(t);else if("function"==typeof t&&t.name)e+=" Received function ".concat(t.name);else if("object"==typeof t&&null!=t){var i;null!==(i=t.constructor)&&void 0!==i&&i.name&&(e+=" Received an instance of ".concat(t.constructor.name))}return e}const so=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return ao("Key for the ".concat(e," algorithm must be "),t,...o)},co=e=>{if("CryptoKey"===(null==e?void 0:e[Symbol.toStringTag]))return!0;try{return e instanceof CryptoKey}catch(e){return!1}},uo=e=>"KeyObject"===(null==e?void 0:e[Symbol.toStringTag]),lo=e=>co(e)||uo(e);function ho(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}const po=(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},fo=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let o=0;for(let t=0;t<n;t++)o=o<<8|e.data[e.pos++];return o}return t},mo=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},yo=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},wo=(e,t,n)=>{var o;const r=(e=>Jn(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"")))(e);let i=n;return null!=t&&null!==(o=t.startsWith)&&void 0!==o&&o.call(t,"ECDH-ES")&&(i||(i={}),i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){mo(e,48,"Invalid PKCS#8 structure"),fo(e),mo(e,2,"Expected version field");const t=fo(e);e.pos+=t,mo(e,48,"Expected algorithm identifier"),fo(e),e.pos}(t),(e=>{const t=(e=>{mo(e,6,"Expected algorithm OID");const t=fo(e);return yo(e,t)})(e);if(po(t,[43,101,110]))return"X25519";if(!po(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");mo(e,6,"Expected curve OID");const n=fo(e),o=yo(e,n);for(const{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(po(o,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,n,o)=>{var r;let i,a;const s="spki"===e,c=()=>s?["verify"]:["sign"];switch(n){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:"SHA-".concat(n.slice(-3))},a=c();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(n.slice(-3))},a=c();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(n.slice(-3),10)||1)},a=s?["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=c();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=o.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new Bn("Invalid or unsupported key format")}a=s?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},a=c();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:n},a=c();break;default:throw new Bn('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,null!==(r=null==o?void 0:o.extractable)&&void 0!==r?r:!!s,a)})("pkcs8",r,t,i)};async function go(e){var t,n;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:o,keyUsages:r}=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 Bn('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(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-".concat(parseInt(e.alg.slice(-3),10)||1)},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Bn('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},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 Bn('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}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 Bn('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Bn('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),i=tt({},e);return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,null!==(t=e.ext)&&void 0!==t?t:!e.d&&!e.priv,null!==(n=e.key_ops)&&void 0!==n?n:r)}const vo=e=>ho(e)&&"string"==typeof e.kty;let bo;const _o=async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];bo||(bo=new WeakMap);let r=bo.get(e);if(null!=r&&r[n])return r[n];const i=await go(tt(tt({},t),{},{alg:n}));return o&&Object.freeze(e),r?r[n]=i:bo.set(e,{[n]:i}),i};const ko=e=>null==e?void 0:e[Symbol.toStringTag],So=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(e,'" when present'))}if(void 0!==t.alg&&t.alg!==e)throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(e,'" when present'));if(Array.isArray(t.key_ops)){var o,r;let i;switch(!0){case"sign"===n||"verify"===n:case"dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===n?"wrapKey":"unwrapKey":n;break;case"encrypt"===n&&e.startsWith("RSA"):i="wrapKey";break;case"decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(i&&!1===(null===(o=t.key_ops)||void 0===o||null===(r=o.includes)||void 0===r?void 0:r.call(o,i)))throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(i,'" when present'))}return!0};var Eo,To;let Ao,Po;if("undefined"==typeof navigator||null===(Eo=navigator.userAgent)||void 0===Eo||null===(To=Eo.startsWith)||void 0===To||!To.call(Eo,"Mozilla/5.0 ")){const e="v6.8.1";Po="".concat("openid-client","/").concat(e),Ao={"user-agent":Po}}const Ro=e=>Io.get(e);let Io,Oo;function Co(e){return void 0!==e?Nt(e):(Oo||(Oo=new WeakMap),(e,t,n,o)=>{let r;return(r=Oo.get(t))||(function(e,t){if("string"!=typeof e)throw Lo("".concat(t," must be a string"),Do);if(0===e.length)throw Lo("".concat(t," must not be empty"),jo)}(t.client_secret,'"metadata.client_secret"'),r=Nt(t.client_secret),Oo.set(t,r)),r(e,t,n,o)})}const xo=ht,jo="ERR_INVALID_ARG_VALUE",Do="ERR_INVALID_ARG_TYPE";function Lo(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}class Uo extends Error{constructor(e,t){var n;super(e,t),$e(this,"code",void 0),this.name=this.constructor.name,this.code=null==t?void 0:t.code,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}function Ko(e,t,n){return new Uo(e,{cause:t,code:n})}function No(e){if(e instanceof TypeError||e instanceof Uo||e instanceof Vt||e instanceof Ft||e instanceof Gt)throw e;if(e instanceof kt)switch(e.code){case Sn:throw Ko("only requests to HTTPS are allowed",e,e.code);case En:throw Ko("only requests to HTTP or HTTPS are allowed",e,e.code);case kn:throw Ko("unexpected HTTP response status code",e.cause,e.code);case _n:throw Ko("unexpected response content-type",e.cause,e.code);case vn:throw Ko("parsing error occured",e,e.code);case bn:throw Ko("invalid response encountered",e,e.code);case An:throw Ko("unexpected JWT claim value encountered",e,e.code);case Pn:throw Ko("unexpected JSON attribute value encountered",e,e.code);case Tn:throw Ko("JWT timestamp claim value failed validation",e,e.code);default:throw Ko(e.message,e,e.code)}if(e instanceof _t)throw Ko("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw Ko("runtime operation error",e,wn);case"NotSupportedError":throw Ko("runtime unsupported operation",e,wn);case"TimeoutError":throw Ko("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw Ko("operation aborted",e,"OAUTH_ABORT")}throw new Uo("something went wrong",{cause:e})}async function Wo(e,t,n,o,r){const i=await async function(e,t){var n,o;if(!(e instanceof URL))throw Lo('"server" must be an instance of URL',Do);const r=!e.href.includes("/.well-known/"),i=null!==(n=null==t?void 0:t.timeout)&&void 0!==n?n:30,a=AbortSignal.timeout(1e3*i),s=await(r?async function(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw ct('"'.concat("issuerIdentifier",'" must be an instance of URL'),"ERR_INVALID_ARG_TYPE");Ht(e,!0!==(null==o?void 0:o[ut]));const r=n(new URL(e.href)),i=Tt(null==o?void 0:o.headers);return i.set("accept","application/json"),((null==o?void 0:o[ht])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:At(r,null==o?void 0:o.signal)})}(e,0,(e=>{switch(null==t?void 0:t.algorithm){case void 0:case"oidc":!function(e){e.pathname=Pt("".concat(e.pathname,"/").concat(".well-known/openid-configuration"))}(e);break;case"oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Pt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")))}(e,".well-known/oauth-authorization-server");break;default:throw ct('"options.algorithm" must be "oidc" (default), or "oauth2"',"ERR_INVALID_ARG_VALUE")}return e}),t)}(e,{algorithm:null==t?void 0:t.algorithm,[ht]:null==t?void 0:t[xo],[ut]:null==t||null===(o=t.execute)||void 0===o?void 0:o.includes(Zo),signal:a,headers:new Headers(Ao)}):((null==t?void 0:t[xo])||fetch)((Ht(e,null==t||null===(c=t.execute)||void 0===c||!c.includes(Zo)),e.href),{headers:Object.fromEntries(new Headers(tt({accept:"application/json"},Ao)).entries()),body:void 0,method:"GET",redirect:"manual",signal:a})).then((e=>async function(e,t){const n=e;if(!(n instanceof URL)&&n!==Nn)throw ct('"expectedIssuerIdentifier" must be an instance of URL',"ERR_INVALID_ARG_TYPE");if(!st(t,Response))throw ct('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");if(200!==t.status)throw St('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',kn,t);On(t);const o=await Kn(t);if(It(o.issuer,'"response" body "issuer" property',bn,{body:o}),n!==Nn&&new URL(o.issuer).href!==n.href)throw St('"response" body "issuer" property does not match the expected value',Pn,{expected:n.href,body:o,attribute:"issuer"});return o}(Nn,e))).catch(No);var c;return r&&new URL(s.issuer).href!==e.href&&(function(e,t,n){return!("https://login.microsoftonline.com"!==e.origin||null!=n&&n.algorithm&&"oidc"!==n.algorithm||(t[zo]=!0,0))}(e,s,t)||function(e,t){return!(!e.hostname.endsWith(".b2clogin.com")||null!=t&&t.algorithm&&"oidc"!==t.algorithm)}(e,t)||(()=>{throw new Uo("discovered metadata issuer does not match the expected issuer",{code:Pn,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}(e,r),a=new Ho(i,t,n,o);let s=Ro(a);if(null!=r&&r[xo]&&(s.fetch=r[xo]),null!=r&&r.timeout&&(s.timeout=r.timeout),null!=r&&r.execute)for(const e of r.execute)e(a);return a}new TextDecoder;const zo=Symbol();class Ho{constructor(e,t,n,o){var r,i,a,s,c;if("string"!=typeof t||!t.length)throw Lo('"clientId" must be a non-empty string',Do);if("string"==typeof n&&(n={client_secret:n}),void 0!==(null===(r=n)||void 0===r?void 0:r.client_id)&&t!==n.client_id)throw Lo('"clientId" and "metadata.client_id" must be the same',jo);const u=tt(tt({},structuredClone(n)),{},{client_id:t});let l;u[lt]=null!==(i=null===(a=n)||void 0===a?void 0:a[lt])&&void 0!==i?i:0,u[dt]=null!==(s=null===(c=n)||void 0===c?void 0:c[dt])&&void 0!==s?s:30,l=o||("string"==typeof u.client_secret&&u.client_secret.length?Co(u.client_secret):(e,t,n,o)=>{n.set("client_id",t.client_id)});let d=Object.freeze(u);const h=structuredClone(e);zo in e&&(h[Wn]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace("{tenantid}",n)});let p=Object.freeze(h);Io||(Io=new WeakMap),Io.set(this,{__proto__:null,as:p,c:d,auth:l,tlsOnly:!0,jwksCache:{}})}serverMetadata(){const e=structuredClone(Ro(this).as);return function(e){Object.defineProperties(e,function(e){return{supportsPKCE:{__proto__:null,value(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"S256";return!0===(null===(t=e.code_challenge_methods_supported)||void 0===t?void 0:t.includes(n))}}}}(e))}(e),e}clientMetadata(){return structuredClone(Ro(this).c)}get timeout(){return Ro(this).timeout}set timeout(e){Ro(this).timeout=e}get[xo](){return Ro(this).fetch}set[xo](e){Ro(this).fetch=e}}function Mo(e){Object.defineProperties(e,function(e){let t;if(void 0!==e.expires_in){const n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){const e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return rn(this)}catch(e){return}}}}}(e))}async function Jo(e,t,n){var o;let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=null===(o=e.headers.get("retry-after"))||void 0===o?void 0:o.trim();if(void 0===i)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else{const e=new Date(i);if(Number.isFinite(e.getTime())){const t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3))}}if(r&&!Number.isFinite(a))throw new kt("invalid Retry-After header value",{cause:e});a>t&&await Vo(a-t,n)}function Vo(e,t){return new Promise(((n,o)=>{const r=e=>{try{t.throwIfAborted()}catch(e){return void o(e)}if(e<=0)return void n();const i=Math.min(e,5);setTimeout((()=>r(e-i)),1e3*i)};r(e)}))}async function Fo(e,t){$o(e);const{as:n,c:o,auth:r,fetch:i,tlsOnly:a,timeout:s}=Ro(e);return async function(e,t,n,o,r){Ut(e),Kt(t);const i=Jt(e,"backchannel_authentication_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==r?void 0:r[ut])),a=new URLSearchParams(o);a.set("client_id",t.client_id);const s=Tt(null==r?void 0:r.headers);return s.set("accept","application/json"),en(e,t,n,i,a,s,r)}(n,o,r,t,{[ht]:i,[ut]:!a,headers:new Headers(Ao),signal:er(s)}).then((e=>async function(e,t,n){if(Ut(e),Kt(t),!st(n,Response))throw ct('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await Yt(n,200,"Backchannel Authentication Endpoint"),On(n);const o=await Kn(n);It(o.auth_req_id,'"response" body "auth_req_id" property',bn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Rt(r,!0,'"response" body "expires_in" property',bn,{body:o}),o.expires_in=r,void 0!==o.interval&&Rt(o.interval,!1,'"response" body "interval" property',bn,{body:o}),o}(n,o,e))).catch(No)}async function Go(e,t,n,o){var r,i;$o(e),n=new URLSearchParams(n);let a=null!==(r=t.interval)&&void 0!==r?r:5;const s=null!==(i=null==o?void 0:o.signal)&&void 0!==i?i:AbortSignal.timeout(1e3*t.expires_in);try{await Vo(a,s)}catch(e){No(e)}const{as:c,c:u,auth:l,fetch:d,tlsOnly:h,nonRepudiation:p,timeout:f,decrypt:m}=Ro(e),y=(r,i)=>Go(e,tt(tt({},t),{},{interval:r}),n,tt(tt({},o),{},{signal:s,flag:i})),w=await async function(e,t,n,o,r){Ut(e),Kt(t),It(o,'"authReqId"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("auth_req_id",o),tn(e,t,n,"urn:openid:params:grant-type:ciba",i,r)}(c,u,l,t.auth_req_id,{[ht]:d,[ut]:!h,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Ao),signal:s.aborted?s:er(f)}).catch(No);var g;if(503===w.status&&w.headers.has("retry-after"))return await Jo(w,a,s,!0),await(null===(g=w.body)||void 0===g?void 0:g.cancel()),y(a);const v=async function(e,t,n,o){return an(e,t,n,void 0,null==o?void 0:o[ft],null==o?void 0:o.recognizedTokenTypes)}(c,u,w,{[ft]:m});let b;try{b=await v}catch(e){if(tr(e,o))return y(a,nr);if(e instanceof Vt)switch(e.error){case"slow_down":a+=5;case"authorization_pending":return await Jo(e.response,a,s),y(a)}No(e)}return b.id_token&&await(null==p?void 0:p(w)),Mo(b),b}function Zo(e){Ro(e).tlsOnly=!1}async function qo(e,t,n,o,r){if($o(e),!((null==r?void 0:r.flag)===nr||t instanceof URL||function(e){try{return"Request"===Object.getPrototypeOf(e)[Symbol.toStringTag]}catch(e){return!1}}(t)))throw Lo('"currentUrl" must be an instance of URL, or Request',Do);let i,a;const{as:s,c:c,auth:u,fetch:l,tlsOnly:d,jarm:h,hybrid:p,nonRepudiation:f,timeout:m,decrypt:y,implicit:w}=Ro(e);if((null==r?void 0:r.flag)===nr)i=r.authResponse,a=r.redirectUri;else{if(!(t instanceof URL)){const e=t;switch(t=new URL(t.url),e.method){case"GET":break;case"POST":const n=new URLSearchParams(await async function(e){if("POST"!==e.method)throw ct("form_post responses are expected to use the POST method","ERR_INVALID_ARG_VALUE",{cause:e});if("application/x-www-form-urlencoded"!==$t(e))throw ct("form_post responses are expected to use the application/x-www-form-urlencoded content-type","ERR_INVALID_ARG_VALUE",{cause:e});return async function(e){if(e.bodyUsed)throw ct("form_post Request instances must contain a readable body","ERR_INVALID_ARG_VALUE",{cause:e});return e.text()}(e)}(e));if(p)t.hash=n.toString();else for(const[e,o]of n.entries())t.searchParams.append(e,o);break;default:throw Lo("unexpected Request HTTP method",jo)}}switch(a=function(e){return(e=new URL(e)).search="",e.hash="",e.href}(t),!0){case!!h:i=await h(t,null==n?void 0:n.expectedState);break;case!!p:i=await p(t,null==n?void 0:n.expectedNonce,null==n?void 0:n.expectedState,null==n?void 0:n.maxAge);break;case!!w:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=function(e,t,n,o){if(Ut(e),Kt(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw ct('"parameters" must be an instance of URLSearchParams, or URL',"ERR_INVALID_ARG_TYPE");if(Dn(n,"response"))throw St('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',bn,{parameters:n});const r=Dn(n,"iss"),i=Dn(n,"state");if(!r&&e.authorization_response_iss_parameter_supported)throw St('response parameter "iss" (issuer) missing',bn,{parameters:n});if(r&&r!==e.issuer)throw St('unexpected "iss" (issuer) response parameter value',bn,{expected:e.issuer,parameters:n});switch(o){case void 0:case Un:if(void 0!==i)throw St('unexpected "state" response parameter encountered',bn,{expected:void 0,parameters:n});break;case Ln:break;default:if(It(o,'"expectedState" argument'),i!==o)throw St(void 0===i?'response parameter "state" missing':'unexpected "state" response parameter value',bn,{expected:o,parameters:n})}if(Dn(n,"error"))throw new Ft("authorization response from the server is an error",{cause:n});const a=Dn(n,"id_token"),s=Dn(n,"token");if(void 0!==a||void 0!==s)throw new _t("implicit and hybrid flows are not supported");return c=new URLSearchParams(n),un.add(c),c;var c}(s,c,t.searchParams,null==n?void 0:n.expectedState)}catch(e){No(e)}}}const g=await async function(e,t,n,o,r,i,a){if(Ut(e),Kt(t),!un.has(o))throw ct('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',"ERR_INVALID_ARG_VALUE");It(r,'"redirectUri"');const s=Dn(o,"code");if(!s)throw St('no authorization code in "callbackParameters"',bn);const c=new URLSearchParams(null==a?void 0:a.additionalParameters);return c.set("redirect_uri",r),c.set("code",s),i!==ln&&(It(i,'"codeVerifier"'),c.set("code_verifier",i)),tn(e,t,n,"authorization_code",c,a)}(s,c,u,i,a,(null==n?void 0:n.pkceCodeVerifier)||ln,{additionalParameters:o,[ht]:l,[ut]:!d,DPoP:null==r?void 0:r.DPoP,headers:new Headers(Ao),signal:er(m)}).catch(No);"string"!=typeof(null==n?void 0:n.expectedNonce)&&"number"!=typeof(null==n?void 0:n.maxAge)||(n.idTokenExpected=!0);const v=async function(e,t,n,o){return"string"==typeof(null==o?void 0:o.expectedNonce)||"number"==typeof(null==o?void 0:o.maxAge)||null!=o&&o.requireIdToken?async function(e,t,n,o,r,i,a){const s=[];switch(o){case void 0:o=pn;break;case pn:break;default:It(o,'"expectedNonce" argument'),s.push("nonce")}switch(null!=r||(r=t.default_max_age),r){case void 0:r=fn;break;case fn:break;default:Rt(r,!0,'"maxAge" argument'),s.push("auth_time")}const c=await an(e,t,n,s,i,a);It(c.id_token,'"response" body "id_token" property',bn,{body:c});const u=rn(c);if(r!==fn){const e=Lt()+jt(t),n=Dt(t);if(u.auth_time+r<e-n)throw St("too much time has elapsed since the last End-User authentication",Tn,{claims:u,now:e,tolerance:n,claim:"auth_time"})}if(o===pn){if(void 0!==u.nonce)throw St('unexpected ID Token "nonce" claim value',An,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==o)throw St('unexpected ID Token "nonce" claim value',An,{expected:o,claims:u,claim:"nonce"});return c}(e,t,n,o.expectedNonce,o.maxAge,o[ft],o.recognizedTokenTypes):async function(e,t,n,o,r){const i=await an(e,t,n,void 0,o,r),a=rn(i);if(a){if(void 0!==t.default_max_age){Rt(t.default_max_age,!0,'"client.default_max_age"');const e=Lt()+jt(t),n=Dt(t);if(a.auth_time+t.default_max_age<e-n)throw St("too much time has elapsed since the last End-User authentication",Tn,{claims:a,now:e,tolerance:n,claim:"auth_time"})}if(void 0!==a.nonce)throw St('unexpected ID Token "nonce" claim value',An,{expected:void 0,claims:a,claim:"nonce"})}return i}(e,t,n,null==o?void 0:o[ft],null==o?void 0:o.recognizedTokenTypes)}(s,c,g,{expectedNonce:null==n?void 0:n.expectedNonce,maxAge:null==n?void 0:n.maxAge,requireIdToken:null==n?void 0:n.idTokenExpected,[ft]:y});let b;try{b=await v}catch(t){if(tr(t,r))return qo(e,void 0,n,o,tt(tt({},r),{},{flag:nr,authResponse:i,redirectUri:a}));No(t)}return b.id_token&&await(null==f?void 0:f(g)),Mo(b),b}async function Bo(e,t,n,o){$o(e),n=new URLSearchParams(n);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,nonRepudiation:u,timeout:l,decrypt:d}=Ro(e),h=await async function(e,t,n,o,r){Ut(e),Kt(t),It(o,'"refreshToken"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("refresh_token",o),tn(e,t,n,"refresh_token",i,r)}(r,i,a,t,{[ht]:s,[ut]:!c,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Ao),signal:er(l)}).catch(No),p=async function(e,t,n,o){return an(e,t,n,void 0,null==o?void 0:o[ft],null==o?void 0:o.recognizedTokenTypes)}(r,i,h,{[ft]:d});let f;try{f=await p}catch(r){if(tr(r,o))return Bo(e,t,n,tt(tt({},o),{},{flag:nr}));No(r)}return f.id_token&&await(null==u?void 0:u(h)),Mo(f),f}async function Xo(e,t,n){$o(e),t=new URLSearchParams(t);const{as:o,c:r,auth:i,fetch:a,tlsOnly:s,timeout:c}=Ro(e),u=await async function(e,t,n,o,r){return Ut(e),Kt(t),tn(e,t,n,"client_credentials",new URLSearchParams(o),r)}(o,r,i,t,{[ht]:a,[ut]:!s,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Ao),signal:er(c)}).catch(No),l=async function(e,t,n){return an(e,t,n,void 0,void 0,void 0)}(o,r,u);let d;try{d=await l}catch(o){if(tr(o,n))return Xo(e,t,tt(tt({},n),{},{flag:nr}));No(o)}return Mo(d),d}function Yo(e,t){$o(e);const{as:n,c:o,tlsOnly:r,hybrid:i,jarm:a,implicit:s}=Ro(e),c=Jt(n,"authorization_endpoint",!1,r);if((t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw Lo("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",jo);a&&t.set("response_mode","jwt")}for(const[e,n]of t.entries())c.searchParams.append(e,n);return c}async function Qo(e,t,n){$o(e);const o=Yo(e,t),{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u}=Ro(e),l=await async function(e,t,n,o,r){var i;Ut(e),Kt(t);const a=Jt(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==r?void 0:r[ut])),s=new URLSearchParams(o);s.set("client_id",t.client_id);const c=Tt(null==r?void 0:r.headers);c.set("accept","application/json"),void 0!==(null==r?void 0:r.DPoP)&&(Qt(r.DPoP),await r.DPoP.addProof(a,c,"POST"));const u=await en(e,t,n,a,s,c,r);return null==r||null===(i=r.DPoP)||void 0===i||i.cacheNonce(u,a),u}(r,i,a,o.searchParams,{[ht]:s,[ut]:!c,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Ao),signal:er(u)}).catch(No),d=async function(e,t,n){if(Ut(e),Kt(t),!st(n,Response))throw ct('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await Yt(n,201,"Pushed Authorization Request Endpoint"),On(n);const o=await Kn(n);It(o.request_uri,'"response" body "request_uri" property',bn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Rt(r,!0,'"response" body "expires_in" property',bn,{body:o}),o.expires_in=r,o}(r,i,l);let h;try{h=await d}catch(o){if(tr(o,n))return Qo(e,t,tt(tt({},n),{},{flag:nr}));No(o)}return Yo(e,{request_uri:h.request_uri})}function $o(e){if(!(e instanceof Ho))throw Lo('"config" must be an instance of Configuration',Do);if(Object.getPrototypeOf(e)!==Ho.prototype)throw Lo("subclassing Configuration is not allowed",jo)}function er(e){return e?AbortSignal.timeout(1e3*e):void 0}function tr(e,t){return!(null==t||!t.DPoP||t.flag===nr)&&function(e){if(e instanceof Gt){const{0:t,length:n}=e.cause;return 1===n&&"dpop"===t.scheme&&"use_dpop_nonce"===t.parameters.error}return e instanceof Vt&&"use_dpop_nonce"===e.error}(e)}Object.freeze(Ho.prototype);const nr=Symbol();async function or(e,t,n,o){$o(e);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u,decrypt:l}=Ro(e),d=await async function(e,t,n,o,r,i){return Ut(e),Kt(t),It(o,'"grantType"'),tn(e,t,n,o,new URLSearchParams(r),i)}(r,i,a,t,new URLSearchParams(n),{[ht]:s,[ut]:!c,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Ao),signal:er(u)}).then((e=>{let n;return"urn:ietf:params:oauth:grant-type:token-exchange"===t&&(n={n_a:()=>{}}),async function(e,t,n,o){return an(e,t,n,void 0,null==o?void 0:o[ft],null==o?void 0:o.recognizedTokenTypes)}(r,i,e,{[ft]:l,recognizedTokenTypes:n})})).catch(No);return Mo(d),d}async function rr(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return ao("Key must be ",e,...n)}(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:"SHA-".concat(e.slice(-3)),name:"HMAC"},!1,[n])}return function(e,t,n){switch(t){case"HS256":case"HS384":case"HS512":{if(!ro(e.algorithm,"HMAC"))throw oo("HMAC");const n=parseInt(t.slice(2),10);if(io(e.algorithm.hash)!==n)throw oo("SHA-".concat(n),"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ro(e.algorithm,"RSASSA-PKCS1-v1_5"))throw oo("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(io(e.algorithm.hash)!==n)throw oo("SHA-".concat(n),"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ro(e.algorithm,"RSA-PSS"))throw oo("RSA-PSS");const n=parseInt(t.slice(2),10);if(io(e.algorithm.hash)!==n)throw oo("SHA-".concat(n),"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!ro(e.algorithm,"Ed25519"))throw oo("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!ro(e.algorithm,t))throw oo(t);break;case"ES256":case"ES384":case"ES512":{if(!ro(e.algorithm,"ECDSA"))throw oo("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw oo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(t,"."))}(e,n)}(t,e,n),t}async function ir(e,t,n){if(!ho(e))throw new Xn("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new Xn('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new Xn("JWS Protected Header incorrect type");if(void 0===e.payload)throw new Xn("JWS Payload missing");if("string"!=typeof e.signature)throw new Xn("JWS Signature missing or incorrect type");if(void 0!==e.header&&!ho(e.header))throw new Xn("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=Vn(e.protected);o=JSON.parse(Hn.decode(t))}catch(e){throw new Xn("JWS Protected Header is invalid")}if(!function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.filter(Boolean);if(0===o.length||1===o.length)return!0;let r;for(const e of o){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0}(o,e.header))throw new Xn("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r=tt(tt({},o),e.header),i=function(e,t,n,o,r){if(void 0!==r.crit&&void 0===(null==o?void 0:o.crit))throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new Bn('Extension Header Parameter "'.concat(t,'" is not recognized'));if(void 0===r[t])throw new e('Extension Header Parameter "'.concat(t,'" is missing'));if(i.get(t)&&void 0===o[t])throw new e('Extension Header Parameter "'.concat(t,'" MUST be integrity protected'))}return new Set(o.crit)}(Xn,new Map([["b64",!0]]),null==n?void 0:n.crit,o,r);let a=!0;if(i.has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new Xn('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new Xn('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError('"'.concat("algorithms",'" option must be an array of strings'));if(t)return new Set(t)}(0,n.algorithms);if(c&&!c.has(s))throw new qn('"alg" (Algorithm) Header Parameter value not allowed');if(a){if("string"!=typeof e.payload)throw new Xn("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new Xn("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t&&(t=await t(o,e),u=!0),function(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(vo(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&So(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!lo(t))throw new TypeError(so(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError("".concat(ko(t),' instances for symmetric algorithms must be of type "secret"'))}})(e,t,n);break;default:((e,t,n)=>{if(vo(t))switch(n){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&So(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&So(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!lo(t))throw new TypeError(so(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError("".concat(ko(t),' instances for asymmetric algorithms must not be of type "secret"'));if("public"===t.type)switch(n){case"sign":throw new TypeError("".concat(ko(t),' instances for asymmetric algorithm signing must be of type "private"'));case"decrypt":throw new TypeError("".concat(ko(t),' instances for asymmetric algorithm decryption must be of type "private"'))}if("private"===t.type)switch(n){case"verify":throw new TypeError("".concat(ko(t),' instances for asymmetric algorithm verifying must be of type "public"'));case"encrypt":throw new TypeError("".concat(ko(t),' instances for asymmetric algorithm encryption must be of type "public"'))}})(e,t,n)}}(s,t,"verify");const l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.reduce(((e,t)=>{let{length:n}=t;return e+n}),0),r=new Uint8Array(o);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}(void 0!==e.protected?Mn(e.protected):new Uint8Array,Mn("."),"string"==typeof e.payload?a?Mn(e.payload):zn.encode(e.payload):e.payload);let d;try{d=Vn(e.signature)}catch(e){throw new Xn("Failed to base64url decode the signature")}const h=await async function(e,t){if(e instanceof Uint8Array)return e;if(co(e))return e;if(uo(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{bo||(bo=new WeakMap);let n=bo.get(e);if(null!=n&&n[t])return n[t];const o="public"===e.type,r=!!o;let i;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=e.toCryptoKey(e.asymmetricKeyType,r,o?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){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 new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,o?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[o?"verify":"sign"])}if("ec"===e.asymmetricKeyType){var a;const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(null===(a=e.asymmetricKeyDetails)||void 0===a?void 0:a.namedCurve);if(!n)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES384"===t&&"P-384"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES512"===t&&"P-521"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:n},r,o?[]:["deriveBits"]))}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[t]=i:bo.set(e,{[t]:i}),i})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return _o(e,n,t)}if(vo(e))return e.k?Vn(e.k):_o(e,e,t,!0);throw new Error("unreachable")}(t,s);if(!await async function(e,t,n,o){const r=await rr(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError("".concat(e," requires key modulusLength to be 2048 bits or larger"))}}(e,r);const i=function(e,t){const n="SHA-".concat(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 Bn("alg ".concat(e," is not supported either by JOSE or your javascript runtime"))}}(e,r.algorithm);try{return await crypto.subtle.verify(i,r,n,o)}catch(e){return!1}}(s,h,d,l))throw new no;let p;if(a)try{p=Vn(e.payload)}catch(e){throw new Xn("Failed to base64url decode the payload")}else p="string"==typeof e.payload?zn.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=o),void 0!==e.header&&(f.unprotectedHeader=e.header),u?tt(tt({},f),{},{key:h}):f}const ar=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function sr(e){const t=ar.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(3600*n);break;case"day":case"days":case"d":o=Math.round(86400*n);break;case"week":case"weeks":case"w":o=Math.round(604800*n);break;default:o=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-o:o}const cr=e=>e.includes("/")?e.toLowerCase():"application/".concat(e.toLowerCase());async function ur(e,t,n){var o;const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=Hn.decode(e)),"string"!=typeof e)throw new Xn("Compact JWS must be a string or Uint8Array");const{0:o,1:r,2:i,length:a}=e.split(".");if(3!==a)throw new Xn("Invalid Compact JWS");const s=await ir({payload:r,protected:o,signature:i},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?tt(tt({},c),{},{key:s.key}):c}(e,t,n);if(null!==(o=r.protectedHeader.crit)&&void 0!==o&&o.includes("b64")&&!1===r.protectedHeader.b64)throw new Yn("JWTs MUST NOT use unencoded payload");const i=function(e,t){let n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{n=JSON.parse(Hn.decode(t))}catch(e){}if(!ho(n))throw new Yn("JWT Claims Set must be a top-level JSON object");const{typ:r}=o;if(r&&("string"!=typeof e.typ||cr(e.typ)!==cr(r)))throw new Gn('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=o,l=[...i];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new Gn('missing required "'.concat(e,'" claim'),n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new Gn('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new Gn('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!((e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e))))(n.aud,"string"==typeof c?[c]:c))throw new Gn('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof o.clockTolerance){case"string":d=sr(o.clockTolerance);break;case"number":d=o.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=o,p=(e=>Math.floor(e.getTime()/1e3))(h||new Date);if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new Gn('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new Gn('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+d)throw new Gn('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new Gn('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-d)throw new Zn('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const e=p-n.iat;if(e-d>("number"==typeof u?u:sr(u)))throw new Zn('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-d)throw new Gn('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}(r.protectedHeader,r.payload,n),a={payload:i,protectedHeader:r.protectedHeader};return"function"==typeof t?tt(tt({},a),{},{key:r.key}):a}function lr(e){return ho(e)}var dr,hr,pr=new WeakMap,fr=new WeakMap;class mr{constructor(e){if(Ye(this,pr,void 0),Ye(this,fr,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(lr)}(e))throw new Qn("JSON Web Key Set malformed");Qe(pr,this,structuredClone(e))}jwks(){return Xe(pr,this)}async getKey(e,t){const{alg:n,kid:o}=tt(tt({},e),null==t?void 0:t.header),r=function(e){switch("string"==typeof e&&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 Bn('Unsupported "alg" value for a JSON Web Key Set')}}(n),i=Xe(pr,this).keys.filter((e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=n===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(n){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t})),{0:a,length:s}=i;if(0===s)throw new $n;if(1!==s){const e=new eo,t=Xe(fr,this);throw e[Symbol.asyncIterator]=function(e){return function(){return new ot(e.apply(this,arguments))}}((function*(){for(const e of i)try{yield yield qe(yr(t,e,n))}catch(e){}})),e}return yr(Xe(fr,this),a,n)}}async function yr(e,t,n){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[n]){const e=await async function(e,t){if(!ho(e))throw new TypeError("JWK must be an object");let n;switch(null!=t||(t=e.alg),null!=n||(n=e.ext),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Vn(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new Bn('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return go(tt(tt({},e),{},{alg:t,ext:n}));case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return go(tt(tt({},e),{},{ext:n}));case"EC":case"OKP":return go(tt(tt({},e),{},{alg:t,ext:n}));default:throw new Bn('Unsupported "kty" (Key Type) Parameter value')}}(tt(tt({},t),{},{ext:!0}),n);if(e instanceof Uint8Array||"public"!==e.type)throw new Qn("JSON Web Key Set members must be public keys");o[n]=e}return o[n]}function wr(e){const t=new mr(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}let gr;if("undefined"==typeof navigator||null===(dr=navigator.userAgent)||void 0===dr||null===(hr=dr.startsWith)||void 0===hr||!hr.call(dr,"Mozilla/5.0 ")){const e="v6.1.3";gr="".concat("jose","/").concat(e)}const vr=Symbol(),br=Symbol();var _r=new WeakMap,kr=new WeakMap,Sr=new WeakMap,Er=new WeakMap,Tr=new WeakMap,Ar=new WeakMap,Pr=new WeakMap,Rr=new WeakMap,Ir=new WeakMap,Or=new WeakMap;class Cr{constructor(e,t){if(Ye(this,_r,void 0),Ye(this,kr,void 0),Ye(this,Sr,void 0),Ye(this,Er,void 0),Ye(this,Tr,void 0),Ye(this,Ar,void 0),Ye(this,Pr,void 0),Ye(this,Rr,void 0),Ye(this,Ir,void 0),Ye(this,Or,void 0),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,o;Qe(_r,this,new URL(e.href)),Qe(kr,this,"number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3),Qe(Sr,this,"number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4),Qe(Er,this,"number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5),Qe(Pr,this,new Headers(null==t?void 0:t.headers)),gr&&!Xe(Pr,this).has("User-Agent")&&Xe(Pr,this).set("User-Agent",gr),Xe(Pr,this).has("accept")||(Xe(Pr,this).set("accept","application/json"),Xe(Pr,this).append("accept","application/jwk-set+json")),Qe(Rr,this,null==t?void 0:t[vr]),void 0!==(null==t?void 0:t[br])&&(Qe(Or,this,null==t?void 0:t[br]),n=null==t?void 0:t[br],o=Xe(Er,this),"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=o)&&"jwks"in n&&ho(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,ho)&&(Qe(Tr,this,Xe(Or,this).uat),Qe(Ir,this,wr(Xe(Or,this).jwks))))}pendingFetch(){return!!Xe(Ar,this)}coolingDown(){return"number"==typeof Xe(Tr,this)&&Date.now()<Xe(Tr,this)+Xe(Sr,this)}fresh(){return"number"==typeof Xe(Tr,this)&&Date.now()<Xe(Tr,this)+Xe(Er,this)}jwks(){var e;return null===(e=Xe(Ir,this))||void 0===e?void 0:e.jwks()}async getKey(e,t){Xe(Ir,this)&&this.fresh()||await this.reload();try{return await Xe(Ir,this).call(this,e,t)}catch(n){if(n instanceof $n&&!1===this.coolingDown())return await this.reload(),Xe(Ir,this).call(this,e,t);throw n}}async reload(){Xe(Ar,this)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&Qe(Ar,this,void 0),Xe(Ar,this)||Qe(Ar,this,async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:fetch;const r=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((e=>{if("TimeoutError"===e.name)throw new to;throw e}));if(200!==r.status)throw new Fn("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch(e){throw new Fn("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(Xe(_r,this).href,Xe(Pr,this),AbortSignal.timeout(Xe(kr,this)),Xe(Rr,this)).then((e=>{Qe(Ir,this,wr(e)),Xe(Or,this)&&(Xe(Or,this).uat=Date.now(),Xe(Or,this).jwks=e),Qe(Tr,this,Date.now()),Qe(Ar,this,void 0)})).catch((e=>{throw Qe(Ar,this,void 0),e}))),await Xe(Ar,this)}}const xr=["mfaToken"],jr=["mfaToken"];var Dr,Lr,Ur,Kr,Nr,Wr,zr,Hr,Mr=class extends Error{constructor(e,t){super(t),$e(this,"code",void 0),this.name="NotSupportedError",this.code=e}},Jr=class extends Error{constructor(e,t,n){super(t),$e(this,"cause",void 0),$e(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},Vr=class extends Jr{constructor(e,t){super("token_by_code_error",e,t),this.name="TokenByCodeError"}},Fr=class extends Jr{constructor(e,t){super("token_by_client_credentials_error",e,t),this.name="TokenByClientCredentialsError"}},Gr=class extends Jr{constructor(e,t){super("token_by_refresh_token_error",e,t),this.name="TokenByRefreshTokenError"}},Zr=class extends Jr{constructor(e,t){super("token_for_connection_error",e,t),this.name="TokenForConnectionErrorCode"}},qr=class extends Jr{constructor(e,t){super("token_exchange_error",e,t),this.name="TokenExchangeError"}},Br=class extends Error{constructor(e){super(e),$e(this,"code","verify_logout_token_error"),this.name="VerifyLogoutTokenError"}},Xr=class extends Jr{constructor(e){super("backchannel_authentication_error","There was an error when trying to use Client-Initiated Backchannel Authentication.",e),$e(this,"code","backchannel_authentication_error"),this.name="BackchannelAuthenticationError"}},Yr=class extends Jr{constructor(e){super("build_authorization_url_error","There was an error when trying to build the authorization URL.",e),this.name="BuildAuthorizationUrlError"}},Qr=class extends Jr{constructor(e){super("build_link_user_url_error","There was an error when trying to build the Link User URL.",e),this.name="BuildLinkUserUrlError"}},$r=class extends Jr{constructor(e){super("build_unlink_user_url_error","There was an error when trying to build the Unlink User URL.",e),this.name="BuildUnlinkUserUrlError"}},ei=class extends Error{constructor(){super("The client secret or client assertion signing key must be provided."),$e(this,"code","missing_client_auth_error"),this.name="MissingClientAuthError"}};function ti(e){return Object.entries(e).filter((e=>{let[,t]=e;return void 0!==t})).reduce(((e,t)=>tt(tt({},e),{},{[t[0]]:t[1]})),{})}var ni=class extends Error{constructor(e,t,n){super(t),$e(this,"cause",void 0),$e(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},oi=class extends ni{constructor(e,t){super("mfa_list_authenticators_error",e,t),this.name="MfaListAuthenticatorsError"}},ri=class extends ni{constructor(e,t){super("mfa_enrollment_error",e,t),this.name="MfaEnrollmentError"}},ii=class extends ni{constructor(e,t){super("mfa_delete_authenticator_error",e,t),this.name="MfaDeleteAuthenticatorError"}},ai=class extends ni{constructor(e,t){super("mfa_challenge_error",e,t),this.name="MfaChallengeError"}};function si(e){return{id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var ci=(Dr=new WeakMap,Lr=new WeakMap,Ur=new WeakMap,class{constructor(e){var t;Ye(this,Dr,void 0),Ye(this,Lr,void 0),Ye(this,Ur,void 0),Qe(Dr,this,"https://".concat(e.domain)),Qe(Lr,this,e.clientId),Qe(Ur,this,null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)})}async listAuthenticators(e){const t="".concat(Xe(Dr,this),"/mfa/authenticators"),{mfaToken:n}=e,o=await Xe(Ur,this).call(this,t,{method:"GET",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!o.ok){const e=await o.json();throw new oi(e.error_description||"Failed to list authenticators",e)}return(await o.json()).map(si)}async enrollAuthenticator(e){const t="".concat(Xe(Dr,this),"/mfa/associate"),{mfaToken:n}=e,o=nt(e,xr),r={authenticator_types:o.authenticatorTypes};"oobChannels"in o&&(r.oob_channels=o.oobChannels),"phoneNumber"in o&&o.phoneNumber&&(r.phone_number=o.phoneNumber),"email"in o&&o.email&&(r.email=o.email);const i=await Xe(Ur,this).call(this,t,{method:"POST",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new ri(e.error_description||"Failed to enroll authenticator",e)}return function(e){if("otp"===e.authenticator_type)return{authenticatorType:"otp",secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if("oob"===e.authenticator_type)return{authenticatorType:"oob",oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id};throw new Error("Unexpected authenticator type: ".concat(e.authenticator_type))}(await i.json())}async deleteAuthenticator(e){const{authenticatorId:t,mfaToken:n}=e,o="".concat(Xe(Dr,this),"/mfa/authenticators/").concat(encodeURIComponent(t)),r=await Xe(Ur,this).call(this,o,{method:"DELETE",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!r.ok){const e=await r.json();throw new ii(e.error_description||"Failed to delete authenticator",e)}}async challengeAuthenticator(e){const t="".concat(Xe(Dr,this),"/mfa/challenge"),{mfaToken:n}=e,o=nt(e,jr),r={mfa_token:n,client_id:Xe(Lr,this),challenge_type:o.challengeType};o.authenticatorId&&(r.authenticator_id=o.authenticatorId);const i=await Xe(Ur,this).call(this,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new ai(e.error_description||"Failed to challenge authenticator",e)}return function(e){const t={challengeType:e.challenge_type};return void 0!==e.oob_code&&(t.oobCode=e.oob_code),void 0!==e.binding_method&&(t.bindingMethod=e.binding_method),t}(await i.json())}}),ui=class e{constructor(e,t,n,o,r,i,a){$e(this,"accessToken",void 0),$e(this,"idToken",void 0),$e(this,"refreshToken",void 0),$e(this,"expiresAt",void 0),$e(this,"scope",void 0),$e(this,"claims",void 0),$e(this,"authorizationDetails",void 0),$e(this,"tokenType",void 0),$e(this,"issuedTokenType",void 0),this.accessToken=e,this.idToken=n,this.refreshToken=o,this.expiresAt=t,this.scope=r,this.claims=i,this.authorizationDetails=a}static fromTokenEndpointResponse(t){const n=t.id_token?t.claims():void 0,o=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 o.tokenType=t.token_type,o.issuedTokenType=t.issued_token_type,o}},li="openid profile email offline_access",di=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 hi(e){if(null==e)throw new qr("subject_token is required");if("string"!=typeof e)throw new qr("subject_token must be a string");if(0===e.trim().length)throw new qr("subject_token cannot be blank or whitespace");if(e!==e.trim())throw new qr("subject_token must not include leading or trailing whitespace");if(/^bearer\s+/i.test(e))throw new qr("subject_token must not include the 'Bearer ' prefix")}function pi(e,t){if(t)for(const[n,o]of Object.entries(t))if(!di.has(n))if(Array.isArray(o)){if(o.length>20)throw new qr("Parameter '".concat(n,"' exceeds maximum array size of ").concat(20));o.forEach((t=>{e.append(n,t)}))}else e.append(n,o)}var fi=(Kr=new WeakMap,Nr=new WeakMap,Wr=new WeakMap,zr=new WeakMap,Hr=new WeakSet,class{constructor(e){if(function(e,t){Be(e,t),t.add(e)}(this,Hr),Ye(this,Kr,void 0),Ye(this,Nr,void 0),Ye(this,Wr,void 0),Ye(this,zr,void 0),$e(this,"mfa",void 0),Qe(Wr,this,e),e.useMtls&&!e.customFetch)throw new Mr("mtls_without_custom_fetch_not_supported","Using mTLS without a custom fetch implementation is not supported");this.mfa=new ci({domain:Xe(Wr,this).domain,clientId:Xe(Wr,this).clientId,customFetch:Xe(Wr,this).customFetch})}async buildAuthorizationUrl(e){const{serverMetadata:t}=await Ze(Hr,this,mi).call(this);if(null!=e&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new Mr("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 Ze(Hr,this,vi).call(this,e)}catch(e){throw new Yr(e)}}async buildLinkUserUrl(e){try{const t=await Ze(Hr,this,vi).call(this,{authorizationParams:tt(tt({},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 Qr(e)}}async buildUnlinkUserUrl(e){try{const t=await Ze(Hr,this,vi).call(this,{authorizationParams:tt(tt({},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 $r(e)}}async backchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await Ze(Hr,this,mi).call(this),o=ti(tt(tt({},Xe(Wr,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(tt(tt({scope:li},o),{},{client_id:Xe(Wr,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await Fo(t,r),n=await Go(t,e);return ui.fromTokenEndpointResponse(n)}catch(e){throw new Xr(e)}}async initiateBackchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await Ze(Hr,this,mi).call(this),o=ti(tt(tt({},Xe(Wr,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(tt(tt({scope:li},o),{},{client_id:Xe(Wr,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await Fo(t,r);return{authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new Xr(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e;const{configuration:n}=await Ze(Hr,this,mi).call(this),o=new URLSearchParams({auth_req_id:t});try{const e=await or(n,"urn:openid:params:grant-type:ciba",o);return ui.fromTokenEndpointResponse(e)}catch(e){throw new Xr(e)}}async getTokenForConnection(e){var t;if(e.refreshToken&&e.accessToken)throw new Zr("Either a refresh or access token should be specified, but not both.");const n=null!==(t=e.accessToken)&&void 0!==t?t:e.refreshToken;if(!n)throw new Zr("Either a refresh or access token must be specified.");try{return await this.exchangeToken({connection:e.connection,subjectToken:n,subjectTokenType:e.accessToken?"urn:ietf:params:oauth:token-type:access_token":"urn:ietf:params:oauth:token-type:refresh_token",loginHint:e.loginHint})}catch(e){if(e instanceof qr)throw new Zr(e.message,e.cause);throw e}}async exchangeToken(e){return"connection"in e?Ze(Hr,this,yi).call(this,e):Ze(Hr,this,wi).call(this,e)}async getTokenByCode(e,t){const{configuration:n}=await Ze(Hr,this,mi).call(this);try{const o=await qo(n,e,{pkceCodeVerifier:t.codeVerifier});return ui.fromTokenEndpointResponse(o)}catch(e){throw new Vr("There was an error while trying to request a token.",e)}}async getTokenByRefreshToken(e){const{configuration:t}=await Ze(Hr,this,mi).call(this);try{const n=await Bo(t,e.refreshToken);return ui.fromTokenEndpointResponse(n)}catch(e){throw new Gr("The access token has expired and there was an error while trying to refresh it.",e)}}async getTokenByClientCredentials(e){const{configuration:t}=await Ze(Hr,this,mi).call(this);try{const n=new URLSearchParams({audience:e.audience});e.organization&&n.append("organization",e.organization);const o=await Xo(t,n);return ui.fromTokenEndpointResponse(o)}catch(e){throw new Fr("There was an error while trying to request a token.",e)}}async buildLogoutUrl(e){const{configuration:t,serverMetadata:n}=await Ze(Hr,this,mi).call(this);if(!n.end_session_endpoint){const t=new URL("https://".concat(Xe(Wr,this).domain,"/v2/logout"));return t.searchParams.set("returnTo",e.returnTo),t.searchParams.set("client_id",Xe(Wr,this).clientId),t}return function(e,t){$o(e);const{as:n,c:o,tlsOnly:r}=Ro(e),i=Jt(n,"end_session_endpoint",!1,r);(t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id);for(const[e,n]of t.entries())i.searchParams.append(e,n);return i}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){const{serverMetadata:t}=await Ze(Hr,this,mi).call(this);Xe(zr,this)||Qe(zr,this,function(e,t){const n=new Cr(e,t),o=async(e,t)=>n.getKey(e,t);return Object.defineProperties(o,{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}}),o}(new URL(t.jwks_uri),{[vr]:Xe(Wr,this).customFetch}));const{payload:n}=await ur(e.logoutToken,Xe(zr,this),{issuer:t.issuer,audience:Xe(Wr,this).clientId,algorithms:["RS256"],requiredClaims:["iat"]});if(!("sid"in n)&&!("sub"in n))throw new Br('either "sid" or "sub" (or both) claims must be present');if("sid"in n&&"string"!=typeof n.sid)throw new Br('"sid" claim must be a string');if("sub"in n&&"string"!=typeof n.sub)throw new Br('"sub" claim must be a string');if("nonce"in n)throw new Br('"nonce" claim is prohibited');if(!("events"in n))throw new Br('"events" claim is missing');if("object"!=typeof n.events||null===n.events)throw new Br('"events" claim must be an object');if(!("http://schemas.openid.net/event/backchannel-logout"in n.events))throw new Br('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');if("object"!=typeof n.events["http://schemas.openid.net/event/backchannel-logout"])throw new Br('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');return{sid:n.sid,sub:n.sub}}});async function mi(){if(Xe(Kr,this)&&Xe(Nr,this))return{configuration:Xe(Kr,this),serverMetadata:Xe(Nr,this)};const e=await Ze(Hr,this,gi).call(this);return Qe(Kr,this,await Wo(new URL("https://".concat(Xe(Wr,this).domain)),Xe(Wr,this).clientId,{use_mtls_endpoint_aliases:Xe(Wr,this).useMtls},e,{[xo]:Xe(Wr,this).customFetch})),Qe(Nr,this,Xe(Kr,this).serverMetadata()),Xe(Kr,this)[xo]=Xe(Wr,this).customFetch||fetch,{configuration:Xe(Kr,this),serverMetadata:Xe(Nr,this)}}async function yi(e){var t,n;const{configuration:o}=await Ze(Hr,this,mi).call(this);if("audience"in e||"resource"in e)throw new qr("audience and resource parameters are not supported for Token Vault exchanges");hi(e.subjectToken);const r=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:null!==(t=e.subjectTokenType)&&void 0!==t?t:"urn:ietf:params:oauth:token-type:access_token",requested_token_type:null!==(n=e.requestedTokenType)&&void 0!==n?n:"http://auth0.com/oauth/token-type/federated-connection-access-token"});e.loginHint&&r.append("login_hint",e.loginHint),e.scope&&r.append("scope",e.scope),pi(r,e.extra);try{const e=await or(o,"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token",r);return ui.fromTokenEndpointResponse(e)}catch(t){throw new qr("Failed to exchange token for connection '".concat(e.connection,"'."),t)}}async function wi(e){const{configuration:t}=await Ze(Hr,this,mi).call(this);hi(e.subjectToken);const 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),pi(n,e.extra);try{const e=await or(t,"urn:ietf:params:oauth:grant-type:token-exchange",n);return ui.fromTokenEndpointResponse(e)}catch(t){throw new qr("Failed to exchange token of type '".concat(e.subjectTokenType,"'").concat(e.audience?" for audience '".concat(e.audience,"'"):"","."),t)}}async function gi(){if(!Xe(Wr,this).clientSecret&&!Xe(Wr,this).clientAssertionSigningKey&&!Xe(Wr,this).useMtls)throw new ei;if(Xe(Wr,this).useMtls)return(e,t,n,o)=>{n.set("client_id",t.client_id)};let e=Xe(Wr,this).clientAssertionSigningKey;return!e||e instanceof CryptoKey||(e=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return wo(e,t,void 0)}(e,Xe(Wr,this).clientAssertionSigningAlg||"RS256")),e?function(e){return Wt(e,void 0)}(e):Co(Xe(Wr,this).clientSecret)}async function vi(e){const{configuration:t}=await Ze(Hr,this,mi).call(this),n=Ct(),o=await function(e){return async function(e){return It(e,"codeVerifier"),bt(await crypto.subtle.digest("SHA-256",wt(e)))}(e)}(n),r=ti(tt(tt({},Xe(Wr,this).authorizationParams),null==e?void 0:e.authorizationParams)),i=new URLSearchParams(tt(tt({scope:li},r),{},{client_id:Xe(Wr,this).clientId,code_challenge:o,code_challenge_method:"S256"}));return{authorizationUrl:null!=e&&e.pushedAuthorizationRequests?await Qo(t,i):await Yo(t,i),codeVerifier:n}}class bi extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,bi.prototype)}static fromPayload(e){let{error:t,error_description:n}=e;return new bi(t,n)}}class _i extends bi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,_i.prototype)}}class ki extends bi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ki.prototype)}}class Si extends bi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Si.prototype)}}class Ei extends bi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Ei.prototype)}}class Ti extends bi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Ti.prototype)}}class Ai{constructor(){let e=arguments.length>0&&void 0!==arguments[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){const 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(){const e=Date.now();for(const[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t)}get size(){return this.contexts.size}}class Pi{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new Ai}setMFAAuthDetails(e,t,n,o){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:o})}async getAuthenticators(e){var t,n;const o=this.contextManager.get(e);if(!(null===(t=null==o?void 0:o.mfaRequirements)||void 0===t?void 0:t.challenge)||0===o.mfaRequirements.challenge.length)throw new _i("invalid_request","challengeType is required and must contain at least one challenge type, please check mfa_required error payload");const r=o.mfaRequirements.challenge.map((e=>e.type));try{return(await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter((e=>!!e.type&&r.includes(e.type)))}catch(e){if(e instanceof oi)throw new _i(null===(n=e.cause)||void 0===n?void 0:n.error,e.message);throw e}}async enroll(e){var t;const n=function(e){const t=Fe[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(n)}catch(e){if(e instanceof ri)throw new ki(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async challenge(e){var t;try{const t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){if(e instanceof ai)throw new Si(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async getEnrollmentFactors(e){const t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new Ti("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&&0!==t.mfaRequirements.enroll.length?t.mfaRequirements.enroll:[]}async verify(e){const t=this.contextManager.get(e.mfaToken);if(!t)throw new Ei("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");const n=function(e){return"otp"in e&&e.otp?"http://auth0.com/oauth/grant-type/mfa-otp":"oobCode"in e&&e.oobCode?"http://auth0.com/oauth/grant-type/mfa-oob":"recoveryCode"in e&&e.recoveryCode?"http://auth0.com/oauth/grant-type/mfa-recovery-code":void 0}(e);if(!n)throw new Ei("invalid_request","Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");const o=t.scope,r=t.audience;try{const t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:o,audience:r,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 g)this.setMFAAuthDetails(e.mfa_token,o,r,e.mfa_requirements);else if(e instanceof Ei)throw new Ei(e.error,e.error_description);throw e}}}class Ri{constructor(e){let t,n;if(this.userCache=(new ye).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)}),"undefined"!=typeof window&&(()=>{if(!S())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===S().subtle)throw new Error("\n 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.\n ")})(),this.lockManager=(Z||(Z=function(){return"undefined"!=typeof navigator&&"function"==typeof(null===(e=navigator.locks)||void 0===e?void 0:e.request)?new F:new G;var e}()),Z),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||"memory",!Le(t))throw new Error('Invalid cache location "'.concat(t,'"'));n=Le(t)()}var o;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?Pe:Re,this.orgHintCookieName=(o=this.options.clientId,"auth0.".concat(o,".organization_hint")),this.isAuthenticatedCookieName=(e=>"auth0.".concat(e,".is.authenticated"))(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const r=e.useCookiesForTransactions?this.cookieStorage:Ie;var i;this.scope=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if("object"!=typeof e)return{default:he(t,e,...o)};let i={default:he(t,...o)};return Object.keys(e).forEach((n=>{const r=e[n];i[n]=he(t,r,...o)})),i}(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new ge(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||l,this.cacheManager=new we(n,n.allKeys?void 0:new je(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new ze(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:"https://".concat(i)),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:"https://".concat(e,"/"):"".concat(t,"/"))(this.options.issuer,this.domainUrl);const a="".concat(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:a},detailedResponse:!0})}));this.myAccountApi=new Je(s,a),this.authJsClient=new fi({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new Pi(this.authJsClient.mfa,this),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new Ce)}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){const t=this.options.auth0Client||u,n=P(t,!0),o=encodeURIComponent(btoa(JSON.stringify(n)));return"".concat(this.domainUrl).concat(e,"&auth0Client=").concat(o)}_authorizeUrl(e){return this._url("/authorize?".concat(R(e)))}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return(e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(O(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],be.includes(e)||(s[e]=i[e])})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(O(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(e.iss,'", found "').concat(t.claims.iss,'"'));if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error('Signature algorithm of "'.concat(t.header.alg,'" is not supported. Expected the ID token to be signed with "RS256".'));if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new 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 new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but was not one of "').concat(t.claims.aud.join(", "),'"'));if(t.claims.aud.length>1){if(!t.claims.azp)throw new 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 new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(e.aud,'", found "').concat(t.claims.azp,'"'))}}else if(t.claims.aud!==e.aud)throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but found "').concat(t.claims.aud,'"'));if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(e.nonce,'", found "').concat(t.claims.nonce,'"'))}if(e.max_age&&!ve(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!ve(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!ve(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(o,") is after expiration time (").concat(r,")"));if(null!=t.claims.nbf&&ve(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(o,") is before ").concat(e))}if(null!=t.claims.auth_time&&ve(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new 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 (".concat(o,") is after last auth at ").concat(r))}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_id,'"'))}else{const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_name,'"'))}}return t})({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r}_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})}async _prepareAuthorizeUrl(e,t,n){var o;const r=T(E()),i=T(E()),a=E(),s=await I(a),c=C(s),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),l=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:pe(t,n.scope,n.audience),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),d=this._authorizeUrl(l);return{nonce:i,code_verifier:a,scope:l.scope,audience:l.audience||"default",redirect_uri:l.redirect_uri,state:r,url:d}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(()=>{const e=window.screenX+(window.innerWidth-400)/2,t=window.screenY+(window.innerHeight-600)/2;return window.open("","auth0:authorize:popup","left=".concat(e,",top=").concat(t,",width=").concat(400,",height=").concat(600,",resizable,scrollbars=yes,status=1"))})(),!t.popup))throw new w;const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const r=await(e=>new Promise(((t,n)=>{let o;const r=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(r),clearTimeout(i),window.removeEventListener("message",o,!1),n(new y(e.popup)))}),1e3),i=setTimeout((()=>{clearInterval(r),n(new m(e.popup)),window.removeEventListener("message",o,!1)}),1e3*(e.timeoutInSeconds||60));o=function(a){if(a.data&&"authorization_response"===a.data.type){if(clearTimeout(i),clearInterval(r),window.removeEventListener("message",o,!1),!1!==e.closePopup&&e.popup.close(),a.data.response.error)return n(d.fromPayload(a.data.response));t(a.data.response)}},window.addEventListener("message",o)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==r.state)throw new d("state_mismatch","Invalid state");const i=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:r.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:i})}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(){var t;const n=Ue(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{openUrl:o,fragment:r,appState:i}=n,a=s(n,["openUrl","fragment","appState"]),c=(null===(t=a.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,u=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:l}=u,d=s(u,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},d),{appState:i,response_type:e.ResponseType.Code}),c&&{organization:c}));const h=r?"".concat(l,"#").concat(r):l;o?await o(h):window.location.assign(h)}async handleRedirectCallback(){const t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.href).split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const n=this.transactionManager.get();if(!n)throw new d("missing_transaction","Invalid state");this.transactionManager.remove();const o=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const 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}})(t.join(""));return n.response_type===e.ResponseType.ConnectCode?this._handleConnectAccountRedirectCallback(o,n):this._handleLoginRedirectCallback(o,n)}async _handleLoginRedirectCallback(t,n){const{code:o,state:r,error:i,error_description:a}=t;if(i)throw new h(i,a||i,r,n.appState);if(!n.code_verifier||n.state&&n.state!==r)throw new d("state_mismatch","Invalid state");const s=n.organization,c=n.nonce,u=n.redirect_uri;return await this._requestToken(Object.assign({audience:n.audience,scope:n.scope,code_verifier:n.code_verifier,grant_type:"authorization_code",code:o},u?{redirect_uri:u}:{}),{nonceIn:c,organization:s}),{appState:n.appState,response_type:e.ResponseType.Code}}async _handleConnectAccountRedirectCallback(t,n){const{connect_code:o,state:r,error:i,error_description:a}=t;if(i)throw new p(i,a||i,n.connection,r,n.appState);if(!o)throw new d("missing_connect_code","Missing connect code");if(!(n.code_verifier&&n.state&&n.auth_session&&n.redirect_uri&&n.state===r))throw new d("state_mismatch","Invalid state");const s=await this.myAccountApi.completeAccount({auth_session:n.auth_session,connect_code:o,redirect_uri:n.redirect_uri,code_verifier:n.code_verifier});return Object.assign(Object.assign({},s),{appState:n.appState,response_type:e.ResponseType.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated")}try{await this.getTokenSilently(e)}catch(e){}}async getTokenSilently(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,n;const o=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:pe(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,(null===(n=e.authorizationParams)||void 0===n?void 0:n.audience)||this.options.authorizationParams.audience)})}),r=await((e,t)=>{let n=xe[t];return n||(n=e().finally((()=>{delete xe[t],n=null})),xe[t]=n),n})((()=>this._getTokenSilently(o)),"".concat(this.options.clientId,"::").concat(o.authorizationParams.audience,"::").concat(o.authorizationParams.scope));return e.detailedResponse?r:null==r?void 0:r.access_token}async _getTokenSilently(e){const{cacheMode:t}=e,n=s(e,["cacheMode"]);if("off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||"default",clientId:this.options.clientId,cacheMode:t});if(e)return e}if("cache-only"===t)return;const o=(r=this.options.clientId,i=n.authorizationParams.audience||"default","".concat("auth0.lock.getTokenSilently",".").concat(r,".").concat(i));var r,i;try{return await this.lockManager.runWithLock(o,5e3,(async()=>{if("off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(n):await this._getTokenFromIFrame(n),{id_token:o,token_type:r,access_token:i,oauthTokenScope:a,expires_in:s}=e;return Object.assign(Object.assign({id_token:o,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:s})}))}catch(e){if(this._isInteractiveError(e)&&"popup"===this.options.interactiveErrorHandler)return await this._handleInteractiveErrorWithPopup(n);throw e}}_isInteractiveError(e){return e instanceof g}async _handleInteractiveErrorWithPopup(e){try{await this.loginWithPopup({authorizationParams:e.authorizationParams});const t=await this._getEntryFromCache({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId});if(!t)throw new d("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&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,o;const r=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:pe(this.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.scope,(null===(o=e.authorizationParams)||void 0===o?void 0:o.audience)||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},c),t),await this.loginWithPopup(r,t),(await this.cacheManager.get(new fe({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){null!==e.clientId?e.clientId=e.clientId||this.options.clientId:delete e.clientId;const t=e.logoutParams||{},{federated:n}=t,o=s(t,["federated"]),r=n?"&federated":"";return this._url("/v2/logout?".concat(R(Object.assign({clientId:e.clientId},o))))+r}async logout(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t;const n=Ue(e),{openUrl:o}=n,r=s(n,["openUrl"]);null===e.clientId?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("@@user@@"),await(null===(t=this.dpop)||void 0===t?void 0:t.clear());const i=this._buildLogoutUrl(r);o?await o(i):!1!==o&&window.location.assign(i)}async _getTokenFromIFrame(e){const t=(n=this.options.clientId,"".concat("auth0.lock.getTokenFromIFrame",".").concat(n));var n;try{return await this.lockManager.runWithLock(t,5e3,(async()=>{const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:r,nonce:i,code_verifier:a,redirect_uri:s,scope:c,audience:u}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new d("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const l=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let h;try{h=new URL(this.domainUrl).origin}catch(e){h=this.domainUrl}const p=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;return new Promise(((o,r)=>{const i=window.document.createElement("iframe");i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.display="none";const a=()=>{window.document.body.contains(i)&&(window.document.body.removeChild(i),window.removeEventListener("message",s,!1))};let s;const c=setTimeout((()=>{r(new f),a()}),1e3*n);s=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?r(d.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",s,!1),setTimeout(a,2e3)},window.addEventListener("message",s,!1),window.document.body.appendChild(i),i.setAttribute("src",e)}))}(o,h,l);if(r!==p.state)throw new d("state_mismatch","Invalid state");const m=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:a,code:p.code,grant_type:"authorization_code",redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:i,organization:t.organization});return Object.assign(Object.assign({},m),{scope:c,oauthTokenScope:m.scope,audience:u})}))}catch(e){throw"login_required"===e.error&&this.logout({openUrl:!1}),e}}async _getTokenUsingRefreshToken(e){var t,n;const o=await this.cacheManager.get(new fe({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(o&&o.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new v(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const r=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null,a=((e,t,n,o)=>{var r;if(e&&n&&o){if(t.audience!==n)return t.scope;const e=o.split(" "),i=(null===(r=t.scope)||void 0===r?void 0:r.split(" "))||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?o:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,null==o?void 0:o.audience,null==o?void 0:o.scope);try{const t=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:o&&o.refresh_token,redirect_uri:r}),i&&{timeout:i}),{scopesToRequest:a});if(t.refresh_token&&(null==o?void 0:o.refresh_token)&&await this.cacheManager.updateEntry(o.refresh_token,t.refresh_token),this.options.useMrrt&&!(s=null==o?void 0:o.audience,c=null==o?void 0:o.scope,u=e.authorizationParams.audience,l=e.authorizationParams.scope,s===u&&Ke(l,c)||Ke(a,t.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const n=((e,t)=>{const n=(null==e?void 0:e.split(" "))||[],o=(null==t?void 0:t.split(" "))||[];return n.filter((e=>-1==o.indexOf(e))).join(",")})(a,t.scope);throw new b(e.authorizationParams.audience||"default",n)}return Object.assign(Object.assign({},t),{scope:e.authorizationParams.scope,oauthTokenScope:t.scope,audience:e.authorizationParams.audience||"default"})}catch(o){if(o.message){if(o.message.includes("user is blocked"))throw await this.logout({openUrl:!1}),o;if((o.message.includes("Missing Refresh Token")||o.message.includes("invalid refresh token"))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw o instanceof g&&this.mfa.setMFAAuthDetails(o.mfa_token,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.audience,o.mfa_requirements),o}var s,c,u,l}async _saveEntryInCache(e){const{id_token:t,decodedToken:n}=e,o=s(e,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:t,decodedToken:n}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(o)}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=this.scope[e],n=await this.cacheManager.getIdToken(new fe({clientId:this.options.clientId,audience:e,scope:t})),o=this.userCache.get("@@user@@");return n&&n.id_token===(null==o?void 0:o.id_token)?o:(this.userCache.set("@@user@@",n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:o,cacheMode:r}=e;const i=await this.cacheManager.get(new fe({scope:t,audience:n,clientId:o}),60,this.options.useMrrt,r);if(i&&i.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:o}=i,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:o})}}async _requestToken(e,t){var n,o;const{nonceIn:r,organization:i,scopesToRequest:a}=t||{},s=await de(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),c=await this._verifyIdToken(s.id_token,r,i);if("authorization_code"===e.grant_type){const e=await this._getIdTokenFromCache();(null===(o=null===(n=null==e?void 0:e.decodedToken)||void 0===n?void 0:n.claims)||void 0===o?void 0:o.sub)&&e.decodedToken.claims.sub!==c.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove("@@user@@"))}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},s),{decodedToken:c,scope:e.scope,audience:e.audience||"default"}),s.scope?{oauthTokenScope:s.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||c.claims.org_id),Object.assign(Object.assign({},s),{decodedToken:c})}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:pe(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 new 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&&void 0!==arguments[0]?arguments[0]:{};return new Me(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>{var t;return this.getTokenSilently({authorizationParams:{scope:null===(t=null==e?void 0:e.scope)||void 0===t?void 0:t.join(" "),audience:null==e?void 0:e.audience},detailedResponse:!0})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(t){const{openUrl:n,appState:o,connection:r,scopes:i,authorization_params:a,redirectUri:s=this.options.authorizationParams.redirect_uri||window.location.origin}=t;if(!r)throw new Error("connection is required");const c=T(E()),u=E(),l=await I(u),d=C(l),{connect_uri:h,connect_params:p,auth_session:f}=await this.myAccountApi.connectAccount({connection:r,scopes:i,redirect_uri:s,state:c,code_challenge:d,code_challenge_method:"S256",authorization_params:a});this.transactionManager.create({state:c,code_verifier:u,auth_session:f,redirect_uri:s,appState:o,connection:r,response_type:e.ResponseType.ConnectCode});const m=new URL(h);m.searchParams.set("ticket",p.ticket),n?await n(m.toString()):window.location.assign(m)}async _requestTokenForMfa(e,t){const{mfaToken:n}=e,o=s(e,["mfaToken"]);return this._requestToken(Object.assign(Object.assign({},o),{mfa_token:n}),t)}}var Ii={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},Oi=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},Ci=o(o({},Ii),{buildAuthorizeUrl:Oi,buildLogoutUrl:Oi,getAccessTokenSilently:Oi,getAccessTokenWithPopup:Oi,getIdTokenClaims:Oi,loginWithCustomTokenExchange:Oi,exchangeToken:Oi,loginWithRedirect:Oi,loginWithPopup:Oi,connectAccountWithRedirect:Oi,logout:Oi,handleRedirectCallback:Oi,getDpopNonce:Oi,setDpopNonce:Oi,generateDpopProof:Oi,createFetcher:Oi,getConfiguration:Oi,mfa:{getAuthenticators:Oi,enroll:Oi,challenge:Oi,verify:Oi,getEnrollmentFactors:Oi}}),xi=t.createContext(Ci),ji=function(e){function t(n,o){var r=e.call(this,null!=o?o:n)||this;return r.error=n,r.error_description=o,Object.setPrototypeOf(r,t.prototype),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}(t,e),t}(Error),Di=/[?&](?:connect_)?code=[^&]+/,Li=/[?&]state=[^&]+/,Ui=/[?&]error=[^&]+/,Ki=function(e){return function(t){if(t instanceof Error)return t;if(null!==t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error){if("error_description"in t&&"string"==typeof t.error_description){var n=t;return new ji(n.error,n.error_description)}return new ji(t.error)}return new Error(e)}},Ni=Ki("Login failed"),Wi=Ki("Get access token failed"),zi=function(e){var t,n;(null==e?void 0: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=null!==(t=e.authorizationParams)&&void 0!==t?t:{},e.authorizationParams.redirect_uri=e.redirectUri,delete e.redirectUri),(null===(n=null==e?void 0:e.authorizationParams)||void 0===n?void 0:n.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)},Hi=function(e,t){switch(t.type){case"LOGIN_POPUP_STARTED":return o(o({},e),{isLoading:!0});case"LOGIN_POPUP_COMPLETE":case"INITIALISED":return o(o({},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:o(o({},e),{isAuthenticated:!!t.user,user:t.user});case"LOGOUT":return o(o({},e),{isAuthenticated:!1,user:void 0});case"ERROR":return o(o({},e),{isLoading:!1,error:t.error})}},Mi=function(e){var t;window.history.replaceState({},document.title,null!==(t=e.returnTo)&&void 0!==t?t:window.location.pathname)},Ji=function(e){return void 0===e&&(e=xi),t.useContext(e)},Vi=function(){return t.createElement(t.Fragment,null)},Fi=function(){return i(void 0,void 0,void 0,(function(){return a(this,(function(e){return[2]}))}))},Gi=function(){return"".concat(window.location.pathname).concat(window.location.search)};e.Auth0Context=xi,e.Auth0Provider=function(n){var s=n.children,c=n.skipRedirectCallback,u=n.onRedirectCallback,l=void 0===u?Mi:u,d=n.context,h=void 0===d?xi:d,p=r(n,["children","skipRedirectCallback","onRedirectCallback","context"]),f=t.useState((function(){return new Ri(function(e){return zi(e),o(o({},e),{auth0Client:{name:"auth0-react",version:"2.15.0"}})}(p))}))[0],m=t.useReducer(Hi,Ii),y=m[0],w=m[1],g=t.useRef(!1),v=t.useCallback((function(e){return w({type:"ERROR",error:e}),e}),[]);t.useEffect((function(){g.current||(g.current=!0,i(void 0,void 0,void 0,(function(){var t,n,o,i,s,u,d;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,7,,8]),t=void 0,void 0===h&&(h=window.location.search),!Di.test(h)&&!Ui.test(h)||!Li.test(h)||c?[3,3]:[4,f.handleRedirectCallback()];case 1:return n=a.sent(),o=n.appState,i=void 0===o?{}:o,s=n.response_type,u=r(n,["appState","response_type"]),[4,f.getUser()];case 2:return t=a.sent(),i.response_type=s,s===e.ResponseType.ConnectCode&&(i.connectedAccount=u),l(i,t),[3,6];case 3:return[4,f.checkSession()];case 4:return a.sent(),[4,f.getUser()];case 5:t=a.sent(),a.label=6;case 6:return w({type:"INITIALISED",user:t}),[3,8];case 7:return d=a.sent(),v(Ni(d)),[3,8];case 8:return[2]}var h}))})))}),[f,l,c,v]);var b=t.useCallback((function(e){return zi(e),f.loginWithRedirect(e)}),[f]),_=t.useCallback((function(e,t){return i(void 0,void 0,void 0,(function(){var n,o;return a(this,(function(r){switch(r.label){case 0:w({type:"LOGIN_POPUP_STARTED"}),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,f.loginWithPopup(e,t)];case 2:return r.sent(),[3,4];case 3:return n=r.sent(),v(Ni(n)),[2];case 4:return[4,f.getUser()];case 5:return o=r.sent(),w({type:"LOGIN_POPUP_COMPLETE",user:o}),[2]}}))}))}),[f,v]),k=t.useCallback((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i(void 0,function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0),void 0,(function(e){return void 0===e&&(e={}),a(this,(function(t){switch(t.label){case 0:return[4,f.logout(e)];case 1:return t.sent(),(e.openUrl||!1===e.openUrl)&&w({type:"LOGOUT"}),[2]}}))}))}),[f]),S=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o,r;return a(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,f.getTokenSilently(e)];case 1:return t=i.sent(),[3,5];case 2:throw n=i.sent(),Wi(n);case 3:return o=w,r={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,f.getUser()];case 4:return o.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2,t]}}))}))}),[f]),E=t.useCallback((function(e,t){return i(void 0,void 0,void 0,(function(){var n,o,r,i;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,f.getTokenWithPopup(e,t)];case 1:return n=a.sent(),[3,5];case 2:throw o=a.sent(),Wi(o);case 3:return r=w,i={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,f.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,n]}}))}))}),[f]),T=t.useCallback((function(e){return f.connectAccountWithRedirect(e)}),[f]),A=t.useCallback((function(){return f.getIdTokenClaims()}),[f]),P=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o,r;return a(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,f.loginWithCustomTokenExchange(e)];case 1:return t=i.sent(),[3,5];case 2:throw n=i.sent(),Wi(n);case 3:return o=w,r={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,f.getUser()];case 4:return o.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2,t]}}))}))}),[f]),R=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){return a(this,(function(t){return[2,P(e)]}))}))}),[P]),I=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o;return a(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,3,5]),[4,f.handleRedirectCallback(e)];case 1:return[2,r.sent()];case 2:throw t=r.sent(),Wi(t);case 3:return n=w,o={type:"HANDLE_REDIRECT_COMPLETE"},[4,f.getUser()];case 4:return n.apply(void 0,[(o.user=r.sent(),o)]),[7];case 5:return[2]}}))}))}),[f]),O=t.useCallback((function(e){return f.getDpopNonce(e)}),[f]),C=t.useCallback((function(e,t){return f.setDpopNonce(e,t)}),[f]),x=t.useCallback((function(e){return f.generateDpopProof(e)}),[f]),j=t.useCallback((function(e){return f.createFetcher(e)}),[f]),D=t.useCallback((function(){return f.getConfiguration()}),[f]),L=t.useMemo((function(){return f.mfa}),[f]),U=t.useMemo((function(){return o(o({},y),{getAccessTokenSilently:S,getAccessTokenWithPopup:E,getIdTokenClaims:A,loginWithCustomTokenExchange:P,exchangeToken:R,loginWithRedirect:b,loginWithPopup:_,connectAccountWithRedirect:T,logout:k,handleRedirectCallback:I,getDpopNonce:O,setDpopNonce:C,generateDpopProof:x,createFetcher:j,getConfiguration:D,mfa:L})}),[y,S,E,A,P,R,b,_,T,k,I,O,C,x,j,D,L]);return t.createElement(h.Provider,{value:U},s)},e.AuthenticationError=h,e.ConnectError=p,e.GenericError=d,e.InMemoryCache=ye,e.LocalStorageCache=me,e.MfaChallengeError=Si,e.MfaEnrollmentError=ki,e.MfaEnrollmentFactorsError=Ti,e.MfaError=bi,e.MfaListAuthenticatorsError=_i,e.MfaRequiredError=g,e.MfaVerifyError=Ei,e.MissingRefreshTokenError=v,e.OAuthError=ji,e.PopupCancelledError=y,e.PopupOpenError=w,e.PopupTimeoutError=m,e.TimeoutError=f,e.UseDpopNonceError=_,e.User=class{},e.initialContext=Ci,e.useAuth0=Ji,e.withAuth0=function(e,n){return void 0===n&&(n=xi),function(r){return t.createElement(n.Consumer,null,(function(n){return t.createElement(e,o({},r,{auth0:n}))}))}},e.withAuthenticationRequired=function(e,n){return void 0===n&&(n={}),function(r){var s=this,c=n.returnTo,u=void 0===c?Gi:c,l=n.onRedirecting,d=void 0===l?Vi:l,h=n.onBeforeAuthentication,p=void 0===h?Fi:h,f=n.loginOptions,m=n.context,y=Ji(void 0===m?xi:m),w=y.isAuthenticated,g=y.isLoading,v=y.loginWithRedirect;return t.useEffect((function(){if(!g&&!w){var e=o(o({},f),{appState:o(o({},null==f?void 0:f.appState),{returnTo:"function"==typeof u?u():u})});i(s,void 0,void 0,(function(){return a(this,(function(t){switch(t.label){case 0:return[4,p()];case 1:return t.sent(),[4,v(e)];case 2:return t.sent(),[2]}}))}))}}),[g,w,v,p,f,u]),w?t.createElement(e,o({},r)):d()}}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).reactAuth0={},e.React)}(this,(function(e,t){"use strict";var n=function(e,t){return n=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])},n(e,t)};var o=function(){return o=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)};function r(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function i(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((o=o.apply(e,t||[])).next())}))}function a(e,t){var n,o,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){i.label=s[1];break}if(6===s[0]&&i.label<r[1]){i.label=r[1],r=s;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(s);break}r[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],o=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function s(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}"function"==typeof SuppressedError&&SuppressedError,"function"==typeof SuppressedError&&SuppressedError;const c={timeoutInSeconds:60},u="memory",l={name:"auth0-spa-js",version:"2.18.0"},d=()=>Date.now(),h="default";class p extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,p.prototype)}static fromPayload(e){let{error:t,error_description:n}=e;return new p(t,n)}}class f extends p{constructor(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,f.prototype)}}class m extends p{constructor(e,t,n,o){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;super(e,t),this.connection=n,this.state=o,this.appState=r,Object.setPrototypeOf(this,m.prototype)}}class y extends p{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,y.prototype)}}class w extends y{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,w.prototype)}}class g extends p{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,g.prototype)}}class v extends p{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,v.prototype)}}class b extends p{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,b.prototype)}}class _ extends p{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(T(e,["default"]),"', scope: '").concat(T(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,_.prototype)}}class k extends p{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(T(e,["default"]),"', missing scope: '").concat(T(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,k.prototype)}}class S extends p{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,S.prototype)}}function T(e){return e&&!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).includes(e)?e:""}const E=()=>window.crypto,P=()=>{let e="";for(;e.length<43;){const t=E().getRandomValues(new Uint8Array(43-e.length));for(const n of t)e.length<43&&n<198&&(e+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~."[n%66])}return e},A=e=>btoa(e),O=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],R=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object.keys(e).reduce(((n,o)=>{if(t&&"env"===o)return n;const r=O.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},C=e=>{var{clientId:t}=e,n=s(e,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:t},n))).toString()},I=async e=>{const t=E().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},x=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),j=e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))};var D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},U={},W={};Object.defineProperty(W,"__esModule",{value:!0});var K=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();W.default=function(){return K.getInstance()};var L=D&&D.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){e.done?r(e.value):new n((function(t){t(e.value)})).then(a,s)}c((o=o.apply(e,t||[])).next())}))},M=D&&D.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},N=D;Object.defineProperty(U,"__esModule",{value:!0});var z=W,H="browser-tabs-lock-key",J={key:function(e){return L(N,void 0,void 0,(function(){return M(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return L(N,void 0,void 0,(function(){return M(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return L(N,void 0,void 0,(function(){return M(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return L(N,void 0,void 0,(function(){return M(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return L(N,void 0,void 0,(function(){return M(this,(function(e){throw new 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 Z(e){return new Promise((function(t){return setTimeout(t,e)}))}function F(e){for(var t="",n=0;n<e;n++)t+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"[Math.floor(61*Math.random())];return t}var V=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+F(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),L(this,void 0,void 0,(function(){var o,r,i,a,s,c,u;return M(this,(function(l){switch(l.label){case 0:o=Date.now()+F(4),r=Date.now()+n,i=H+"-"+t,a=void 0===this.storageHandler?J:this.storageHandler,l.label=1;case 1:return Date.now()<r?[4,Z(30)]:[3,8];case 2:return l.sent(),null!==a.getItemSync(i)?[3,5]:(s=this.id+"-"+t+"-"+o,[4,Z(Math.floor(25*Math.random()))]);case 3:return l.sent(),a.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,Z(30)];case 4:return l.sent(),null!==(c=a.getItemSync(i))&&(u=JSON.parse(c)).id===this.id&&u.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?J:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:l.sent(),l.label=7;case 7:return o=Date.now()+F(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return L(this,void 0,void 0,(function(){var n=this;return M(this,(function(o){return setTimeout((function(){return L(n,void 0,void 0,(function(){var n,o,r;return M(this,(function(i){switch(i.label){case 0:return[4,z.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?J:this.storageHandler,null===(o=n.getItemSync(e))?(z.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),z.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(z.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return L(this,void 0,void 0,(function(){return M(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){var o=!1,r=Date.now(),i=!1;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=!0),!o){o=!0;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return L(this,void 0,void 0,(function(){return M(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 L(this,void 0,void 0,(function(){var n,o,r,i;return M(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?J:this.storageHandler,o=H+"-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,z.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),z.default().unlock(i.iat),e.notifyWaiters(),a.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],i=0;;){var a=o.keySync(i);if(null===a)break;r.push(a),i++}for(var s=!1,c=0;c<r.length;c++){var u=r[c];if(u.includes(H)){var l=o.getItemSync(u);if(null!==l){var d=JSON.parse(l);(void 0===d.timeRefreshed&&d.timeAcquired<n||void 0!==d.timeRefreshed&&d.timeRefreshed<n)&&(o.removeItemSync(u),s=!0)}}}s&&e.notifyWaiters()},e.waiters=void 0,e}(),q=U.default=V;class G{async runWithLock(e,t,n){const o=new AbortController,r=setTimeout((()=>o.abort()),t);try{return await navigator.locks.request(e,{mode:"exclusive",signal:o.signal},(async e=>{if(clearTimeout(r),!e)throw new Error("Lock not available");return await n()}))}catch(e){if(clearTimeout(r),"AbortError"===(null==e?void 0:e.name))throw new y;throw e}}}class X{constructor(){this.activeLocks=new Set,this.lock=new q,this.pagehideHandler=()=>{this.activeLocks.forEach((e=>this.lock.releaseLock(e))),this.activeLocks.clear()}}async runWithLock(e,t,n){let o=!1;for(let n=0;n<10&&!o;n++)o=await this.lock.acquireLock(e,t);if(!o)throw new y;this.activeLocks.add(e),1===this.activeLocks.size&&"undefined"!=typeof window&&window.addEventListener("pagehide",this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),0===this.activeLocks.size&&"undefined"!=typeof window&&window.removeEventListener("pagehide",this.pagehideHandler)}}}let B=null;const Y=new TextEncoder,Q=new TextDecoder;function $(e){return"string"==typeof e?Y.encode(e):Q.decode(e)}function ee(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new re(`${e.name} modulusLength must be at least 2048 bits`)}let te;if(Uint8Array.prototype.toBase64)te=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;te=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}function ne(e){return te(e)}class oe extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class re extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}function ie(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return"PS256";throw new oe("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return"RS256";throw new oe("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return"ES256";throw new oe("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return"Ed25519";default:throw new oe("unsupported CryptoKey algorithm name")}}function ae(e){return e instanceof CryptoKey}function se(e){return ae(e)&&"public"===e.type}async function ce(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!ae(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!se(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(!0!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw new TypeError('"additional" must be an object');return async function(e,t,n){if(!1===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${ne($(JSON.stringify(e)))}.${ne($(JSON.stringify(t)))}`;return`${o}.${ne(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return ee(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return ee(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new oe}(n),n,$(o)))}`}({alg:ie(a),typ:"dpop+jwt",jwk:await ue(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?ne(await crypto.subtle.digest("SHA-256",$(r))):void 0}),a)}async function ue(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:a,e:n,n:o,x:r,y:i}}const le="dpop-nonce",de=["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"];const he=async(e,t)=>{const n=await fetch(e,t);return{ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,t)=>{let[n,o]=t;return e[n]=o,e}),{}))};var o},pe=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4;return r?(async(e,t,n,o,r,i,a,s)=>((e,t)=>new Promise((function(n,o){const r=new MessageChannel;r.port1.onmessage=function(e){e.data.error?o(new Error(e.data.error)):n(e.data),r.port1.close()},t.postMessage(e,[r.port2])})))({auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a,useMrrt:s},i))(e,t,n,o,a,r,i,arguments.length>7?arguments[7]:void 0):(async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([he(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"))}),n)}))]).finally((()=>{clearTimeout(r)}))})(e,o,a)};async function fe(e,t,n,o,r,i,a,c,u,l){if(u){const t=await u.generateProof({url:e,method:r.method||"GET",nonce:await u.getNonce()});r.headers=Object.assign(Object.assign({},r.headers),{dpop:t})}let d,h=null;for(let s=0;s<3;s++)try{d=await pe(e,n,o,r,i,a,t,c),h=null;break}catch(e){h=e}if(h)throw h;const f=d.json,{error:m,error_description:y}=f,w=s(f,["error","error_description"]),{headers:g,ok:v}=d;let k;if(u&&(k=g[le],k&&await u.setNonce(k)),!v){const s=y||"HTTP error. Unable to fetch ".concat(e);if("mfa_required"===m)throw new b(m,s,w.mfa_token,w.mfa_requirements);if("missing_refresh_token"===m)throw new _(n,o);if("use_dpop_nonce"===m){if(!u||!k||l)throw new S(k);return fe(e,t,n,o,r,i,a,c,u,!0)}throw new p(m||"request_error",s)}return w}async function me(e,t){var{baseUrl:n,timeout:o,audience:r,scope:i,auth0Client:a,useFormData:c,useMrrt:u,dpop:d}=e,p=s(e,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const f="urn:ietf:params:oauth:grant-type:token-exchange"===p.grant_type,m="refresh_token"===p.grant_type&&u,y=Object.assign(Object.assign(Object.assign(Object.assign({},p),f&&r&&{audience:r}),f&&i&&{scope:i}),m&&{audience:r,scope:i}),w=c?C(y):JSON.stringify(y),g=(v=p.grant_type,de.includes(v));var v;return await fe("".concat(n,"/oauth/token"),o,r||h,i,{method:"POST",body:w,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(R(a||l)))}},t,c,u,g?d:void 0)}const ye=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(o=t.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(o))).join(" ");var o},we=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e[h]),ye(o,t)},ge="@@auth0spajs@@",ve="@@user@@";class be{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ge,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(e){const[t,n,o,r]=e.split("::");return new be({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new be({scope:t,audience:n,clientId:o})}}class _e{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith(ge)))}}class ke{constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){const n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}}class Se{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||d}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r))}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return{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&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3?arguments[3]:void 0;var r;let i=await this.cache.get(e.toKey());if(!i){const t=await this.getCacheKeys();if(!t)return;const r=this.matchExistingCacheKey(e,t);if(r&&(i=await this.cache.get(r)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!i)return;const a=await this.nowProvider(),s=Math.floor(a/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await(null===(r=this.keyManifest)||void 0===r?void 0:r.remove(e.toKey()))):i.body}async modifiedCachedEntry(e,t){return e.body={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},await this.cache.set(t.toKey(),e),{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}async set(e){var t;const n=new be({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()))}async remove(e,t,n){const o=new be({clientId:e,scope:n,audience:t});await this.cache.remove(o.toKey())}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t)}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()))}async wrapCacheEntry(e){const t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new be({clientId:e},ge,ve).toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=be.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),!0);return o.prefix===ge&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=be.fromKey(o);if(t.prefix===ge&&t.clientId===e.clientId){const t=await this.cache.get(o);if(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){var n;const o=await this.getCacheKeys();if(o)for(const r of o){const o=await this.cache.get(r);(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e&&(o.body.refresh_token=t,await this.cache.set(r,o))}}}class Te{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey="".concat("a0.spajs.txs",".").concat(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})}}const Ee=e=>"number"==typeof e,Pe=["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"];var Ae=D&&D.__assign||function(){return Ae=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Ae.apply(this,arguments)};function Oe(e,t){if(!t)return"";var n="; "+e;return!0===t?n:n+"="+t}var Re=function(e){return function(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent)}catch(e){}}return t}(document.cookie)[e]};function Ce(e,t,n){document.cookie=function(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("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return Oe("Expires",e.expires?e.expires.toUTCString():"")+Oe("Domain",e.domain)+Oe("Path",e.path)+Oe("Secure",e.secure)+Oe("SameSite",e.sameSite)}(n)}(e,t,Ae({path:"/"},n))}var Ie=Ce,xe=function(e,t){Ce(e,"",Ae(Ae({},t),{expires:-1}))};const je={get(e){const t=Re(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie(e,JSON.stringify(t),o)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n)}},De="_legacy_",Ue={get:e=>je.get(e)||je.get("".concat(De).concat(e)),save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie("".concat(De).concat(e),JSON.stringify(t),o),je.save(e,t,n)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n),je.remove(e,t),je.remove("".concat(De).concat(e),t)}},We={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}};e.ResponseType=void 0,function(e){e.Code="code",e.ConnectCode="connect_code"}(e.ResponseType||(e.ResponseType={}));var Ke,Le=function(e){return Ke=Ke||function(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtyZXR1cm4gZSYmIShhcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W10pLmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIodD0+dm9pZCAwIT09ZVt0XSkucmVkdWNlKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkse30pKShPYmplY3QuYXNzaWduKHtjbGllbnRfaWQ6dH0scikpKS50b1N0cmluZygpfTtsZXQgbz17fTtjb25zdCBuPShlLHQpPT4iIi5jb25jYXQoZSwifCIpLmNvbmNhdCh0KTthZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixhc3luYyBlPT57bGV0IHIsYyx7ZGF0YTp7dGltZW91dDppLGF1dGg6YSxmZXRjaFVybDpmLGZldGNoT3B0aW9uczpsLHVzZUZvcm1EYXRhOnAsdXNlTXJydDpofSxwb3J0czpbdV19PWUsZD17fTtjb25zdHthdWRpZW5jZTpnLHNjb3BlOnl9PWF8fHt9O3RyeXtjb25zdCBlPXA/KGU9Pntjb25zdCB0PW5ldyBVUkxTZWFyY2hQYXJhbXMoZSkscj17fTtyZXR1cm4gdC5mb3JFYWNoKChlLHQpPT57clt0XT1lfSkscn0pKGwuYm9keSk6SlNPTi5wYXJzZShsLmJvZHkpO2lmKCFlLnJlZnJlc2hfdG9rZW4mJiJyZWZyZXNoX3Rva2VuIj09PWUuZ3JhbnRfdHlwZSl7aWYoYz0oKGUsdCk9Pm9bbihlLHQpXSkoZyx5KSwhYyYmaCl7Y29uc3QgZT1vLmxhdGVzdF9yZWZyZXNoX3Rva2VuLHQ9KChlLHQpPT57Y29uc3Qgcj1PYmplY3Qua2V5cyhvKS5maW5kKHI9PntpZigibGF0ZXN0X3JlZnJlc2hfdG9rZW4iIT09cil7Y29uc3Qgcz0oKGUsdCk9PnQuc3RhcnRzV2l0aCgiIi5jb25jYXQoZSwifCIpKSkodCxyKSxvPXIuc3BsaXQoInwiKVsxXS5zcGxpdCgiICIpLG49ZS5zcGxpdCgiICIpLmV2ZXJ5KGU9Pm8uaW5jbHVkZXMoZSkpO3JldHVybiBzJiZufX0pO3JldHVybiEhcn0pKHksZyk7ZSYmIXQmJihjPWUpfWlmKCFjKXRocm93IG5ldyB0KGcseSk7bC5ib2R5PXA/cyhPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sZSkse3JlZnJlc2hfdG9rZW46Y30pKTpKU09OLnN0cmluZ2lmeShPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sZSkse3JlZnJlc2hfdG9rZW46Y30pKX1sZXQgYSxrOyJmdW5jdGlvbiI9PXR5cGVvZiBBYm9ydENvbnRyb2xsZXImJihhPW5ldyBBYm9ydENvbnRyb2xsZXIsbC5zaWduYWw9YS5zaWduYWwpO3RyeXtrPWF3YWl0IFByb21pc2UucmFjZShbKGo9aSxuZXcgUHJvbWlzZShlPT5zZXRUaW1lb3V0KGUsaikpKSxmZXRjaChmLE9iamVjdC5hc3NpZ24oe30sbCkpXSl9Y2F0Y2goZSl7cmV0dXJuIHZvaWQgdS5wb3N0TWVzc2FnZSh7ZXJyb3I6ZS5tZXNzYWdlfSl9aWYoIWspcmV0dXJuIGEmJmEuYWJvcnQoKSx2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOiJUaW1lb3V0IHdoZW4gZXhlY3V0aW5nICdmZXRjaCcifSk7Xz1rLmhlYWRlcnMsZD1bLi4uX10ucmVkdWNlKChlLHQpPT57bGV0W3Isc109dDtyZXR1cm4gZVtyXT1zLGV9LHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKGU9PntsZXRbdCxyXT1lO3I9PT1PJiYob1t0XT1iKX0pKSwoKGUsdCxyKT0+e29bbih0LHIpXT1lfSkoci5yZWZyZXNoX3Rva2VuLGcseSksZGVsZXRlIHIucmVmcmVzaF90b2tlbik6KChlLHQpPT57ZGVsZXRlIG9bbihlLHQpXX0pKGcseSksdS5wb3N0TWVzc2FnZSh7b2s6ay5vayxqc29uOnIsaGVhZGVyczpkfSl9Y2F0Y2goZSl7dS5wb3N0TWVzc2FnZSh7b2s6ITEsanNvbjp7ZXJyb3I6ZS5lcnJvcixlcnJvcl9kZXNjcmlwdGlvbjplLm1lc3NhZ2V9LGhlYWRlcnM6ZH0pfXZhciBPLGIsXyxqfSl9KCk7Cgo=",null,false),new Worker(Ke,e)};const Me={};class Ne{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]})}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const 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"".concat(ge,"::").concat(e)}}const ze="auth0.is.authenticated",He={memory:()=>(new ke).enclosedCache,localstorage:()=>new _e},Je=e=>He[e],Ze=e=>{const{openUrl:t,onRedirect:n}=e,o=s(e,["openUrl","onRedirect"]);return Object.assign(Object.assign({},o),{openUrl:!1===t||t?t:n})},Fe=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},Ve={NONCE:"nonce",KEYPAIR:"keypair"};class qe{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(Ve).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)}))}buildKey(e){const t=e?"_".concat(e):"auth0";return"".concat(this.clientId,"::").concat(t)}setNonce(e,t){return this.save(Ve.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Ve.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)))}findNonce(e){return this.find(Ve.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Ve.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))))}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith("".concat(t,"::"))))}clearNonces(){return this.deleteByClientId(Ve.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Ve.KEYPAIR,this.clientId)}}class Ge{constructor(e){this.storage=new qe(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 async function(e,t){var n;let o;return o={name:"ECDSA",namedCurve:"P-256"},crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}(0,{extractable:!1}),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return function(e){let{keyPair:t,url:n,method:o,nonce:r,accessToken:i}=e;const a=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(n);return ce(t,a,o,r,i)}(Object.assign({keyPair:t},e))}async calculateThumbprint(){return function(e){return async function(e){if(!se(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(!0!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await ue(e);let 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 oe("unsupported JWK kty")}return ne(await crypto.subtle.digest({name:"SHA-256"},$(JSON.stringify(n))))}(e.publicKey)}(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}var Xe;!function(e){e.Bearer="Bearer",e.DPoP="DPoP"}(Xe||(Xe={}));class Be{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?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"".concat(e.replace(/\/?\/$/,""),"/").concat(t.replace(/^\/+/,""))}throw new 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"string"==typeof e?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),o=e instanceof Request?new Request(n,e):n;return new Request(o,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Xe.Bearer;e.headers.set("authorization","".concat(n," ").concat(t))}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o)}async prepareRequest(e,t){const n=await this.getAccessToken(t);let o,r;"string"==typeof n?(o=this.config.dpopNonceId?Xe.DPoP:Xe.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===Xe.DPoP&&await this.setDpopProofHeader(e,r)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return!1;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,le);if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new S(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,o);const i=await this.config.fetch(r);return this.handleResponse(i,n)}fetchWithAuth(e,t,n){const o={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},o),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,o,n)}}class Ye{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/connect"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(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 Qe({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new Qe(t)}}class Qe extends Error{constructor(e){let{type:t,status:n,title:o,detail:r,validation_errors:i}=e;super(r),this.name="MyAccountApiError",this.type=t,this.status=n,this.title=o,this.detail=r,this.validation_errors=i,Object.setPrototypeOf(this,Qe.prototype)}}const $e={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}};function et(e,t){this.v=e,this.k=t}function tt(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function nt(e){return new et(e,0)}function ot(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function rt(e,t){return e.get(tt(e,t))}function it(e,t,n){ot(e,t),t.set(e,n)}function at(e,t,n){return e.set(tt(e,t),n),n}function st(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ct(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function ut(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ct(Object(n),!0).forEach((function(t){st(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ct(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function lt(e,t){if(null==e)return{};var n,o,r=function(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function dt(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof et;Promise.resolve(s?a.v:a).then((function(n){if(s){var c="return"===t&&a.k?t:"next";if(!a.k||n.done)return o(c,n);n=e[c](n).value}r(!!i.done,n)}),(function(e){o("throw",e)}))}catch(e){r(2,e)}}function r(e,r){2===e?t.reject(r):t.resolve({value:r,done:e}),(t=t.next)?o(t.key,t.arg):n=null}this._invoke=function(e,r){return new Promise((function(i,a){var s={key:e,arg:r,resolve:i,reject:a,next:null};n?n=n.next=s:(t=n=s,o(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}var ht,pt;let ft;if(dt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},dt.prototype.next=function(e){return this._invoke("next",e)},dt.prototype.throw=function(e){return this._invoke("throw",e)},dt.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(ht=navigator.userAgent)||void 0===ht||null===(pt=ht.startsWith)||void 0===pt||!pt.call(ht,"Mozilla/5.0 ")){const e="v3.8.5";ft="".concat("oauth4webapi","/").concat(e)}function mt(e,t){if(null==e)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch(e){return!1}}const yt="ERR_INVALID_ARG_VALUE",wt="ERR_INVALID_ARG_TYPE";function gt(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const vt=Symbol(),bt=Symbol(),_t=Symbol(),kt=Symbol(),St=Symbol(),Tt=Symbol(),Et=new TextEncoder,Pt=new TextDecoder;function At(e){return"string"==typeof e?Et.encode(e):Pt.decode(e)}let Ot,Rt;if(Uint8Array.prototype.toBase64)Ot=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;Ot=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}function Ct(e){return"string"==typeof e?Rt(e):Ot(e)}Rt=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw gt("The input to be decoded is not correctly encoded.",yt,e)}}:e=>{try{const 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 gt("The input to be decoded is not correctly encoded.",yt,e)}};class It extends Error{constructor(e,t){var n;super(e,t),st(this,"code",void 0),this.name=this.constructor.name,this.code=Cn,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}class xt extends Error{constructor(e,t){var n;super(e,t),st(this,"code",void 0),this.name=this.constructor.name,null!=t&&t.code&&(this.code=null==t?void 0:t.code),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}function jt(e,t,n){return new xt(e,{code:t,cause:n})}function Dt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ut(e){mt(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(ft&&!t.has("user-agent")&&t.set("user-agent",ft),t.has("authorization"))throw gt('"options.headers" must not include the "authorization" header name',yt);return t}function Wt(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw gt('"options.signal" must return or be an instance of AbortSignal',wt);return t}}function Kt(e){return e.includes("//")?e.replace("//","/"):e}function Lt(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw gt("".concat(n," must be a number"),wt,r);if(e>0)return;if(t){if(0!==e)throw gt("".concat(n," must be a non-negative number"),yt,r);return}throw gt("".concat(n," must be a positive number"),yt,r)}catch(e){if(o)throw jt(e.message,o,r);throw e}}function Mt(e,t,n,o){try{if("string"!=typeof e)throw gt("".concat(t," must be a string"),wt,o);if(0===e.length)throw gt("".concat(t," must not be empty"),yt,o)}catch(e){if(n)throw jt(e.message,n,o);throw e}}function Nt(e){!function(e,t){if(pn(e)!==t)throw function(e){let t='"response" content-type must be ';for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];if(o.length>2){const e=o.pop();t+="".concat(o.join(", "),", or ").concat(e)}else 2===o.length?t+="".concat(o[0]," or ").concat(o[1]):t+=o[0];return jt(t,Dn,e)}(e,t)}(e,"application/json")}function zt(){return Ct(crypto.getRandomValues(new Uint8Array(32)))}function Ht(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 It("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 It("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 It("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 It("unsupported CryptoKey algorithm name",{cause:e})}}function Jt(e){const t=null==e?void 0:e[bt];return"number"==typeof t&&Number.isFinite(t)?t:0}function Zt(e){const t=null==e?void 0:e[_t];return"number"==typeof t&&Number.isFinite(t)&&-1!==Math.sign(t)?t:30}function Ft(){return Math.floor(Date.now()/1e3)}function Vt(e){if("object"!=typeof e||null===e)throw gt('"as" must be an object',wt);Mt(e.issuer,'"as.issuer"')}function qt(e){if("object"!=typeof e||null===e)throw gt('"client" must be an object',wt);Mt(e.client_id,'"client.client_id"')}function Gt(e){return Mt(e,'"clientSecret"'),(t,n,o,r)=>{o.set("client_id",n.client_id),o.set("client_secret",e)}}function Xt(e,t){const{key:n,kid:o}=(r=e)instanceof CryptoKey?{key:r}:(null==r?void 0:r.key)instanceof CryptoKey?(void 0!==r.kid&&Mt(r.kid,'"kid"'),{key:r.key,kid:r.kid}):{};var r;return function(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw gt("".concat(t," must be a CryptoKey"),wt)}(e,t),"private"!==e.type)throw gt("".concat(t," must be a private CryptoKey"),yt)}(n,'"clientPrivateKey.key"'),async(e,r,i,a)=>{var s;const c={alg:Ht(n),kid:o},u=function(e,t){const n=Ft()+Jt(t);return{jti:zt(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,r);null==t||null===(s=t[St])||void 0===s||s.call(t,c,u),i.set("client_id",r.client_id),i.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),i.set("client_assertion",await async function(e,t,n){if(!n.usages.includes("sign"))throw gt('CryptoKey instances used for signing assertions must include "sign" in their "usages"',yt);const o="".concat(Ct(At(JSON.stringify(e))),".").concat(Ct(At(JSON.stringify(t)))),r=Ct(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:Fn(e)};case"RSA-PSS":switch(Zn(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 It("unsupported RSA-PSS hash name",{cause:e})}case"RSASSA-PKCS1-v1_5":return Zn(e),e.algorithm.name;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":case"Ed25519":return e.algorithm.name}throw new It("unsupported CryptoKey algorithm name",{cause:e})}(n),n,At(o)));return"".concat(o,".").concat(r)}(c,u,n))}}const Bt=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch(e){return null}};function Yt(e,t){if(t&&"https:"!==e.protocol)throw jt("only requests to HTTPS are allowed",Wn,e);if("https:"!==e.protocol&&"http:"!==e.protocol)throw jt("only HTTP and HTTPS requests are allowed",Kn,e)}function Qt(e,t,n,o){let r;if("string"!=typeof e||!(r=Bt(e)))throw jt("authorization server metadata does not contain a valid ".concat(n?'"as.mtls_endpoint_aliases.'.concat(t,'"'):'"as.'.concat(t,'"')),void 0===e?zn:Hn,{attribute:n?"mtls_endpoint_aliases.".concat(t):t});return Yt(r,o),r}function $t(e,t,n,o){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Qt(e.mtls_endpoint_aliases[t],t,n,o):Qt(e[t],t,n,o)}class en extends Error{constructor(e,t){var n;super(e,t),st(this,"cause",void 0),st(this,"code",void 0),st(this,"error",void 0),st(this,"status",void 0),st(this,"error_description",void 0),st(this,"response",void 0),this.name=this.constructor.name,this.code=Rn,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}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}class tn extends Error{constructor(e,t){var n,o;super(e,t),st(this,"cause",void 0),st(this,"code",void 0),st(this,"error",void 0),st(this,"error_description",void 0),this.name=this.constructor.name,this.code=In,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=null!==(n=t.cause.get("error_description"))&&void 0!==n?n:void 0,null===(o=Error.captureStackTrace)||void 0===o||o.call(Error,this,this.constructor)}}class nn extends Error{constructor(e,t){var n;super(e,t),st(this,"cause",void 0),st(this,"code",void 0),st(this,"response",void 0),st(this,"status",void 0),this.name=this.constructor.name,this.code=On,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}const on="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",rn="("+on+')\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"',an="("+on+")\\s*=\\s*("+on+")",sn=new RegExp("^[,\\s]*("+on+")"),cn=new RegExp("^[,\\s]*"+rn+"[,\\s]*(.*)"),un=new RegExp("^[,\\s]*"+an+"[,\\s]*(.*)"),ln=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");async function dn(e,t,n){if(e.status!==t){let t;var o;if(function(e){let t;if(t=function(e){if(!mt(e,Response))throw gt('"response" must be an instance of Response',wt);const t=e.headers.get("www-authenticate");if(null===t)return;const n=[];let o=t;for(;o;){var r;let t=o.match(sn);const i=null===(r=t)||void 0===r?void 0:r[1].toLowerCase();if(!i)return;const a=o.substring(t[0].length);if(a&&!a.match(/^[\s,]/))return;const s=a.match(/^\s+(.*)$/),c=!!s;o=s?s[1]:void 0;const u={};let l;if(c)for(;o;){let n,r;if(t=o.match(cn)){if([,n,r,o]=t,r.includes("\\"))try{r=JSON.parse('"'.concat(r,'"'))}catch(e){}u[n.toLowerCase()]=r}else{if(!(t=o.match(un))){if(t=o.match(ln)){if(Object.keys(u).length)break;[,l,o]=t;break}return}[,n,r,o]=t,u[n.toLowerCase()]=r}}else o=a||void 0;const d={scheme:i,parameters:u};l&&(d.token68=l),n.push(d)}return n.length?n:void 0}(e))throw new nn("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){Jn(e),Nt(e);try{const t=await e.clone().json();if(Dt(t)&&"string"==typeof t.error&&t.error.length)return t}catch(e){}}}(e))throw await(null===(o=e.body)||void 0===o?void 0:o.cancel()),new en("server responded with an error in the response body",{cause:t,response:e});throw jt('"response" is not a conform '.concat(n," response (unexpected HTTP status code)"),Un,e)}}function hn(e){if(!kn.has(e))throw gt('"options.DPoP" is not a valid DPoPHandle',yt)}function pn(e){var t;return null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.split(";")[0]}async function fn(e,t,n,o,r,i,a){return await n(e,t,r,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),((null==a?void 0:a[kt])||fetch)(o.href,{body:r,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Wt(o,null==a?void 0:a.signal)})}async function mn(e,t,n,o,r,i){var a;const s=$t(e,"token_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==i?void 0:i[vt]));r.set("grant_type",o);const c=Ut(null==i?void 0:i.headers);c.set("accept","application/json"),void 0!==(null==i?void 0:i.DPoP)&&(hn(i.DPoP),await i.DPoP.addProof(s,c,"POST"));const u=await fn(e,t,n,s,r,c,i);return null==i||null===(a=i.DPoP)||void 0===a||a.cacheNonce(u,s),u}const yn=new WeakMap,wn=new WeakMap;function gn(e){if(!e.id_token)return;const t=yn.get(e);if(!t)throw gt('"ref" was already garbage collected or did not resolve from the proper sources',yt);return t}async function vn(e,t,n,o,r,i){if(Vt(e),qt(t),!mt(n,Response))throw gt('"response" must be an instance of Response',wt);await dn(n,200,"Token Endpoint"),Jn(n);const a=await Bn(n);if(Mt(a.access_token,'"response" body "access_token" property',jn,{body:a}),Mt(a.token_type,'"response" body "token_type" property',jn,{body:a}),a.token_type=a.token_type.toLowerCase(),void 0!==a.expires_in){let e="number"!=typeof a.expires_in?parseFloat(a.expires_in):a.expires_in;Lt(e,!0,'"response" body "expires_in" property',jn,{body:a}),a.expires_in=e}if(void 0!==a.refresh_token&&Mt(a.refresh_token,'"response" body "refresh_token" property',jn,{body:a}),void 0!==a.scope&&"string"!=typeof a.scope)throw jt('"response" body "scope" property must be a string',jn,{body:a});if(void 0!==a.id_token){Mt(a.id_token,'"response" body "id_token" property',jn,{body:a});const i=["aud","exp","iat","iss","sub"];!0===t.require_auth_time&&i.push("auth_time"),void 0!==t.default_max_age&&(Lt(t.default_max_age,!0,'"client.default_max_age"'),i.push("auth_time")),null!=o&&o.length&&i.push(...o);const{claims:s,jwt:c}=await async function(e,t,n,o,r){let i,a,{0:s,1:c,length:u}=e.split(".");if(5===u){if(void 0===r)throw new It("JWE decryption is not configured",{cause:e});e=await r(e),({0:s,1:c,length:u}=e.split("."))}if(3!==u)throw jt("Invalid JWT",jn,e);try{i=JSON.parse(At(Ct(s)))}catch(e){throw jt("failed to parse JWT Header body as base64url encoded JSON",xn,e)}if(!Dt(i))throw jt("JWT Header must be a top level object",jn,e);if(t(i),void 0!==i.crit)throw new It('no JWT "crit" header parameter extensions are supported',{cause:{header:i}});try{a=JSON.parse(At(Ct(c)))}catch(e){throw jt("failed to parse JWT Payload body as base64url encoded JSON",xn,e)}if(!Dt(a))throw jt("JWT Payload must be a top level object",jn,e);const l=Ft()+n;if(void 0!==a.exp){if("number"!=typeof a.exp)throw jt('unexpected JWT "exp" (expiration time) claim type',jn,{claims:a});if(a.exp<=l-o)throw jt('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Ln,{claims:a,now:l,tolerance:o,claim:"exp"})}if(void 0!==a.iat&&"number"!=typeof a.iat)throw jt('unexpected JWT "iat" (issued at) claim type',jn,{claims:a});if(void 0!==a.iss&&"string"!=typeof a.iss)throw jt('unexpected JWT "iss" (issuer) claim type',jn,{claims:a});if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw jt('unexpected JWT "nbf" (not before) claim type',jn,{claims:a});if(a.nbf>l+o)throw jt('unexpected JWT "nbf" (not before) claim value',Ln,{claims:a,now:l,tolerance:o,claim:"nbf"})}if(void 0!==a.aud&&"string"!=typeof a.aud&&!Array.isArray(a.aud))throw jt('unexpected JWT "aud" (audience) claim type',jn,{claims:a});return{header:i,claims:a,jwt:e}}(a.id_token,Vn.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Jt(t),Zt(t),r).then(En.bind(void 0,i)).then(_n.bind(void 0,e)).then(bn.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&1!==s.aud.length){if(void 0===s.azp)throw jt('ID Token "aud" (audience) claim includes additional untrusted audiences',Mn,{claims:s,claim:"aud"});if(s.azp!==t.client_id)throw jt('unexpected ID Token "azp" (authorized party) claim value',Mn,{expected:t.client_id,claims:s,claim:"azp"})}void 0!==s.auth_time&&Lt(s.auth_time,!0,'ID Token "auth_time" (authentication time)',jn,{claims:s}),wn.set(n,c),yn.set(a,s)}if(void 0!==(null==i?void 0:i[a.token_type]))i[a.token_type](n,a);else if("dpop"!==a.token_type&&"bearer"!==a.token_type)throw new It("unsupported `token_type` value",{cause:{body:a}});return a}function bn(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw jt('unexpected JWT "aud" (audience) claim value',Mn,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw jt('unexpected JWT "aud" (audience) claim value',Mn,{expected:e,claims:t.claims,claim:"aud"});return t}function _n(e,t){var n,o;const r=null!==(n=null===(o=e[Qn])||void 0===o?void 0:o.call(e,t))&&void 0!==n?n:e.issuer;if(t.claims.iss!==r)throw jt('unexpected JWT "iss" (issuer) claim value',Mn,{expected:r,claims:t.claims,claim:"iss"});return t}const kn=new WeakSet,Sn=Symbol(),Tn={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 En(e,t){for(const n of e)if(void 0===t.claims[n])throw jt('JWT "'.concat(n,'" (').concat(Tn[n],") claim missing"),jn,{claims:t.claims});return t}const Pn=Symbol(),An=Symbol();const On="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Rn="OAUTH_RESPONSE_BODY_ERROR",Cn="OAUTH_UNSUPPORTED_OPERATION",In="OAUTH_AUTHORIZATION_RESPONSE_ERROR",xn="OAUTH_PARSE_ERROR",jn="OAUTH_INVALID_RESPONSE",Dn="OAUTH_RESPONSE_IS_NOT_JSON",Un="OAUTH_RESPONSE_IS_NOT_CONFORM",Wn="OAUTH_HTTP_REQUEST_FORBIDDEN",Kn="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Ln="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Mn="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Nn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",zn="OAUTH_MISSING_SERVER_METADATA",Hn="OAUTH_INVALID_SERVER_METADATA";function Jn(e){if(e.bodyUsed)throw gt('"response" body has been used already',yt)}function Zn(e){const{algorithm:t}=e;if("number"!=typeof t.modulusLength||t.modulusLength<2048)throw new It("unsupported ".concat(t.name," modulusLength"),{cause:e})}function Fn(e){const{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 It("unsupported ECDSA namedCurve",{cause:e})}}function Vn(e,t,n,o){if(void 0===e)if(Array.isArray(t)){if(!t.includes(o.alg))throw jt('unexpected JWT "alg" header parameter',jn,{header:o,expected:t,reason:"authorization server metadata"})}else{if(void 0===n)throw jt('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n});if("string"==typeof n?o.alg!==n:"function"==typeof n?!n(o.alg):!n.includes(o.alg))throw jt('unexpected JWT "alg" header parameter',jn,{header:o,expected:n,reason:"default value"})}else if("string"==typeof e?o.alg!==e:!e.includes(o.alg))throw jt('unexpected JWT "alg" header parameter',jn,{header:o,expected:e,reason:"client configuration"})}function qn(e,t){const{0:n,length:o}=e.getAll(t);if(o>1)throw jt('"'.concat(t,'" parameter must be provided only once'),jn);return n}const Gn=Symbol(),Xn=Symbol();async function Bn(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Nt;try{t=await e.json()}catch(t){throw n(e),jt('failed to parse "response" body as JSON',xn,t)}if(!Dt(t))throw jt('"response" body must be a top level object',jn,{body:t});return t}const Yn=Symbol(),Qn=Symbol(),$n=new TextEncoder,eo=new TextDecoder;function to(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=o}return t}function no(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function oo(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:eo.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=eo.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return no(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}const ro=function(e){return new TypeError("CryptoKey does not support this operation, its ".concat(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name"," must be ").concat(e))},io=(e,t)=>e.name===t;function ao(e,t){var n;if(n=e.hash,parseInt(n.name.slice(4),10)!==t)throw ro("SHA-".concat(t),"algorithm.hash")}function so(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if((o=o.filter(Boolean)).length>2){const t=o.pop();e+="one of type ".concat(o.join(", "),", or ").concat(t,".")}else 2===o.length?e+="one of type ".concat(o[0]," or ").concat(o[1],"."):e+="of type ".concat(o[0],".");if(null==t)e+=" Received ".concat(t);else if("function"==typeof t&&t.name)e+=" Received function ".concat(t.name);else if("object"==typeof t&&null!=t){var i;null!==(i=t.constructor)&&void 0!==i&&i.name&&(e+=" Received an instance of ".concat(t.constructor.name))}return e}const co=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return so("Key for the ".concat(e," algorithm must be "),t,...o)};class uo extends Error{constructor(e,t){var n;super(e,t),st(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}st(uo,"code","ERR_JOSE_GENERIC");class lo extends uo{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),st(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),st(this,"claim",void 0),st(this,"reason",void 0),st(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t}}st(lo,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class ho extends uo{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),st(this,"code","ERR_JWT_EXPIRED"),st(this,"claim",void 0),st(this,"reason",void 0),st(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t}}st(ho,"code","ERR_JWT_EXPIRED");class po extends uo{constructor(){super(...arguments),st(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}st(po,"code","ERR_JOSE_ALG_NOT_ALLOWED");class fo extends uo{constructor(){super(...arguments),st(this,"code","ERR_JOSE_NOT_SUPPORTED")}}st(fo,"code","ERR_JOSE_NOT_SUPPORTED"),st(class extends uo{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),st(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),st(class extends uo{constructor(){super(...arguments),st(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");class mo extends uo{constructor(){super(...arguments),st(this,"code","ERR_JWS_INVALID")}}st(mo,"code","ERR_JWS_INVALID");class yo extends uo{constructor(){super(...arguments),st(this,"code","ERR_JWT_INVALID")}}st(yo,"code","ERR_JWT_INVALID"),st(class extends uo{constructor(){super(...arguments),st(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");class wo extends uo{constructor(){super(...arguments),st(this,"code","ERR_JWKS_INVALID")}}st(wo,"code","ERR_JWKS_INVALID");class go extends uo{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),st(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}st(go,"code","ERR_JWKS_NO_MATCHING_KEY");class vo extends uo{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),st(this,Symbol.asyncIterator,void 0),st(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}st(vo,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class bo extends uo{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),st(this,"code","ERR_JWKS_TIMEOUT")}}st(bo,"code","ERR_JWKS_TIMEOUT");class _o extends uo{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),st(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}st(_o,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const ko=e=>{if("CryptoKey"===(null==e?void 0:e[Symbol.toStringTag]))return!0;try{return e instanceof CryptoKey}catch(e){return!1}},So=e=>"KeyObject"===(null==e?void 0:e[Symbol.toStringTag]),To=e=>ko(e)||So(e);function Eo(e,t,n){try{return oo(e)}catch(e){throw new n("Failed to base64url decode the ".concat(t))}}function Po(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}const Ao=e=>Po(e)&&"string"==typeof e.kty;async function Oo(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return so("Key must be ",e,...n)}(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:"SHA-".concat(e.slice(-3)),name:"HMAC"},!1,[n])}return function(e,t,n){switch(t){case"HS256":case"HS384":case"HS512":if(!io(e.algorithm,"HMAC"))throw ro("HMAC");ao(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if(!io(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ro("RSASSA-PKCS1-v1_5");ao(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if(!io(e.algorithm,"RSA-PSS"))throw ro("RSA-PSS");ao(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if(!io(e.algorithm,"Ed25519"))throw ro("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!io(e.algorithm,t))throw ro(t);break;case"ES256":case"ES384":case"ES512":{if(!io(e.algorithm,"ECDSA"))throw ro("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw ro(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(t,"."))}(e,n)}(t,e,n),t}const Ro='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function Co(e){var t,n;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:o,keyUsages:r}=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 fo(Ro)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(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-".concat(parseInt(e.alg.slice(-3),10)||1)},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new fo(Ro)}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 fo(Ro)}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 fo(Ro)}break;default:throw new fo('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),i=ut({},e);return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,null!==(t=e.ext)&&void 0!==t?t:!e.d&&!e.priv,null!==(n=e.key_ops)&&void 0!==n?n:r)}const Io="given KeyObject instance cannot be used for this algorithm";let xo;const jo=async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];xo||(xo=new WeakMap);let r=xo.get(e);if(null!=r&&r[n])return r[n];const i=await Co(ut(ut({},t),{},{alg:n}));return o&&Object.freeze(e),r?r[n]=i:xo.set(e,{[n]:i}),i};const Do=(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},Uo=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let o=0;for(let t=0;t<n;t++)o=o<<8|e.data[e.pos++];return o}return t},Wo=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},Ko=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Lo=(e,t,n)=>{var o;const r=(e=>no(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"")))(e);let i=n;return null!=t&&null!==(o=t.startsWith)&&void 0!==o&&o.call(t,"ECDH-ES")&&(i||(i={}),i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){Wo(e,48,"Invalid PKCS#8 structure"),Uo(e),Wo(e,2,"Expected version field");const t=Uo(e);e.pos+=t,Wo(e,48,"Expected algorithm identifier"),Uo(e),e.pos}(t),(e=>{const t=(e=>{Wo(e,6,"Expected algorithm OID");const t=Uo(e);return Ko(e,t)})(e);if(Do(t,[43,101,110]))return"X25519";if(!Do(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Wo(e,6,"Expected curve OID");const n=Uo(e),o=Ko(e,n);for(const{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(Do(o,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,n,o)=>{var r;let i,a;const s="spki"===e,c=()=>s?["verify"]:["sign"];switch(n){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:"SHA-".concat(n.slice(-3))},a=c();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(n.slice(-3))},a=c();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(n.slice(-3),10)||1)},a=s?["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=c();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=o.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new fo("Invalid or unsupported key format")}a=s?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},a=c();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:n},a=c();break;default:throw new fo('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,null!==(r=null==o?void 0:o.extractable)&&void 0!==r?r:!!s,a)})("pkcs8",r,t,i)},Mo=e=>null==e?void 0:e[Symbol.toStringTag],No=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(e,'" when present'))}if(void 0!==t.alg&&t.alg!==e)throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(e,'" when present'));if(Array.isArray(t.key_ops)){var o,r;let i;switch(!0){case"sign"===n||"verify"===n:case"dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===n?"wrapKey":"unwrapKey":n;break;case"encrypt"===n&&e.startsWith("RSA"):i="wrapKey";break;case"decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(i&&!1===(null===(o=t.key_ops)||void 0===o||null===(r=o.includes)||void 0===r?void 0:r.call(o,i)))throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(i,'" when present'))}return!0};var zo,Ho;let Jo,Zo;if("undefined"==typeof navigator||null===(zo=navigator.userAgent)||void 0===zo||null===(Ho=zo.startsWith)||void 0===Ho||!Ho.call(zo,"Mozilla/5.0 ")){const e="v6.8.2";Zo="".concat("openid-client","/").concat(e),Jo={"user-agent":Zo}}const Fo=e=>Vo.get(e);let Vo,qo;function Go(e){return void 0!==e?Gt(e):(qo||(qo=new WeakMap),(e,t,n,o)=>{let r;return(r=qo.get(t))||(function(e,t){if("string"!=typeof e)throw Qo("".concat(t," must be a string"),Yo);if(0===e.length)throw Qo("".concat(t," must not be empty"),Bo)}(t.client_secret,'"metadata.client_secret"'),r=Gt(t.client_secret),qo.set(t,r)),r(e,t,n,o)})}const Xo=kt,Bo="ERR_INVALID_ARG_VALUE",Yo="ERR_INVALID_ARG_TYPE";function Qo(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}class $o extends Error{constructor(e,t){var n;super(e,t),st(this,"code",void 0),this.name=this.constructor.name,this.code=null==t?void 0:t.code,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}function er(e,t,n){return new $o(e,{cause:t,code:n})}function tr(e){if(e instanceof TypeError||e instanceof $o||e instanceof en||e instanceof tn||e instanceof nn)throw e;if(e instanceof xt)switch(e.code){case Wn:throw er("only requests to HTTPS are allowed",e,e.code);case Kn:throw er("only requests to HTTP or HTTPS are allowed",e,e.code);case Un:throw er("unexpected HTTP response status code",e.cause,e.code);case Dn:throw er("unexpected response content-type",e.cause,e.code);case xn:throw er("parsing error occured",e,e.code);case jn:throw er("invalid response encountered",e,e.code);case Mn:throw er("unexpected JWT claim value encountered",e,e.code);case Nn:throw er("unexpected JSON attribute value encountered",e,e.code);case Ln:throw er("JWT timestamp claim value failed validation",e,e.code);default:throw er(e.message,e,e.code)}if(e instanceof It)throw er("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw er("runtime operation error",e,Cn);case"NotSupportedError":throw er("runtime unsupported operation",e,Cn);case"TimeoutError":throw er("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw er("operation aborted",e,"OAUTH_ABORT")}throw new $o("something went wrong",{cause:e})}async function nr(e,t,n,o,r){const i=await async function(e,t){var n,o;if(!(e instanceof URL))throw Qo('"server" must be an instance of URL',Yo);const r=!e.href.includes("/.well-known/"),i=null!==(n=null==t?void 0:t.timeout)&&void 0!==n?n:30,a=AbortSignal.timeout(1e3*i),s=await(r?async function(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw gt('"'.concat("issuerIdentifier",'" must be an instance of URL'),wt);Yt(e,!0!==(null==o?void 0:o[vt]));const r=n(new URL(e.href)),i=Ut(null==o?void 0:o.headers);return i.set("accept","application/json"),((null==o?void 0:o[kt])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Wt(r,null==o?void 0:o.signal)})}(e,0,(e=>{switch(null==t?void 0:t.algorithm){case void 0:case"oidc":!function(e){e.pathname=Kt("".concat(e.pathname,"/").concat(".well-known/openid-configuration"))}(e);break;case"oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Kt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")))}(e,".well-known/oauth-authorization-server");break;default:throw gt('"options.algorithm" must be "oidc" (default), or "oauth2"',yt)}return e}),t)}(e,{algorithm:null==t?void 0:t.algorithm,[kt]:null==t?void 0:t[Xo],[vt]:null==t||null===(o=t.execute)||void 0===o?void 0:o.includes(lr),signal:a,headers:new Headers(Jo)}):((null==t?void 0:t[Xo])||fetch)((Yt(e,null==t||null===(c=t.execute)||void 0===c||!c.includes(lr)),e.href),{headers:Object.fromEntries(new Headers(ut({accept:"application/json"},Jo)).entries()),body:void 0,method:"GET",redirect:"manual",signal:a})).then((e=>async function(e,t){const n=e;if(!(n instanceof URL)&&n!==Yn)throw gt('"expectedIssuerIdentifier" must be an instance of URL',wt);if(!mt(t,Response))throw gt('"response" must be an instance of Response',wt);if(200!==t.status)throw jt('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Un,t);Jn(t);const o=await Bn(t);if(Mt(o.issuer,'"response" body "issuer" property',jn,{body:o}),n!==Yn&&new URL(o.issuer).href!==n.href)throw jt('"response" body "issuer" property does not match the expected value',Nn,{expected:n.href,body:o,attribute:"issuer"});return o}(Yn,e))).catch(tr);var c;return r&&new URL(s.issuer).href!==e.href&&(function(e,t,n){return!("https://login.microsoftonline.com"!==e.origin||null!=n&&n.algorithm&&"oidc"!==n.algorithm||(t[or]=!0,0))}(e,s,t)||function(e,t){return!(!e.hostname.endsWith(".b2clogin.com")||null!=t&&t.algorithm&&"oidc"!==t.algorithm)}(e,t)||(()=>{throw new $o("discovered metadata issuer does not match the expected issuer",{code:Nn,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}(e,r),a=new rr(i,t,n,o);let s=Fo(a);if(null!=r&&r[Xo]&&(s.fetch=r[Xo]),null!=r&&r.timeout&&(s.timeout=r.timeout),null!=r&&r.execute)for(const e of r.execute)e(a);return a}new TextDecoder;const or=Symbol();class rr{constructor(e,t,n,o){var r,i,a,s,c;if("string"!=typeof t||!t.length)throw Qo('"clientId" must be a non-empty string',Yo);if("string"==typeof n&&(n={client_secret:n}),void 0!==(null===(r=n)||void 0===r?void 0:r.client_id)&&t!==n.client_id)throw Qo('"clientId" and "metadata.client_id" must be the same',Bo);const u=ut(ut({},structuredClone(n)),{},{client_id:t});let l;u[bt]=null!==(i=null===(a=n)||void 0===a?void 0:a[bt])&&void 0!==i?i:0,u[_t]=null!==(s=null===(c=n)||void 0===c?void 0:c[_t])&&void 0!==s?s:30,l=o||("string"==typeof u.client_secret&&u.client_secret.length?Go(u.client_secret):(e,t,n,o)=>{n.set("client_id",t.client_id)});let d=Object.freeze(u);const h=structuredClone(e);or in e&&(h[Qn]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace("{tenantid}",n)});let p=Object.freeze(h);Vo||(Vo=new WeakMap),Vo.set(this,{__proto__:null,as:p,c:d,auth:l,tlsOnly:!0,jwksCache:{}})}serverMetadata(){const e=structuredClone(Fo(this).as);return function(e){Object.defineProperties(e,function(e){return{supportsPKCE:{__proto__:null,value(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"S256";return!0===(null===(t=e.code_challenge_methods_supported)||void 0===t?void 0:t.includes(n))}}}}(e))}(e),e}clientMetadata(){return structuredClone(Fo(this).c)}get timeout(){return Fo(this).timeout}set timeout(e){Fo(this).timeout=e}get[Xo](){return Fo(this).fetch}set[Xo](e){Fo(this).fetch=e}}function ir(e){Object.defineProperties(e,function(e){let t;if(void 0!==e.expires_in){const n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){const e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return gn(this)}catch(e){return}}}}}(e))}async function ar(e,t,n){var o;let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=null===(o=e.headers.get("retry-after"))||void 0===o?void 0:o.trim();if(void 0===i)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else{const e=new Date(i);if(Number.isFinite(e.getTime())){const t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3))}}if(r&&!Number.isFinite(a))throw new xt("invalid Retry-After header value",{cause:e});a>t&&await sr(a-t,n)}function sr(e,t){return new Promise(((n,o)=>{const r=e=>{try{t.throwIfAborted()}catch(e){return void o(e)}if(e<=0)return void n();const i=Math.min(e,5);setTimeout((()=>r(e-i)),1e3*i)};r(e)}))}async function cr(e,t){yr(e);const{as:n,c:o,auth:r,fetch:i,tlsOnly:a,timeout:s}=Fo(e);return async function(e,t,n,o,r){Vt(e),qt(t);const i=$t(e,"backchannel_authentication_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==r?void 0:r[vt])),a=new URLSearchParams(o);a.set("client_id",t.client_id);const s=Ut(null==r?void 0:r.headers);return s.set("accept","application/json"),fn(e,t,n,i,a,s,r)}(n,o,r,t,{[kt]:i,[vt]:!a,headers:new Headers(Jo),signal:wr(s)}).then((e=>async function(e,t,n){if(Vt(e),qt(t),!mt(n,Response))throw gt('"response" must be an instance of Response',wt);await dn(n,200,"Backchannel Authentication Endpoint"),Jn(n);const o=await Bn(n);Mt(o.auth_req_id,'"response" body "auth_req_id" property',jn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Lt(r,!0,'"response" body "expires_in" property',jn,{body:o}),o.expires_in=r,void 0!==o.interval&&Lt(o.interval,!1,'"response" body "interval" property',jn,{body:o}),o}(n,o,e))).catch(tr)}async function ur(e,t,n,o){var r,i;yr(e),n=new URLSearchParams(n);let a=null!==(r=t.interval)&&void 0!==r?r:5;const s=null!==(i=null==o?void 0:o.signal)&&void 0!==i?i:AbortSignal.timeout(1e3*t.expires_in);try{await sr(a,s)}catch(e){tr(e)}const{as:c,c:u,auth:l,fetch:d,tlsOnly:h,nonRepudiation:p,timeout:f,decrypt:m}=Fo(e),y=(r,i)=>ur(e,ut(ut({},t),{},{interval:r}),n,ut(ut({},o),{},{signal:s,flag:i})),w=await async function(e,t,n,o,r){Vt(e),qt(t),Mt(o,'"authReqId"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("auth_req_id",o),mn(e,t,n,"urn:openid:params:grant-type:ciba",i,r)}(c,u,l,t.auth_req_id,{[kt]:d,[vt]:!h,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Jo),signal:s.aborted?s:wr(f)}).catch(tr);var g;if(503===w.status&&w.headers.has("retry-after"))return await ar(w,a,s,!0),await(null===(g=w.body)||void 0===g?void 0:g.cancel()),y(a);const v=async function(e,t,n,o){return vn(e,t,n,void 0,null==o?void 0:o[Tt],null==o?void 0:o.recognizedTokenTypes)}(c,u,w,{[Tt]:m});let b;try{b=await v}catch(e){if(gr(e,o))return y(a,vr);if(e instanceof en)switch(e.error){case"slow_down":a+=5;case"authorization_pending":return await ar(e.response,a,s),y(a)}tr(e)}return b.id_token&&await(null==p?void 0:p(w)),ir(b),b}function lr(e){Fo(e).tlsOnly=!1}async function dr(e,t,n,o,r){if(yr(e),!((null==r?void 0:r.flag)===vr||t instanceof URL||function(e){try{return"Request"===Object.getPrototypeOf(e)[Symbol.toStringTag]}catch(e){return!1}}(t)))throw Qo('"currentUrl" must be an instance of URL, or Request',Yo);let i,a;const{as:s,c:c,auth:u,fetch:l,tlsOnly:d,jarm:h,hybrid:p,nonRepudiation:f,timeout:m,decrypt:y,implicit:w}=Fo(e);if((null==r?void 0:r.flag)===vr)i=r.authResponse,a=r.redirectUri;else{if(!(t instanceof URL)){const e=t;switch(t=new URL(t.url),e.method){case"GET":break;case"POST":const n=new URLSearchParams(await async function(e){if("POST"!==e.method)throw gt("form_post responses are expected to use the POST method",yt,{cause:e});if("application/x-www-form-urlencoded"!==pn(e))throw gt("form_post responses are expected to use the application/x-www-form-urlencoded content-type",yt,{cause:e});return async function(e){if(e.bodyUsed)throw gt("form_post Request instances must contain a readable body",yt,{cause:e});return e.text()}(e)}(e));if(p)t.hash=n.toString();else for(const[e,o]of n.entries())t.searchParams.append(e,o);break;default:throw Qo("unexpected Request HTTP method",Bo)}}switch(a=function(e){return(e=new URL(e)).search="",e.hash="",e.href}(t),!0){case!!h:i=await h(t,null==n?void 0:n.expectedState);break;case!!p:i=await p(t,null==n?void 0:n.expectedNonce,null==n?void 0:n.expectedState,null==n?void 0:n.maxAge);break;case!!w:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=function(e,t,n,o){if(Vt(e),qt(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw gt('"parameters" must be an instance of URLSearchParams, or URL',wt);if(qn(n,"response"))throw jt('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',jn,{parameters:n});const r=qn(n,"iss"),i=qn(n,"state");if(!r&&e.authorization_response_iss_parameter_supported)throw jt('response parameter "iss" (issuer) missing',jn,{parameters:n});if(r&&r!==e.issuer)throw jt('unexpected "iss" (issuer) response parameter value',jn,{expected:e.issuer,parameters:n});switch(o){case void 0:case Xn:if(void 0!==i)throw jt('unexpected "state" response parameter encountered',jn,{expected:void 0,parameters:n});break;case Gn:break;default:if(Mt(o,'"expectedState" argument'),i!==o)throw jt(void 0===i?'response parameter "state" missing':'unexpected "state" response parameter value',jn,{expected:o,parameters:n})}if(qn(n,"error"))throw new tn("authorization response from the server is an error",{cause:n});const a=qn(n,"id_token"),s=qn(n,"token");if(void 0!==a||void 0!==s)throw new It("implicit and hybrid flows are not supported");return c=new URLSearchParams(n),kn.add(c),c;var c}(s,c,t.searchParams,null==n?void 0:n.expectedState)}catch(e){tr(e)}}}const g=await async function(e,t,n,o,r,i,a){if(Vt(e),qt(t),!kn.has(o))throw gt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',yt);Mt(r,'"redirectUri"');const s=qn(o,"code");if(!s)throw jt('no authorization code in "callbackParameters"',jn);const c=new URLSearchParams(null==a?void 0:a.additionalParameters);return c.set("redirect_uri",r),c.set("code",s),i!==Sn&&(Mt(i,'"codeVerifier"'),c.set("code_verifier",i)),mn(e,t,n,"authorization_code",c,a)}(s,c,u,i,a,(null==n?void 0:n.pkceCodeVerifier)||Sn,{additionalParameters:o,[kt]:l,[vt]:!d,DPoP:null==r?void 0:r.DPoP,headers:new Headers(Jo),signal:wr(m)}).catch(tr);"string"!=typeof(null==n?void 0:n.expectedNonce)&&"number"!=typeof(null==n?void 0:n.maxAge)||(n.idTokenExpected=!0);const v=async function(e,t,n,o){return"string"==typeof(null==o?void 0:o.expectedNonce)||"number"==typeof(null==o?void 0:o.maxAge)||null!=o&&o.requireIdToken?async function(e,t,n,o,r,i,a){const s=[];switch(o){case void 0:o=Pn;break;case Pn:break;default:Mt(o,'"expectedNonce" argument'),s.push("nonce")}switch(null!=r||(r=t.default_max_age),r){case void 0:r=An;break;case An:break;default:Lt(r,!0,'"maxAge" argument'),s.push("auth_time")}const c=await vn(e,t,n,s,i,a);Mt(c.id_token,'"response" body "id_token" property',jn,{body:c});const u=gn(c);if(r!==An){const e=Ft()+Jt(t),n=Zt(t);if(u.auth_time+r<e-n)throw jt("too much time has elapsed since the last End-User authentication",Ln,{claims:u,now:e,tolerance:n,claim:"auth_time"})}if(o===Pn){if(void 0!==u.nonce)throw jt('unexpected ID Token "nonce" claim value',Mn,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==o)throw jt('unexpected ID Token "nonce" claim value',Mn,{expected:o,claims:u,claim:"nonce"});return c}(e,t,n,o.expectedNonce,o.maxAge,o[Tt],o.recognizedTokenTypes):async function(e,t,n,o,r){const i=await vn(e,t,n,void 0,o,r),a=gn(i);if(a){if(void 0!==t.default_max_age){Lt(t.default_max_age,!0,'"client.default_max_age"');const e=Ft()+Jt(t),n=Zt(t);if(a.auth_time+t.default_max_age<e-n)throw jt("too much time has elapsed since the last End-User authentication",Ln,{claims:a,now:e,tolerance:n,claim:"auth_time"})}if(void 0!==a.nonce)throw jt('unexpected ID Token "nonce" claim value',Mn,{expected:void 0,claims:a,claim:"nonce"})}return i}(e,t,n,null==o?void 0:o[Tt],null==o?void 0:o.recognizedTokenTypes)}(s,c,g,{expectedNonce:null==n?void 0:n.expectedNonce,maxAge:null==n?void 0:n.maxAge,requireIdToken:null==n?void 0:n.idTokenExpected,[Tt]:y});let b;try{b=await v}catch(t){if(gr(t,r))return dr(e,void 0,n,o,ut(ut({},r),{},{flag:vr,authResponse:i,redirectUri:a}));tr(t)}return b.id_token&&await(null==f?void 0:f(g)),ir(b),b}async function hr(e,t,n,o){yr(e),n=new URLSearchParams(n);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,nonRepudiation:u,timeout:l,decrypt:d}=Fo(e),h=await async function(e,t,n,o,r){Vt(e),qt(t),Mt(o,'"refreshToken"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("refresh_token",o),mn(e,t,n,"refresh_token",i,r)}(r,i,a,t,{[kt]:s,[vt]:!c,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Jo),signal:wr(l)}).catch(tr),p=async function(e,t,n,o){return vn(e,t,n,void 0,null==o?void 0:o[Tt],null==o?void 0:o.recognizedTokenTypes)}(r,i,h,{[Tt]:d});let f;try{f=await p}catch(r){if(gr(r,o))return hr(e,t,n,ut(ut({},o),{},{flag:vr}));tr(r)}return f.id_token&&await(null==u?void 0:u(h)),ir(f),f}async function pr(e,t,n){yr(e),t=new URLSearchParams(t);const{as:o,c:r,auth:i,fetch:a,tlsOnly:s,timeout:c}=Fo(e),u=await async function(e,t,n,o,r){return Vt(e),qt(t),mn(e,t,n,"client_credentials",new URLSearchParams(o),r)}(o,r,i,t,{[kt]:a,[vt]:!s,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Jo),signal:wr(c)}).catch(tr),l=async function(e,t,n){return vn(e,t,n,void 0,void 0,void 0)}(o,r,u);let d;try{d=await l}catch(o){if(gr(o,n))return pr(e,t,ut(ut({},n),{},{flag:vr}));tr(o)}return ir(d),d}function fr(e,t){yr(e);const{as:n,c:o,tlsOnly:r,hybrid:i,jarm:a,implicit:s}=Fo(e),c=$t(n,"authorization_endpoint",!1,r);if((t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw Qo("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Bo);a&&t.set("response_mode","jwt")}for(const[e,n]of t.entries())c.searchParams.append(e,n);return c}async function mr(e,t,n){yr(e);const o=fr(e,t),{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u}=Fo(e),l=await async function(e,t,n,o,r){var i;Vt(e),qt(t);const a=$t(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,!0!==(null==r?void 0:r[vt])),s=new URLSearchParams(o);s.set("client_id",t.client_id);const c=Ut(null==r?void 0:r.headers);c.set("accept","application/json"),void 0!==(null==r?void 0:r.DPoP)&&(hn(r.DPoP),await r.DPoP.addProof(a,c,"POST"));const u=await fn(e,t,n,a,s,c,r);return null==r||null===(i=r.DPoP)||void 0===i||i.cacheNonce(u,a),u}(r,i,a,o.searchParams,{[kt]:s,[vt]:!c,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Jo),signal:wr(u)}).catch(tr),d=async function(e,t,n){if(Vt(e),qt(t),!mt(n,Response))throw gt('"response" must be an instance of Response',wt);await dn(n,201,"Pushed Authorization Request Endpoint"),Jn(n);const o=await Bn(n);Mt(o.request_uri,'"response" body "request_uri" property',jn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Lt(r,!0,'"response" body "expires_in" property',jn,{body:o}),o.expires_in=r,o}(r,i,l);let h;try{h=await d}catch(o){if(gr(o,n))return mr(e,t,ut(ut({},n),{},{flag:vr}));tr(o)}return fr(e,{request_uri:h.request_uri})}function yr(e){if(!(e instanceof rr))throw Qo('"config" must be an instance of Configuration',Yo);if(Object.getPrototypeOf(e)!==rr.prototype)throw Qo("subclassing Configuration is not allowed",Bo)}function wr(e){return e?AbortSignal.timeout(1e3*e):void 0}function gr(e,t){return!(null==t||!t.DPoP||t.flag===vr)&&function(e){if(e instanceof nn){const{0:t,length:n}=e.cause;return 1===n&&"dpop"===t.scheme&&"use_dpop_nonce"===t.parameters.error}return e instanceof en&&"use_dpop_nonce"===e.error}(e)}Object.freeze(rr.prototype);const vr=Symbol();async function br(e,t,n,o){yr(e);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u,decrypt:l}=Fo(e),d=await async function(e,t,n,o,r,i){return Vt(e),qt(t),Mt(o,'"grantType"'),mn(e,t,n,o,new URLSearchParams(r),i)}(r,i,a,t,new URLSearchParams(n),{[kt]:s,[vt]:!c,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Jo),signal:wr(u)}).then((e=>{let n;return"urn:ietf:params:oauth:grant-type:token-exchange"===t&&(n={n_a:()=>{}}),async function(e,t,n,o){return vn(e,t,n,void 0,null==o?void 0:o[Tt],null==o?void 0:o.recognizedTokenTypes)}(r,i,e,{[Tt]:l,recognizedTokenTypes:n})})).catch(tr);return ir(d),d}async function _r(e,t,n){if(!Po(e))throw new mo("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new mo('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new mo("JWS Protected Header incorrect type");if(void 0===e.payload)throw new mo("JWS Payload missing");if("string"!=typeof e.signature)throw new mo("JWS Signature missing or incorrect type");if(void 0!==e.header&&!Po(e.header))throw new mo("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=oo(e.protected);o=JSON.parse(eo.decode(t))}catch(e){throw new mo("JWS Protected Header is invalid")}if(!function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.filter(Boolean);if(0===o.length||1===o.length)return!0;let r;for(const e of o){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0}(o,e.header))throw new mo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r=ut(ut({},o),e.header),i=function(e,t,n,o,r){if(void 0!==r.crit&&void 0===(null==o?void 0:o.crit))throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new fo('Extension Header Parameter "'.concat(t,'" is not recognized'));if(void 0===r[t])throw new e('Extension Header Parameter "'.concat(t,'" is missing'));if(i.get(t)&&void 0===o[t])throw new e('Extension Header Parameter "'.concat(t,'" MUST be integrity protected'))}return new Set(o.crit)}(mo,new Map([["b64",!0]]),null==n?void 0:n.crit,o,r);let a=!0;if(i.has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new mo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new mo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError('"'.concat("algorithms",'" option must be an array of strings'));if(t)return new Set(t)}(0,n.algorithms);if(c&&!c.has(s))throw new po('"alg" (Algorithm) Header Parameter value not allowed');if(a){if("string"!=typeof e.payload)throw new mo("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new mo("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t&&(t=await t(o,e),u=!0),function(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(Ao(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&No(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!To(t))throw new TypeError(co(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError("".concat(Mo(t),' instances for symmetric algorithms must be of type "secret"'))}})(e,t,n);break;default:((e,t,n)=>{if(Ao(t))switch(n){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&No(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&No(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!To(t))throw new TypeError(co(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError("".concat(Mo(t),' instances for asymmetric algorithms must not be of type "secret"'));if("public"===t.type)switch(n){case"sign":throw new TypeError("".concat(Mo(t),' instances for asymmetric algorithm signing must be of type "private"'));case"decrypt":throw new TypeError("".concat(Mo(t),' instances for asymmetric algorithm decryption must be of type "private"'))}if("private"===t.type)switch(n){case"verify":throw new TypeError("".concat(Mo(t),' instances for asymmetric algorithm verifying must be of type "public"'));case"encrypt":throw new TypeError("".concat(Mo(t),' instances for asymmetric algorithm encryption must be of type "public"'))}})(e,t,n)}}(s,t,"verify");const l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.reduce(((e,t)=>{let{length:n}=t;return e+n}),0),r=new Uint8Array(o);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}(void 0!==e.protected?to(e.protected):new Uint8Array,to("."),"string"==typeof e.payload?a?to(e.payload):$n.encode(e.payload):e.payload),d=Eo(e.signature,"signature",mo),h=await async function(e,t){if(e instanceof Uint8Array)return e;if(ko(e))return e;if(So(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{xo||(xo=new WeakMap);let n=xo.get(e);if(null!=n&&n[t])return n[t];const o="public"===e.type,r=!!o;let i;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Io)}i=e.toCryptoKey(e.asymmetricKeyType,r,o?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError(Io);i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Io);i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){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 new TypeError(Io)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,o?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[o?"verify":"sign"])}if("ec"===e.asymmetricKeyType){var a;const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(null===(a=e.asymmetricKeyDetails)||void 0===a?void 0:a.namedCurve);if(!n)throw new TypeError(Io);const s={ES256:"P-256",ES384:"P-384",ES512:"P-521"};s[t]&&n===s[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:n},r,o?[]:["deriveBits"]))}if(!i)throw new TypeError(Io);return n?n[t]=i:xo.set(e,{[t]:i}),i})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return jo(e,n,t)}if(Ao(e))return e.k?oo(e.k):jo(e,e,t,!0);throw new Error("unreachable")}(t,s);if(!await async function(e,t,n,o){const r=await Oo(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError("".concat(e," requires key modulusLength to be 2048 bits or larger"))}}(e,r);const i=function(e,t){const n="SHA-".concat(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 fo("alg ".concat(e," is not supported either by JOSE or your javascript runtime"))}}(e,r.algorithm);try{return await crypto.subtle.verify(i,r,n,o)}catch(e){return!1}}(s,h,d,l))throw new _o;let p;p=a?Eo(e.payload,"payload",mo):"string"==typeof e.payload?$n.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=o),void 0!==e.header&&(f.unprotectedHeader=e.header),u?ut(ut({},f),{},{key:h}):f}const kr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Sr(e){const t=kr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(3600*n);break;case"day":case"days":case"d":o=Math.round(86400*n);break;case"week":case"weeks":case"w":o=Math.round(604800*n);break;default:o=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-o:o}const Tr=e=>e.includes("/")?e.toLowerCase():"application/".concat(e.toLowerCase());function Er(e,t){let n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{n=JSON.parse(eo.decode(t))}catch(e){}if(!Po(n))throw new yo("JWT Claims Set must be a top-level JSON object");const{typ:r}=o;if(r&&("string"!=typeof e.typ||Tr(e.typ)!==Tr(r)))throw new lo('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=o,l=[...i];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new lo('missing required "'.concat(e,'" claim'),n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new lo('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new lo('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(h="string"==typeof c?[c]:c,!("string"==typeof(d=n.aud)?h.includes(d):Array.isArray(d)&&h.some(Set.prototype.has.bind(new Set(d))))))throw new lo('unexpected "aud" claim value',n,"aud","check_failed");var d,h;let p;switch(typeof o.clockTolerance){case"string":p=Sr(o.clockTolerance);break;case"number":p=o.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=o,m=(y=f||new Date,Math.floor(y.getTime()/1e3));var y;if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new lo('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new lo('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>m+p)throw new lo('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new lo('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=m-p)throw new ho('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const e=m-n.iat;if(e-p>("number"==typeof u?u:Sr(u)))throw new ho('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-p)throw new lo('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}function Pr(e){return Po(e)}var Ar,Or,Rr=new WeakMap,Cr=new WeakMap;class Ir{constructor(e){if(it(this,Rr,void 0),it(this,Cr,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Pr)}(e))throw new wo("JSON Web Key Set malformed");at(Rr,this,structuredClone(e))}jwks(){return rt(Rr,this)}async getKey(e,t){const{alg:n,kid:o}=ut(ut({},e),null==t?void 0:t.header),r=function(e){switch("string"==typeof e&&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 fo('Unsupported "alg" value for a JSON Web Key Set')}}(n),i=rt(Rr,this).keys.filter((e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=n===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(n){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t})),{0:a,length:s}=i;if(0===s)throw new go;if(1!==s){const e=new vo,t=rt(Cr,this);throw e[Symbol.asyncIterator]=function(e){return function(){return new dt(e.apply(this,arguments))}}((function*(){for(const e of i)try{yield yield nt(xr(t,e,n))}catch(e){}})),e}return xr(rt(Cr,this),a,n)}}async function xr(e,t,n){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[n]){const e=await async function(e,t){if(!Po(e))throw new TypeError("JWK must be an object");let n;switch(null!=t||(t=e.alg),null!=n||(n=e.ext),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return oo(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new fo('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Co(ut(ut({},e),{},{alg:t,ext:n}));case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return Co(ut(ut({},e),{},{ext:n}));case"EC":case"OKP":return Co(ut(ut({},e),{},{alg:t,ext:n}));default:throw new fo('Unsupported "kty" (Key Type) Parameter value')}}(ut(ut({},t),{},{ext:!0}),n);if(e instanceof Uint8Array||"public"!==e.type)throw new wo("JSON Web Key Set members must be public keys");o[n]=e}return o[n]}function jr(e){const t=new Ir(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}let Dr;if("undefined"==typeof navigator||null===(Ar=navigator.userAgent)||void 0===Ar||null===(Or=Ar.startsWith)||void 0===Or||!Or.call(Ar,"Mozilla/5.0 ")){const e="v6.2.2";Dr="".concat("jose","/").concat(e)}const Ur=Symbol(),Wr=Symbol();var Kr=new WeakMap,Lr=new WeakMap,Mr=new WeakMap,Nr=new WeakMap,zr=new WeakMap,Hr=new WeakMap,Jr=new WeakMap,Zr=new WeakMap,Fr=new WeakMap,Vr=new WeakMap;class qr{constructor(e,t){if(it(this,Kr,void 0),it(this,Lr,void 0),it(this,Mr,void 0),it(this,Nr,void 0),it(this,zr,void 0),it(this,Hr,void 0),it(this,Jr,void 0),it(this,Zr,void 0),it(this,Fr,void 0),it(this,Vr,void 0),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,o;at(Kr,this,new URL(e.href)),at(Lr,this,"number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3),at(Mr,this,"number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4),at(Nr,this,"number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5),at(Jr,this,new Headers(null==t?void 0:t.headers)),Dr&&!rt(Jr,this).has("User-Agent")&&rt(Jr,this).set("User-Agent",Dr),rt(Jr,this).has("accept")||(rt(Jr,this).set("accept","application/json"),rt(Jr,this).append("accept","application/jwk-set+json")),at(Zr,this,null==t?void 0:t[Ur]),void 0!==(null==t?void 0:t[Wr])&&(at(Vr,this,null==t?void 0:t[Wr]),n=null==t?void 0:t[Wr],o=rt(Nr,this),"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=o)&&"jwks"in n&&Po(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,Po)&&(at(zr,this,rt(Vr,this).uat),at(Fr,this,jr(rt(Vr,this).jwks))))}pendingFetch(){return!!rt(Hr,this)}coolingDown(){return"number"==typeof rt(zr,this)&&Date.now()<rt(zr,this)+rt(Mr,this)}fresh(){return"number"==typeof rt(zr,this)&&Date.now()<rt(zr,this)+rt(Nr,this)}jwks(){var e;return null===(e=rt(Fr,this))||void 0===e?void 0:e.jwks()}async getKey(e,t){rt(Fr,this)&&this.fresh()||await this.reload();try{return await rt(Fr,this).call(this,e,t)}catch(n){if(n instanceof go&&!1===this.coolingDown())return await this.reload(),rt(Fr,this).call(this,e,t);throw n}}async reload(){rt(Hr,this)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&at(Hr,this,void 0),rt(Hr,this)||at(Hr,this,async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:fetch;const r=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((e=>{if("TimeoutError"===e.name)throw new bo;throw e}));if(200!==r.status)throw new uo("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch(e){throw new uo("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(rt(Kr,this).href,rt(Jr,this),AbortSignal.timeout(rt(Lr,this)),rt(Zr,this)).then((e=>{at(Fr,this,jr(e)),rt(Vr,this)&&(rt(Vr,this).uat=Date.now(),rt(Vr,this).jwks=e),at(zr,this,Date.now()),at(Hr,this,void 0)})).catch((e=>{throw at(Hr,this,void 0),e}))),await rt(Hr,this)}}const Gr=["mfaToken"],Xr=["mfaToken"];var Br,Yr,Qr,$r,ei,ti,ni,oi,ri,ii,ai,si,ci,ui,li,di,hi=class extends Error{constructor(e,t){super(t),st(this,"code",void 0),this.name="NotSupportedError",this.code=e}},pi=class extends Error{constructor(e,t,n){super(t),st(this,"cause",void 0),st(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},fi=class extends pi{constructor(e,t){super("token_by_code_error",e,t),this.name="TokenByCodeError"}},mi=class extends pi{constructor(e,t){super("token_by_client_credentials_error",e,t),this.name="TokenByClientCredentialsError"}},yi=class extends pi{constructor(e,t){super("token_by_refresh_token_error",e,t),this.name="TokenByRefreshTokenError"}},wi=class extends pi{constructor(e,t){super("token_for_connection_error",e,t),this.name="TokenForConnectionErrorCode"}},gi=class extends pi{constructor(e,t){super("token_exchange_error",e,t),this.name="TokenExchangeError"}},vi=class extends Error{constructor(e){super(e),st(this,"code","verify_logout_token_error"),this.name="VerifyLogoutTokenError"}},bi=class extends pi{constructor(e){super("backchannel_authentication_error","There was an error when trying to use Client-Initiated Backchannel Authentication.",e),st(this,"code","backchannel_authentication_error"),this.name="BackchannelAuthenticationError"}},_i=class extends pi{constructor(e){super("build_authorization_url_error","There was an error when trying to build the authorization URL.",e),this.name="BuildAuthorizationUrlError"}},ki=class extends pi{constructor(e){super("build_link_user_url_error","There was an error when trying to build the Link User URL.",e),this.name="BuildLinkUserUrlError"}},Si=class extends pi{constructor(e){super("build_unlink_user_url_error","There was an error when trying to build the Unlink User URL.",e),this.name="BuildUnlinkUserUrlError"}},Ti=class extends Error{constructor(){super("The client secret or client assertion signing key must be provided."),st(this,"code","missing_client_auth_error"),this.name="MissingClientAuthError"}};function Ei(e){return Object.entries(e).filter((e=>{let[,t]=e;return void 0!==t})).reduce(((e,t)=>ut(ut({},e),{},{[t[0]]:t[1]})),{})}var Pi=class extends Error{constructor(e,t,n){super(t),st(this,"cause",void 0),st(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},Ai=class extends Pi{constructor(e,t){super("mfa_list_authenticators_error",e,t),this.name="MfaListAuthenticatorsError"}},Oi=class extends Pi{constructor(e,t){super("mfa_enrollment_error",e,t),this.name="MfaEnrollmentError"}},Ri=class extends Pi{constructor(e,t){super("mfa_delete_authenticator_error",e,t),this.name="MfaDeleteAuthenticatorError"}},Ci=class extends Pi{constructor(e,t){super("mfa_challenge_error",e,t),this.name="MfaChallengeError"}};function Ii(e){return{id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var xi=(Br=new WeakMap,Yr=new WeakMap,Qr=new WeakMap,class{constructor(e){var t;it(this,Br,void 0),it(this,Yr,void 0),it(this,Qr,void 0),at(Br,this,"https://".concat(e.domain)),at(Yr,this,e.clientId),at(Qr,this,null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)})}async listAuthenticators(e){const t="".concat(rt(Br,this),"/mfa/authenticators"),{mfaToken:n}=e,o=await rt(Qr,this).call(this,t,{method:"GET",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!o.ok){const e=await o.json();throw new Ai(e.error_description||"Failed to list authenticators",e)}return(await o.json()).map(Ii)}async enrollAuthenticator(e){const t="".concat(rt(Br,this),"/mfa/associate"),{mfaToken:n}=e,o=lt(e,Gr),r={authenticator_types:o.authenticatorTypes};"oobChannels"in o&&(r.oob_channels=o.oobChannels),"phoneNumber"in o&&o.phoneNumber&&(r.phone_number=o.phoneNumber),"email"in o&&o.email&&(r.email=o.email);const i=await rt(Qr,this).call(this,t,{method:"POST",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Oi(e.error_description||"Failed to enroll authenticator",e)}return function(e){if("otp"===e.authenticator_type)return{authenticatorType:"otp",secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if("oob"===e.authenticator_type)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 new Error("Unexpected authenticator type: ".concat(e.authenticator_type))}(await i.json())}async deleteAuthenticator(e){const{authenticatorId:t,mfaToken:n}=e,o="".concat(rt(Br,this),"/mfa/authenticators/").concat(encodeURIComponent(t)),r=await rt(Qr,this).call(this,o,{method:"DELETE",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!r.ok){const e=await r.json();throw new Ri(e.error_description||"Failed to delete authenticator",e)}}async challengeAuthenticator(e){const t="".concat(rt(Br,this),"/mfa/challenge"),{mfaToken:n}=e,o=lt(e,Xr),r={mfa_token:n,client_id:rt(Yr,this),challenge_type:o.challengeType};o.authenticatorId&&(r.authenticator_id=o.authenticatorId);const i=await rt(Qr,this).call(this,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Ci(e.error_description||"Failed to challenge authenticator",e)}return function(e){const t={challengeType:e.challenge_type};return void 0!==e.oob_code&&(t.oobCode=e.oob_code),void 0!==e.binding_method&&(t.bindingMethod=e.binding_method),t}(await i.json())}}),ji=class e{constructor(e,t,n,o,r,i,a){st(this,"accessToken",void 0),st(this,"idToken",void 0),st(this,"refreshToken",void 0),st(this,"expiresAt",void 0),st(this,"scope",void 0),st(this,"claims",void 0),st(this,"authorizationDetails",void 0),st(this,"tokenType",void 0),st(this,"issuedTokenType",void 0),this.accessToken=e,this.idToken=n,this.refreshToken=o,this.expiresAt=t,this.scope=r,this.claims=i,this.authorizationDetails=a}static fromTokenEndpointResponse(t){const n=t.id_token?t.claims():void 0,o=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 o.tokenType=t.token_type,o.issuedTokenType=t.issued_token_type,o}},Di=($r=new WeakMap,ei=new WeakMap,ti=new WeakMap,class{constructor(e,t){it(this,$r,new Map),it(this,ei,void 0),it(this,ti,void 0),at(ti,this,Math.max(1,Math.floor(e))),at(ei,this,Math.max(0,Math.floor(t)))}get(e){const t=rt($r,this).get(e);if(t){if(!(Date.now()>=t.expiresAt))return rt($r,this).delete(e),rt($r,this).set(e,t),t.value;rt($r,this).delete(e)}}set(e,t){for(rt($r,this).has(e)&&rt($r,this).delete(e),rt($r,this).set(e,{value:t,expiresAt:Date.now()+rt(ei,this)});rt($r,this).size>rt(ti,this);){const e=rt($r,this).keys().next().value;if(void 0===e)break;rt($r,this).delete(e)}}}),Ui=new Map;function Wi(e){return{ttlMs:1e3*("number"==typeof(null==e?void 0:e.ttl)?e.ttl:600),maxEntries:"number"==typeof(null==e?void 0:e.maxEntries)&&e.maxEntries>0?e.maxEntries:100}}var Ki=class{static createDiscoveryCache(e){const t=(n=e.maxEntries,o=e.ttlMs,"".concat(n,":").concat(o));var n,o;let r=(i=t,Ui.get(i));var i;return r||(r=new Di(e.maxEntries,e.ttlMs),Ui.set(t,r)),r}static createJwksCache(){return{}}},Li="openid profile email offline_access",Mi=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 Ni(e){if(null==e)throw new gi("subject_token is required");if("string"!=typeof e)throw new gi("subject_token must be a string");if(0===e.trim().length)throw new gi("subject_token cannot be blank or whitespace");if(e!==e.trim())throw new gi("subject_token must not include leading or trailing whitespace");if(/^bearer\s+/i.test(e))throw new gi("subject_token must not include the 'Bearer ' prefix")}function zi(e,t){if(t)for(const[n,o]of Object.entries(t))if(!Mi.has(n))if(Array.isArray(o)){if(o.length>20)throw new gi("Parameter '".concat(n,"' exceeds maximum array size of ").concat(20));o.forEach((t=>{e.append(n,t)}))}else e.append(n,o)}var Hi="urn:ietf:params:oauth:token-type:access_token",Ji=(ni=new WeakMap,oi=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap,si=new WeakMap,ci=new WeakMap,ui=new WeakMap,li=new WeakMap,di=new WeakSet,class{constructor(e){var t,n,o,r;if(function(e,t){ot(e,t),t.add(e)}(this,di),it(this,ni,void 0),it(this,oi,void 0),it(this,ri,void 0),it(this,ii,void 0),it(this,ai,void 0),it(this,si,void 0),it(this,ci,void 0),it(this,ui,void 0),it(this,li,void 0),st(this,"mfa",void 0),at(ii,this,e),e.useMtls&&!e.customFetch)throw new hi("mtls_without_custom_fetch_not_supported","Using mTLS without a custom fetch implementation is not supported");at(ai,this,function(e,t){if(!1===t.enabled)return e;const n={name:t.name,version:t.version},o=btoa(JSON.stringify(n));return async(t,n)=>{const r=t instanceof Request?new Headers(t.headers):new Headers;return null!=n&&n.headers&&new Headers(n.headers).forEach(((e,t)=>{r.set(t,e)})),r.set("Auth0-Client",o),e(t,ut(ut({},n),{},{headers:r}))}}(null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)},!1===(null==(n=e.telemetry)?void 0:n.enabled)?n:{enabled:!0,name:null!==(o=null==n?void 0:n.name)&&void 0!==o?o:"@auth0/auth0-auth-js",version:null!==(r=null==n?void 0:n.version)&&void 0!==r?r:"1.5.0"}));const i=Wi(e.discoveryCache);at(ci,this,Ki.createDiscoveryCache(i)),at(ui,this,new Map),at(li,this,Ki.createJwksCache()),this.mfa=new xi({domain:rt(ii,this).domain,clientId:rt(ii,this).clientId,customFetch:rt(ai,this)})}async getServerMetadata(){const{serverMetadata:e}=await tt(di,this,Vi).call(this);return e}async buildAuthorizationUrl(e){const{serverMetadata:t}=await tt(di,this,Vi).call(this);if(null!=e&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new hi("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 tt(di,this,Bi).call(this,e)}catch(e){throw new _i(e)}}async buildLinkUserUrl(e){try{const t=await tt(di,this,Bi).call(this,{authorizationParams:ut(ut({},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 ki(e)}}async buildUnlinkUserUrl(e){try{const t=await tt(di,this,Bi).call(this,{authorizationParams:ut(ut({},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 Si(e)}}async backchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await tt(di,this,Vi).call(this),o=Ei(ut(ut({},rt(ii,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ut(ut({scope:Li},o),{},{client_id:rt(ii,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await cr(t,r),n=await ur(t,e);return ji.fromTokenEndpointResponse(n)}catch(e){throw new bi(e)}}async initiateBackchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await tt(di,this,Vi).call(this),o=Ei(ut(ut({},rt(ii,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ut(ut({scope:Li},o),{},{client_id:rt(ii,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await cr(t,r);return{authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new bi(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e;const{configuration:n}=await tt(di,this,Vi).call(this),o=new URLSearchParams({auth_req_id:t});try{const e=await br(n,"urn:openid:params:grant-type:ciba",o);return ji.fromTokenEndpointResponse(e)}catch(e){throw new bi(e)}}async getTokenForConnection(e){var t;if(e.refreshToken&&e.accessToken)throw new wi("Either a refresh or access token should be specified, but not both.");const n=null!==(t=e.accessToken)&&void 0!==t?t:e.refreshToken;if(!n)throw new wi("Either a refresh or access token must be specified.");try{return await this.exchangeToken({connection:e.connection,subjectToken:n,subjectTokenType:e.accessToken?Hi:"urn:ietf:params:oauth:token-type:refresh_token",loginHint:e.loginHint})}catch(e){if(e instanceof gi)throw new wi(e.message,e.cause);throw e}}async exchangeToken(e){return"connection"in e?tt(di,this,qi).call(this,e):tt(di,this,Gi).call(this,e)}async getTokenByCode(e,t){const{configuration:n}=await tt(di,this,Vi).call(this);try{const o=await dr(n,e,{pkceCodeVerifier:t.codeVerifier});return ji.fromTokenEndpointResponse(o)}catch(e){throw new fi("There was an error while trying to request a token.",e)}}async getTokenByRefreshToken(e){const{configuration:t}=await tt(di,this,Vi).call(this),n=new URLSearchParams;e.audience&&n.append("audience",e.audience),e.scope&&n.append("scope",e.scope);try{const o=await hr(t,e.refreshToken,n);return ji.fromTokenEndpointResponse(o)}catch(e){throw new yi("The access token has expired and there was an error while trying to refresh it.",e)}}async getTokenByClientCredentials(e){const{configuration:t}=await tt(di,this,Vi).call(this);try{const n=new URLSearchParams({audience:e.audience});e.organization&&n.append("organization",e.organization);const o=await pr(t,n);return ji.fromTokenEndpointResponse(o)}catch(e){throw new mi("There was an error while trying to request a token.",e)}}async buildLogoutUrl(e){const{configuration:t,serverMetadata:n}=await tt(di,this,Vi).call(this);if(!n.end_session_endpoint){const t=new URL("https://".concat(rt(ii,this).domain,"/v2/logout"));return t.searchParams.set("returnTo",e.returnTo),t.searchParams.set("client_id",rt(ii,this).clientId),t}return function(e,t){yr(e);const{as:n,c:o,tlsOnly:r}=Fo(e),i=$t(n,"end_session_endpoint",!1,r);(t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id);for(const[e,n]of t.entries())i.searchParams.append(e,n);return i}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){const{serverMetadata:t}=await tt(di,this,Vi).call(this),n=Wi(rt(ii,this).discoveryCache),o=t.jwks_uri;rt(si,this)||at(si,this,function(e,t){const n=new qr(e,t),o=async(e,t)=>n.getKey(e,t);return Object.defineProperties(o,{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}}),o}(new URL(o),{cacheMaxAge:n.ttlMs,[Ur]:rt(ai,this),[Wr]:rt(li,this)}));const{payload:r}=await async function(e,t,n){var o;const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=eo.decode(e)),"string"!=typeof e)throw new mo("Compact JWS must be a string or Uint8Array");const{0:o,1:r,2:i,length:a}=e.split(".");if(3!==a)throw new mo("Invalid Compact JWS");const s=await _r({payload:r,protected:o,signature:i},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?ut(ut({},c),{},{key:s.key}):c}(e,t,n);if(null!==(o=r.protectedHeader.crit)&&void 0!==o&&o.includes("b64")&&!1===r.protectedHeader.b64)throw new yo("JWTs MUST NOT use unencoded payload");const i={payload:Er(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return"function"==typeof t?ut(ut({},i),{},{key:r.key}):i}(e.logoutToken,rt(si,this),{issuer:t.issuer,audience:rt(ii,this).clientId,algorithms:["RS256"],requiredClaims:["iat"]});if(!("sid"in r)&&!("sub"in r))throw new vi('either "sid" or "sub" (or both) claims must be present');if("sid"in r&&"string"!=typeof r.sid)throw new vi('"sid" claim must be a string');if("sub"in r&&"string"!=typeof r.sub)throw new vi('"sub" claim must be a string');if("nonce"in r)throw new vi('"nonce" claim is prohibited');if(!("events"in r))throw new vi('"events" claim is missing');if("object"!=typeof r.events||null===r.events)throw new vi('"events" claim must be an object');if(!("http://schemas.openid.net/event/backchannel-logout"in r.events))throw new vi('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');if("object"!=typeof r.events["http://schemas.openid.net/event/backchannel-logout"])throw new vi('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');return{sid:r.sid,sub:r.sub}}});function Zi(){const e=rt(ii,this).domain.toLowerCase();return"".concat(e,"|mtls:").concat(rt(ii,this).useMtls?"1":"0")}async function Fi(e){const t=await tt(di,this,Xi).call(this),n=new rr(e,rt(ii,this).clientId,rt(ii,this).clientSecret,t);return n[Xo]=rt(ai,this),n}async function Vi(){if(rt(ni,this)&&rt(oi,this))return{configuration:rt(ni,this),serverMetadata:rt(oi,this)};const e=tt(di,this,Zi).call(this),t=rt(ci,this).get(e);if(t)return at(oi,this,t.serverMetadata),at(ni,this,await tt(di,this,Fi).call(this,t.serverMetadata)),{configuration:rt(ni,this),serverMetadata:rt(oi,this)};const n=rt(ui,this).get(e);if(n){const e=await n;return at(oi,this,e.serverMetadata),at(ni,this,await tt(di,this,Fi).call(this,e.serverMetadata)),{configuration:rt(ni,this),serverMetadata:rt(oi,this)}}const o=(async()=>{const t=await tt(di,this,Xi).call(this),n=await nr(new URL("https://".concat(rt(ii,this).domain)),rt(ii,this).clientId,{use_mtls_endpoint_aliases:rt(ii,this).useMtls},t,{[Xo]:rt(ai,this)}),o=n.serverMetadata();return rt(ci,this).set(e,{serverMetadata:o}),{configuration:n,serverMetadata:o}})(),r=o.then((e=>{let{serverMetadata:t}=e;return{serverMetadata:t}}));r.catch((()=>{})),rt(ui,this).set(e,r);try{const{configuration:e,serverMetadata:t}=await o;at(ni,this,e),at(oi,this,t),rt(ni,this)[Xo]=rt(ai,this)}finally{rt(ui,this).delete(e)}return{configuration:rt(ni,this),serverMetadata:rt(oi,this)}}async function qi(e){var t,n;const{configuration:o}=await tt(di,this,Vi).call(this);if("audience"in e||"resource"in e)throw new gi("audience and resource parameters are not supported for Token Vault exchanges");Ni(e.subjectToken);const r=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:null!==(t=e.subjectTokenType)&&void 0!==t?t:Hi,requested_token_type:null!==(n=e.requestedTokenType)&&void 0!==n?n:"http://auth0.com/oauth/token-type/federated-connection-access-token"});e.loginHint&&r.append("login_hint",e.loginHint),e.scope&&r.append("scope",e.scope),zi(r,e.extra);try{const e=await br(o,"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token",r);return ji.fromTokenEndpointResponse(e)}catch(t){throw new gi("Failed to exchange token for connection '".concat(e.connection,"'."),t)}}async function Gi(e){const{configuration:t}=await tt(di,this,Vi).call(this);Ni(e.subjectToken);const 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),zi(n,e.extra);try{const e=await br(t,"urn:ietf:params:oauth:grant-type:token-exchange",n);return ji.fromTokenEndpointResponse(e)}catch(t){throw new gi("Failed to exchange token of type '".concat(e.subjectTokenType,"'").concat(e.audience?" for audience '".concat(e.audience,"'"):"","."),t)}}async function Xi(){return rt(ri,this)||at(ri,this,(async()=>{if(!rt(ii,this).clientSecret&&!rt(ii,this).clientAssertionSigningKey&&!rt(ii,this).useMtls)throw new Ti;if(rt(ii,this).useMtls)return(e,t,n,o)=>{n.set("client_id",t.client_id)};let e=rt(ii,this).clientAssertionSigningKey;return!e||e instanceof CryptoKey||(e=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Lo(e,t,void 0)}(e,rt(ii,this).clientAssertionSigningAlg||"RS256")),e?function(e){return Xt(e,void 0)}(e):Go(rt(ii,this).clientSecret)})().catch((e=>{throw at(ri,this,void 0),e}))),rt(ri,this)}async function Bi(e){const{configuration:t}=await tt(di,this,Vi).call(this),n=zt(),o=await function(e){return async function(e){return Mt(e,"codeVerifier"),Ct(await crypto.subtle.digest("SHA-256",At(e)))}(e)}(n),r=Ei(ut(ut({},rt(ii,this).authorizationParams),null==e?void 0:e.authorizationParams)),i=new URLSearchParams(ut(ut({scope:Li},r),{},{client_id:rt(ii,this).clientId,code_challenge:o,code_challenge_method:"S256"}));return{authorizationUrl:null!=e&&e.pushedAuthorizationRequests?await mr(t,i):await fr(t,i),codeVerifier:n}}class Yi extends p{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Yi.prototype)}static fromPayload(e){let{error:t,error_description:n}=e;return new Yi(t,n)}}class Qi extends Yi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Qi.prototype)}}class $i extends Yi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,$i.prototype)}}class ea extends Yi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ea.prototype)}}class ta extends Yi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ta.prototype)}}class na extends Yi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,na.prototype)}}class oa{constructor(){let e=arguments.length>0&&void 0!==arguments[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){const 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(){const e=Date.now();for(const[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t)}get size(){return this.contexts.size}}class ra{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new oa}setMFAAuthDetails(e,t,n,o){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:o})}async getAuthenticators(e){var t,n;const o=this.contextManager.get(e);if(!(null===(t=null==o?void 0:o.mfaRequirements)||void 0===t?void 0:t.challenge)||0===o.mfaRequirements.challenge.length)throw new Qi("invalid_request","challengeType is required and must contain at least one challenge type, please check mfa_required error payload");const r=o.mfaRequirements.challenge.map((e=>e.type));try{return(await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter((e=>!!e.type&&r.includes(e.type)))}catch(e){if(e instanceof Ai)throw new Qi(null===(n=e.cause)||void 0===n?void 0:n.error,e.message);throw e}}async enroll(e){var t;const n=function(e){const t=$e[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(n)}catch(e){if(e instanceof Oi)throw new $i(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async challenge(e){var t;try{const t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){if(e instanceof Ci)throw new ea(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async getEnrollmentFactors(e){const t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new na("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&&0!==t.mfaRequirements.enroll.length?t.mfaRequirements.enroll:[]}async verify(e){const t=this.contextManager.get(e.mfaToken);if(!t)throw new ta("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");const n=function(e){return"otp"in e&&e.otp?"http://auth0.com/oauth/grant-type/mfa-otp":"oobCode"in e&&e.oobCode?"http://auth0.com/oauth/grant-type/mfa-oob":"recoveryCode"in e&&e.recoveryCode?"http://auth0.com/oauth/grant-type/mfa-recovery-code":void 0}(e);if(!n)throw new ta("invalid_request","Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");const o=t.scope,r=t.audience;try{const t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:o,audience:r,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 b)this.setMFAAuthDetails(e.mfa_token,o,r,e.mfa_requirements);else if(e instanceof ta)throw new ta(e.error,e.error_description);throw e}}}class ia{constructor(e){let t,n;if(this.userCache=(new ke).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)}),"undefined"!=typeof window&&(()=>{if(!E())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===E().subtle)throw new Error("\n 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.\n ")})(),this.lockManager=(B||(B=function(){return"undefined"!=typeof navigator&&"function"==typeof(null===(e=navigator.locks)||void 0===e?void 0:e.request)?new G:new X;var e}()),B),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||u,!Je(t))throw new Error('Invalid cache location "'.concat(t,'"'));n=Je(t)()}var o;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?je:Ue,this.orgHintCookieName=(o=this.options.clientId,"auth0.".concat(o,".organization_hint")),this.isAuthenticatedCookieName=(e=>"auth0.".concat(e,".is.authenticated"))(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const r=e.useCookiesForTransactions?this.cookieStorage:We;var i;this.scope=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if("object"!=typeof e)return{[h]:ye(t,e,...o)};let i={[h]:ye(t,...o)};return Object.keys(e).forEach((n=>{const r=e[n];i[n]=ye(t,r,...o)})),i}(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new Te(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||d,this.cacheManager=new Se(n,n.allKeys?void 0:new Ne(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ge(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:"https://".concat(i)),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:"https://".concat(e,"/"):"".concat(t,"/"))(this.options.issuer,this.domainUrl);const a="".concat(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:a},detailedResponse:!0})}));this.myAccountApi=new Ye(s,a),this.authJsClient=new Ji({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new ra(this.authJsClient.mfa,this),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&t===u&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new Le)}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){const t=this.options.auth0Client||l,n=R(t,!0),o=encodeURIComponent(btoa(JSON.stringify(n)));return"".concat(this.domainUrl).concat(e,"&auth0Client=").concat(o)}_authorizeUrl(e){return this._url("/authorize?".concat(C(e)))}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return(e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(x(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],Pe.includes(e)||(s[e]=i[e])})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(x(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(e.iss,'", found "').concat(t.claims.iss,'"'));if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error('Signature algorithm of "'.concat(t.header.alg,'" is not supported. Expected the ID token to be signed with "RS256".'));if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new 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 new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but was not one of "').concat(t.claims.aud.join(", "),'"'));if(t.claims.aud.length>1){if(!t.claims.azp)throw new 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 new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(e.aud,'", found "').concat(t.claims.azp,'"'))}}else if(t.claims.aud!==e.aud)throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but found "').concat(t.claims.aud,'"'));if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(e.nonce,'", found "').concat(t.claims.nonce,'"'))}if(e.max_age&&!Ee(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!Ee(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!Ee(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(o,") is after expiration time (").concat(r,")"));if(null!=t.claims.nbf&&Ee(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(o,") is before ").concat(e))}if(null!=t.claims.auth_time&&Ee(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new 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 (".concat(o,") is after last auth at ").concat(r))}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_id,'"'))}else{const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_name,'"'))}}return t})({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r}_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{const t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState({},"",t.toString()))}catch(e){}}_applySessionTransferToken(e){const t=this.options.sessionTransferTokenQueryParamName;if(!t||e.session_transfer_token)return e;const n=this._extractSessionTransferToken(t);return n?(this._clearSessionTransferTokenFromUrl(t),Object.assign(Object.assign({},e),{session_transfer_token:n})):e}async _prepareAuthorizeUrl(e,t,n){var o;const r=A(P()),i=A(P()),a=P(),s=await I(a),c=j(s),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),l=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:we(t,n.scope,n.audience),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),d=this._authorizeUrl(l);return{nonce:i,code_verifier:a,scope:l.scope,audience:l.audience||h,redirect_uri:l.redirect_uri,state:r,url:d}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(()=>{const e=window.screenX+(window.innerWidth-400)/2,t=window.screenY+(window.innerHeight-600)/2;return window.open("","auth0:authorize:popup","left=".concat(e,",top=").concat(t,",width=").concat(400,",height=").concat(600,",resizable,scrollbars=yes,status=1"))})(),!t.popup))throw new v;const o=this._applySessionTransferToken(e.authorizationParams||{}),r=await this._prepareAuthorizeUrl(o,{response_mode:"web_message"},window.location.origin);t.popup.location.href=r.url;const i=await(e=>new Promise(((t,n)=>{let o;const r=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(r),clearTimeout(i),window.removeEventListener("message",o,!1),n(new g(e.popup)))}),1e3),i=setTimeout((()=>{clearInterval(r),n(new w(e.popup)),window.removeEventListener("message",o,!1)}),1e3*(e.timeoutInSeconds||60));o=function(a){if(a.data&&"authorization_response"===a.data.type){if(clearTimeout(i),clearInterval(r),window.removeEventListener("message",o,!1),!1!==e.closePopup&&e.popup.close(),a.data.response.error)return n(p.fromPayload(a.data.response));t(a.data.response)}},window.addEventListener("message",o)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(r.state!==i.state)throw new p("state_mismatch","Invalid state");const a=(null===(n=e.authorizationParams)||void 0===n?void 0:n.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(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(){var t;const n=Ze(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{openUrl:o,fragment:r,appState:i}=n,a=s(n,["openUrl","fragment","appState"]),c=(null===(t=a.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,u=this._applySessionTransferToken(a.authorizationParams||{}),l=await this._prepareAuthorizeUrl(u),{url:d}=l,h=s(l,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},h),{appState:i,response_type:e.ResponseType.Code}),c&&{organization:c}));const p=r?"".concat(d,"#").concat(r):d;o?await o(p):window.location.assign(p)}async handleRedirectCallback(){const t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.href).split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const n=this.transactionManager.get();if(!n)throw new p("missing_transaction","Invalid state");this.transactionManager.remove();const o=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const 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}})(t.join(""));return n.response_type===e.ResponseType.ConnectCode?this._handleConnectAccountRedirectCallback(o,n):this._handleLoginRedirectCallback(o,n)}async _handleLoginRedirectCallback(t,n){const{code:o,state:r,error:i,error_description:a}=t;if(i)throw new f(i,a||i,r,n.appState);if(!n.code_verifier||n.state&&n.state!==r)throw new p("state_mismatch","Invalid state");const s=n.organization,c=n.nonce,u=n.redirect_uri;return await this._requestToken(Object.assign({audience:n.audience,scope:n.scope,code_verifier:n.code_verifier,grant_type:"authorization_code",code:o},u?{redirect_uri:u}:{}),{nonceIn:c,organization:s}),{appState:n.appState,response_type:e.ResponseType.Code}}async _handleConnectAccountRedirectCallback(t,n){const{connect_code:o,state:r,error:i,error_description:a}=t;if(i)throw new m(i,a||i,n.connection,r,n.appState);if(!o)throw new p("missing_connect_code","Missing connect code");if(!(n.code_verifier&&n.state&&n.auth_session&&n.redirect_uri&&n.state===r))throw new p("state_mismatch","Invalid state");const s=await this.myAccountApi.completeAccount({auth_session:n.auth_session,connect_code:o,redirect_uri:n.redirect_uri,code_verifier:n.code_verifier});return Object.assign(Object.assign({},s),{appState:n.appState,response_type:e.ResponseType.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get(ze))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(ze)}try{await this.getTokenSilently(e)}catch(e){}}async getTokenSilently(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,n;const o=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:we(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,(null===(n=e.authorizationParams)||void 0===n?void 0:n.audience)||this.options.authorizationParams.audience)})}),r=await((e,t)=>{let n=Me[t];return n||(n=e().finally((()=>{delete Me[t],n=null})),Me[t]=n),n})((()=>this._getTokenSilently(o)),"".concat(this.options.clientId,"::").concat(o.authorizationParams.audience,"::").concat(o.authorizationParams.scope));return e.detailedResponse?r:null==r?void 0:r.access_token}async _getTokenSilently(e){const{cacheMode:t}=e,n=s(e,["cacheMode"]);if("off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||h,clientId:this.options.clientId,cacheMode:t});if(e)return e}if("cache-only"===t)return;const o=(r=this.options.clientId,i=n.authorizationParams.audience||"default","".concat("auth0.lock.getTokenSilently",".").concat(r,".").concat(i));var r,i;try{return await this.lockManager.runWithLock(o,5e3,(async()=>{if("off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||h,clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(n):await this._getTokenFromIFrame(n),{id_token:o,token_type:r,access_token:i,oauthTokenScope:a,expires_in:s}=e;return Object.assign(Object.assign({id_token:o,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:s})}))}catch(e){if(this._isInteractiveError(e)&&"popup"===this.options.interactiveErrorHandler)return await this._handleInteractiveErrorWithPopup(n);throw e}}_isInteractiveError(e){return e instanceof b||e instanceof p&&this._isIframeMfaError(e)}_isIframeMfaError(e){return"login_required"===e.error&&"Multifactor authentication required"===e.error_description}async _handleInteractiveErrorWithPopup(e){try{await this.loginWithPopup({authorizationParams:e.authorizationParams});const t=await this._getEntryFromCache({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||h,clientId:this.options.clientId});if(!t)throw new p("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&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,o;const r=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:we(this.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.scope,(null===(o=e.authorizationParams)||void 0===o?void 0:o.audience)||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},c),t),await this.loginWithPopup(r,t),(await this.cacheManager.get(new be({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||h,clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){null!==e.clientId?e.clientId=e.clientId||this.options.clientId:delete e.clientId;const t=e.logoutParams||{},{federated:n}=t,o=s(t,["federated"]),r=n?"&federated":"";return this._url("/v2/logout?".concat(C(Object.assign({clientId:e.clientId},o))))+r}async logout(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t;const n=Ze(e),{openUrl:o}=n,r=s(n,["openUrl"]);null===e.clientId?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(ve),await(null===(t=this.dpop)||void 0===t?void 0:t.clear());const i=this._buildLogoutUrl(r);o?await o(i):!1!==o&&window.location.assign(i)}async _getTokenFromIFrame(e){const t=(n=this.options.clientId,"".concat("auth0.lock.getTokenFromIFrame",".").concat(n));var n;try{return await this.lockManager.runWithLock(t,5e3,(async()=>{const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:r,nonce:i,code_verifier:a,redirect_uri:s,scope:c,audience:u}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new p("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const l=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let d;try{d=new URL(this.domainUrl).origin}catch(e){d=this.domainUrl}const h=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;return new Promise(((o,r)=>{const i=window.document.createElement("iframe");i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.display="none";const a=()=>{window.document.body.contains(i)&&(window.document.body.removeChild(i),window.removeEventListener("message",s,!1))};let s;const c=setTimeout((()=>{r(new y),a()}),1e3*n);s=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?r(p.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",s,!1),setTimeout(a,2e3)},window.addEventListener("message",s,!1),window.document.body.appendChild(i),i.setAttribute("src",e)}))}(o,d,l);if(r!==h.state)throw new p("state_mismatch","Invalid state");const f=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:a,code:h.code,grant_type:"authorization_code",redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:i,organization:t.organization});return Object.assign(Object.assign({},f),{scope:c,oauthTokenScope:f.scope,audience:u})}))}catch(e){throw"login_required"===e.error&&(e instanceof p&&this._isIframeMfaError(e)&&"popup"===this.options.interactiveErrorHandler||this.logout({openUrl:!1})),e}}async _getTokenUsingRefreshToken(e){var t,n;const o=await this.cacheManager.get(new be({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||h,clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(o&&o.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new _(e.authorizationParams.audience||h,e.authorizationParams.scope)}const r=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null,a=((e,t,n,o)=>{var r;if(e&&n&&o){if(t.audience!==n)return t.scope;const e=o.split(" "),i=(null===(r=t.scope)||void 0===r?void 0:r.split(" "))||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?o:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,null==o?void 0:o.audience,null==o?void 0:o.scope);try{const t=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:o&&o.refresh_token,redirect_uri:r}),i&&{timeout:i}),{scopesToRequest:a});if(t.refresh_token&&(null==o?void 0:o.refresh_token)&&await this.cacheManager.updateEntry(o.refresh_token,t.refresh_token),this.options.useMrrt&&!(s=null==o?void 0:o.audience,c=null==o?void 0:o.scope,u=e.authorizationParams.audience,l=e.authorizationParams.scope,s===u&&Fe(l,c)||Fe(a,t.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const n=((e,t)=>{const n=(null==e?void 0:e.split(" "))||[],o=(null==t?void 0:t.split(" "))||[];return n.filter((e=>-1==o.indexOf(e))).join(",")})(a,t.scope);throw new k(e.authorizationParams.audience||"default",n)}return Object.assign(Object.assign({},t),{scope:e.authorizationParams.scope,oauthTokenScope:t.scope,audience:e.authorizationParams.audience||h})}catch(o){if(o.message){if(o.message.includes("user is blocked"))throw await this.logout({openUrl:!1}),o;if((o.message.includes("Missing Refresh Token")||o.message.includes("invalid refresh token"))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw o instanceof b&&this.mfa.setMFAAuthDetails(o.mfa_token,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.audience,o.mfa_requirements),o}var s,c,u,l}async _saveEntryInCache(e){const{id_token:t,decodedToken:n}=e,o=s(e,["id_token","decodedToken"]);this.userCache.set(ve,{id_token:t,decodedToken:n}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(o)}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||h,t=this.scope[e],n=await this.cacheManager.getIdToken(new be({clientId:this.options.clientId,audience:e,scope:t})),o=this.userCache.get(ve);return n&&n.id_token===(null==o?void 0:o.id_token)?o:(this.userCache.set(ve,n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:o,cacheMode:r}=e;const i=await this.cacheManager.get(new be({scope:t,audience:n,clientId:o}),60,this.options.useMrrt,r);if(i&&i.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:o}=i,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:o})}}async _requestToken(e,t){var n,o;const{nonceIn:r,organization:i,scopesToRequest:a}=t||{},s=await me(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),c=await this._verifyIdToken(s.id_token,r,i);if("authorization_code"===e.grant_type){const e=await this._getIdTokenFromCache();(null===(o=null===(n=null==e?void 0:e.decodedToken)||void 0===n?void 0:n.claims)||void 0===o?void 0:o.sub)&&e.decodedToken.claims.sub!==c.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove(ve))}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},s),{decodedToken:c,scope:e.scope,audience:e.audience||h}),s.scope?{oauthTokenScope:s.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||c.claims.org_id),Object.assign(Object.assign({},s),{decodedToken:c})}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:we(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 new 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&&void 0!==arguments[0]?arguments[0]:{};return new Be(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>{var t;return this.getTokenSilently({authorizationParams:{scope:null===(t=null==e?void 0:e.scope)||void 0===t?void 0:t.join(" "),audience:null==e?void 0:e.audience},detailedResponse:!0})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(t){const{openUrl:n,appState:o,connection:r,scopes:i,authorization_params:a,redirectUri:s=this.options.authorizationParams.redirect_uri||window.location.origin}=t;if(!r)throw new Error("connection is required");const c=A(P()),u=P(),l=await I(u),d=j(l),{connect_uri:h,connect_params:p,auth_session:f}=await this.myAccountApi.connectAccount({connection:r,scopes:i,redirect_uri:s,state:c,code_challenge:d,code_challenge_method:"S256",authorization_params:a});this.transactionManager.create({state:c,code_verifier:u,auth_session:f,redirect_uri:s,appState:o,connection:r,response_type:e.ResponseType.ConnectCode});const m=new URL(h);m.searchParams.set("ticket",p.ticket),n?await n(m.toString()):window.location.assign(m)}async _requestTokenForMfa(e,t){const{mfaToken:n}=e,o=s(e,["mfaToken"]);return this._requestToken(Object.assign(Object.assign({},o),{mfa_token:n}),t)}}var aa={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},sa=function(){throw new Error("You forgot to wrap your component in <Auth0Provider>.")},ca=o(o({},aa),{buildAuthorizeUrl:sa,buildLogoutUrl:sa,getAccessTokenSilently:sa,getAccessTokenWithPopup:sa,getIdTokenClaims:sa,loginWithCustomTokenExchange:sa,exchangeToken:sa,loginWithRedirect:sa,loginWithPopup:sa,connectAccountWithRedirect:sa,logout:sa,handleRedirectCallback:sa,getDpopNonce:sa,setDpopNonce:sa,generateDpopProof:sa,createFetcher:sa,getConfiguration:sa,mfa:{getAuthenticators:sa,enroll:sa,challenge:sa,verify:sa,getEnrollmentFactors:sa}}),ua=t.createContext(ca),la=function(e){function t(n,o){var r=e.call(this,null!=o?o:n)||this;return r.error=n,r.error_description=o,Object.setPrototypeOf(r,t.prototype),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}(t,e),t}(Error),da=/[?&](?:connect_)?code=[^&]+/,ha=/[?&]state=[^&]+/,pa=/[?&]error=[^&]+/,fa=function(e){return function(t){if(t instanceof Error)return t;if(null!==t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error){if("error_description"in t&&"string"==typeof t.error_description){var n=t;return new la(n.error,n.error_description)}return new la(t.error)}return new Error(e)}},ma=fa("Login failed"),ya=fa("Get access token failed"),wa=function(e){var t,n;(null==e?void 0: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=null!==(t=e.authorizationParams)&&void 0!==t?t:{},e.authorizationParams.redirect_uri=e.redirectUri,delete e.redirectUri),(null===(n=null==e?void 0:e.authorizationParams)||void 0===n?void 0:n.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)},ga=function(e,t){switch(t.type){case"LOGIN_POPUP_STARTED":return o(o({},e),{isLoading:!0});case"LOGIN_POPUP_COMPLETE":case"INITIALISED":return o(o({},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:o(o({},e),{isAuthenticated:!!t.user,user:t.user});case"LOGOUT":return o(o({},e),{isAuthenticated:!1,user:void 0});case"ERROR":return o(o({},e),{isLoading:!1,error:t.error})}},va=function(e){var t;window.history.replaceState({},document.title,null!==(t=e.returnTo)&&void 0!==t?t:window.location.pathname)},ba=function(e){return void 0===e&&(e=ua),t.useContext(e)},_a=function(){return t.createElement(t.Fragment,null)},ka=function(){return i(void 0,void 0,void 0,(function(){return a(this,(function(e){return[2]}))}))},Sa=function(){return"".concat(window.location.pathname).concat(window.location.search)};e.Auth0Context=ua,e.Auth0Provider=function(n){var s=n,c=s.children,u=s.skipRedirectCallback,l=s.onRedirectCallback,d=void 0===l?va:l,h=s.context,p=void 0===h?ua:h,f=s.client,m=r(s,["children","skipRedirectCallback","onRedirectCallback","context","client"]);f&&(m.domain||m.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 y=t.useState((function(){return null!=f?f:new ia(function(e){return wa(e),o(o({},e),{auth0Client:{name:"auth0-react",version:"2.16.0"}})}(m))}))[0],w=t.useReducer(ga,aa),g=w[0],v=w[1],b=t.useRef(!1),_=t.useCallback((function(e){return v({type:"ERROR",error:e}),e}),[]);t.useEffect((function(){b.current||(b.current=!0,i(void 0,void 0,void 0,(function(){var t,n,o,i,s,c,l;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,7,,8]),t=void 0,void 0===h&&(h=window.location.search),!da.test(h)&&!pa.test(h)||!ha.test(h)||u?[3,3]:[4,y.handleRedirectCallback()];case 1:return n=a.sent(),o=n.appState,i=void 0===o?{}:o,s=n.response_type,c=r(n,["appState","response_type"]),[4,y.getUser()];case 2:return t=a.sent(),i.response_type=s,s===e.ResponseType.ConnectCode&&(i.connectedAccount=c),d(i,t),[3,6];case 3:return[4,y.checkSession()];case 4:return a.sent(),[4,y.getUser()];case 5:t=a.sent(),a.label=6;case 6:return v({type:"INITIALISED",user:t}),[3,8];case 7:return l=a.sent(),_(ma(l)),[3,8];case 8:return[2]}var h}))})))}),[y,d,u,_]);var k=t.useCallback((function(e){return wa(e),y.loginWithRedirect(e)}),[y]),S=t.useCallback((function(e,t){return i(void 0,void 0,void 0,(function(){var n,o;return a(this,(function(r){switch(r.label){case 0:v({type:"LOGIN_POPUP_STARTED"}),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,y.loginWithPopup(e,t)];case 2:return r.sent(),[3,4];case 3:return n=r.sent(),_(ma(n)),[2];case 4:return[4,y.getUser()];case 5:return o=r.sent(),v({type:"LOGIN_POPUP_COMPLETE",user:o}),[2]}}))}))}),[y,_]),T=t.useCallback((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i(void 0,function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0),void 0,(function(e){return void 0===e&&(e={}),a(this,(function(t){switch(t.label){case 0:return[4,y.logout(e)];case 1:return t.sent(),(e.openUrl||!1===e.openUrl)&&v({type:"LOGOUT"}),[2]}}))}))}),[y]),E=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o,r;return a(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,y.getTokenSilently(e)];case 1:return t=i.sent(),[3,5];case 2:throw n=i.sent(),ya(n);case 3:return o=v,r={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,y.getUser()];case 4:return o.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2,t]}}))}))}),[y]),P=t.useCallback((function(e,t){return i(void 0,void 0,void 0,(function(){var n,o,r,i;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,y.getTokenWithPopup(e,t)];case 1:return n=a.sent(),[3,5];case 2:throw o=a.sent(),ya(o);case 3:return r=v,i={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,y.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,n]}}))}))}),[y]),A=t.useCallback((function(e){return y.connectAccountWithRedirect(e)}),[y]),O=t.useCallback((function(){return y.getIdTokenClaims()}),[y]),R=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o,r;return a(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,y.loginWithCustomTokenExchange(e)];case 1:return t=i.sent(),[3,5];case 2:throw n=i.sent(),ya(n);case 3:return o=v,r={type:"GET_ACCESS_TOKEN_COMPLETE"},[4,y.getUser()];case 4:return o.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2,t]}}))}))}),[y]),C=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){return a(this,(function(t){return[2,R(e)]}))}))}),[R]),I=t.useCallback((function(e){return i(void 0,void 0,void 0,(function(){var t,n,o;return a(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,3,5]),[4,y.handleRedirectCallback(e)];case 1:return[2,r.sent()];case 2:throw t=r.sent(),ya(t);case 3:return n=v,o={type:"HANDLE_REDIRECT_COMPLETE"},[4,y.getUser()];case 4:return n.apply(void 0,[(o.user=r.sent(),o)]),[7];case 5:return[2]}}))}))}),[y]),x=t.useCallback((function(e){return y.getDpopNonce(e)}),[y]),j=t.useCallback((function(e,t){return y.setDpopNonce(e,t)}),[y]),D=t.useCallback((function(e){return y.generateDpopProof(e)}),[y]),U=t.useCallback((function(e){return y.createFetcher(e)}),[y]),W=t.useCallback((function(){return y.getConfiguration()}),[y]),K=t.useMemo((function(){return y.mfa}),[y]),L=t.useMemo((function(){return o(o({},g),{getAccessTokenSilently:E,getAccessTokenWithPopup:P,getIdTokenClaims:O,loginWithCustomTokenExchange:R,exchangeToken:C,loginWithRedirect:k,loginWithPopup:S,connectAccountWithRedirect:A,logout:T,handleRedirectCallback:I,getDpopNonce:x,setDpopNonce:j,generateDpopProof:D,createFetcher:U,getConfiguration:W,mfa:K})}),[g,E,P,O,R,C,k,S,A,T,I,x,j,D,U,W,K]);return t.createElement(p.Provider,{value:L},c)},e.AuthenticationError=f,e.ConnectError=m,e.GenericError=p,e.InMemoryCache=ke,e.LocalStorageCache=_e,e.MfaChallengeError=ea,e.MfaEnrollmentError=$i,e.MfaEnrollmentFactorsError=na,e.MfaError=Yi,e.MfaListAuthenticatorsError=Qi,e.MfaRequiredError=b,e.MfaVerifyError=ta,e.MissingRefreshTokenError=_,e.OAuthError=la,e.PopupCancelledError=g,e.PopupOpenError=v,e.PopupTimeoutError=w,e.TimeoutError=y,e.UseDpopNonceError=S,e.User=class{},e.initialContext=ca,e.useAuth0=ba,e.withAuth0=function(e,n){return void 0===n&&(n=ua),function(r){return t.createElement(n.Consumer,null,(function(n){return t.createElement(e,o({},r,{auth0:n}))}))}},e.withAuthenticationRequired=function(e,n){return void 0===n&&(n={}),function(r){var s=this,c=n.returnTo,u=void 0===c?Sa:c,l=n.onRedirecting,d=void 0===l?_a:l,h=n.onBeforeAuthentication,p=void 0===h?ka:h,f=n.loginOptions,m=n.context,y=ba(void 0===m?ua:m),w=y.isAuthenticated,g=y.isLoading,v=y.loginWithRedirect;return t.useEffect((function(){if(!g&&!w){var e=o(o({},f),{appState:o(o({},null==f?void 0:f.appState),{returnTo:"function"==typeof u?u():u})});i(s,void 0,void 0,(function(){return a(this,(function(t){switch(t.label){case 0:return[4,p()];case 1:return t.sent(),[4,v(e)];case 2:return t.sent(),[2]}}))}))}}),[g,w,v,p,f,u]),w?t.createElement(e,o({},r)):d()}}}));
2
2
  //# sourceMappingURL=auth0-react.min.js.map