UNPKG

@auth0/auth0-react

Version:

Auth0 SDK for React Single Page Applications (SPA)

1 lines 70.8 kB
!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 i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function i(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 i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function r(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}function s(e,t){var n,o,i,r={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(r=0)),r;)try{if(n=1,o&&(i=2&a[0]?o.return:a[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,a[1])).done)return i;switch(o=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,o=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(i=r.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){r.label=a[1];break}if(6===a[0]&&r.label<i[1]){r.label=i[1],i=a;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(a);break}i[2]&&r.ops.pop(),r.trys.pop();continue}a=t.call(e,r)}catch(e){a=[6,e],o=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function a(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 i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}"function"==typeof SuppressedError&&SuppressedError,"function"==typeof SuppressedError&&SuppressedError;var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function d(e,t){return e(t={exports:{}},t.exports),t.exports}var l=d((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=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}();t.default=function(){return n.getInstance()}}));u(l);var h=u(d((function(e,t){var n=c&&c.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(s,a)}c((o=o.apply(e,t||[])).next())}))},o=c&&c.__generator||function(e,t){var n,o,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,o=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=t.call(e,s)}catch(e){r=[6,e],o=0}finally{n=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,a])}}},i=c;Object.defineProperty(t,"__esModule",{value:!0});var r="browser-tabs-lock-key",s={key:function(e){return n(i,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return n(i,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return n(i,void 0,void 0,(function(){return o(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return n(i,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return n(i,void 0,void 0,(function(){return o(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 a(e){return new Promise((function(t){return setTimeout(t,e)}))}function u(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++)n+=t[Math.floor(61*Math.random())];return n}var d=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+u(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),n(this,void 0,void 0,(function(){var n,c,d,l,h,p,f;return o(this,(function(o){switch(o.label){case 0:n=Date.now()+u(4),c=Date.now()+i,d=r+"-"+t,l=void 0===this.storageHandler?s:this.storageHandler,o.label=1;case 1:return Date.now()<c?[4,a(30)]:[3,8];case 2:return o.sent(),null!==l.getItemSync(d)?[3,5]:(h=this.id+"-"+t+"-"+n,[4,a(Math.floor(25*Math.random()))]);case 3:return o.sent(),l.setItemSync(d,JSON.stringify({id:this.id,iat:n,timeoutKey:h,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,a(30)];case 4:return o.sent(),null!==(p=l.getItemSync(d))&&(f=JSON.parse(p)).id===this.id&&f.iat===n?(this.acquiredIatSet.add(n),this.refreshLockWhileAcquired(d,n),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?s:this.storageHandler),[4,this.waitForSomethingToChange(c)];case 6:o.sent(),o.label=7;case 7:return n=Date.now()+u(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return n(this,void 0,void 0,(function(){var i=this;return o(this,(function(r){return setTimeout((function(){return n(i,void 0,void 0,(function(){var n,i,r;return o(this,(function(o){switch(o.label){case 0:return[4,l.default().lock(t)];case 1:return o.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?s:this.storageHandler,null===(i=n.getItemSync(e))?(l.default().unlock(t),[2]):((r=JSON.parse(i)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),l.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(l.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){var o=!1,i=Date.now(),r=!1;function s(){if(r||(window.removeEventListener("storage",s),e.removeFromWaiting(s),clearTimeout(a),r=!0),!o){o=!0;var t=50-(Date.now()-i);t>0?setTimeout(n,t):n(null)}}window.addEventListener("storage",s),e.addToWaiting(s);var a=setTimeout(s,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 n(this,void 0,void 0,(function(){return o(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 n(this,void 0,void 0,(function(){var n,i,a,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?s:this.storageHandler,i=r+"-"+t,null===(a=n.getItemSync(i))?[2]:(c=JSON.parse(a)).id!==this.id?[3,2]:[4,l.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(i),l.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,i=[],s=0;;){var a=o.keySync(s);if(null===a)break;i.push(a),s++}for(var c=!1,u=0;u<i.length;u++){var d=i[u];if(d.includes(r)){var l=o.getItemSync(d);if(null!==l){var h=JSON.parse(l);(void 0===h.timeRefreshed&&h.timeAcquired<n||void 0!==h.timeRefreshed&&h.timeRefreshed<n)&&(o.removeItemSync(d),c=!0)}}}c&&e.notifyWaiters()},e.waiters=void 0,e}();t.default=d})));const p={timeoutInSeconds:60},f={name:"auth0-spa-js",version:"2.9.0"},m=()=>Date.now();class y extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,y.prototype)}static fromPayload({error:e,error_description:t}){return new y(e,t)}}class g extends y{constructor(e,t,n,o=null){super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,g.prototype)}}class w extends y{constructor(e,t,n,o,i=null){super(e,t),this.connection=n,this.state=o,this.appState=i,Object.setPrototypeOf(this,w.prototype)}}class b extends y{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,b.prototype)}}class v extends b{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,v.prototype)}}class k extends y{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,k.prototype)}}class _ extends y{constructor(e,t,n){super(e,t),this.mfa_token=n,Object.setPrototypeOf(this,_.prototype)}}class S extends y{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${T(e,["default"])}', scope: '${T(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,S.prototype)}}class I extends y{constructor(e,t){super("missing_scopes",`Missing requested scopes after refresh (audience: '${T(e,["default"])}', missing scope: '${T(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,I.prototype)}}class P extends y{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,P.prototype)}}function T(e,t=[]){return e&&!t.includes(e)?e:""}const O=()=>window.crypto,C=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(O().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%66])),t},E=e=>btoa(e),j=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],x=e=>Object.keys(e).reduce(((t,n)=>{const o=j.find((e=>e.key===n));return o&&o.type.includes(typeof e[n])&&(t[n]=e[n]),t}),{}),R=e=>{var{clientId:t}=e,n=a(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()},z=async e=>{const t=O().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},K=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),N=e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))},A=new TextEncoder,U=new TextDecoder;function D(e){return"string"==typeof e?A.encode(e):U.decode(e)}function L(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new G(`${e.name} modulusLength must be at least 2048 bits`)}let Z;if(Uint8Array.prototype.toBase64)Z=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;Z=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 W(e){return Z(e)}class H 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 G 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 J(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return"PS256";throw new H("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return"RS256";throw new H("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return"ES256";throw new H("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return"Ed25519";default:throw new H("unsupported CryptoKey algorithm name")}}function X(e){return e instanceof CryptoKey}function F(e){return X(e)&&"public"===e.type}async function V(e,t,n,o,i,r){const s=null==e?void 0:e.privateKey,a=null==e?void 0:e.publicKey;if(!X(c=s)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!F(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(!0!==a.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!==i&&"string"!=typeof i)throw new TypeError('"accessToken" must be a string or undefined');if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))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=`${W(D(JSON.stringify(e)))}.${W(D(JSON.stringify(t)))}`;return`${o}.${W(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return L(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return L(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new H}(n),n,D(o)))}`}({alg:J(s),typ:"dpop+jwt",jwk:await M(a)},Object.assign(Object.assign({},r),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:i?W(await crypto.subtle.digest("SHA-256",D(i))):void 0}),s)}async function M(e){const{kty:t,e:n,n:o,x:i,y:r,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:n,n:o,x:i,y:r}}const Y=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange"];const $=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,n])=>(e[t]=n,e)),{}))};var o},B=async(e,t,n,o,i,r,s=1e4,a)=>i?(async(e,t,n,o,i,r,s,a)=>{return c={auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:o,useFormData:s,useMrrt:a},u=r,new Promise((function(e,t){const n=new MessageChannel;n.port1.onmessage=function(o){o.data.error?t(new Error(o.data.error)):e(o.data),n.port1.close()},u.postMessage(c,[n.port2])}));var c,u})(e,t,n,o,s,i,r,a):(async(e,t,n)=>{const o=new AbortController;let i;return t.signal=o.signal,Promise.race([$(e,t),new Promise(((e,t)=>{i=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"))}),n)}))]).finally((()=>{clearTimeout(i)}))})(e,o,s);async function q(e,t,n,o,i,r,s,c,u,d){if(u){const t=await u.generateProof({url:e,method:i.method||"GET",nonce:await u.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:t})}let l,h=null;for(let a=0;a<3;a++)try{l=await B(e,n,o,i,r,s,t,c),h=null;break}catch(e){h=e}if(h)throw h;const p=l.json,{error:f,error_description:m}=p,g=a(p,["error","error_description"]),{headers:w,ok:b}=l;let v;if(u&&(v=w["dpop-nonce"],v&&await u.setNonce(v)),!b){const a=m||`HTTP error. Unable to fetch ${e}`;if("mfa_required"===f)throw new _(f,a,g.mfa_token);if("missing_refresh_token"===f)throw new S(n,o);if("use_dpop_nonce"===f){if(!u||!v||d)throw new P(v);return q(e,t,n,o,i,r,s,c,u,!0)}throw new y(f||"request_error",a)}return g}async function Q(e,t){var{baseUrl:n,timeout:o,audience:i,scope:r,auth0Client:s,useFormData:c,useMrrt:u,dpop:d}=e,l=a(e,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const h="urn:ietf:params:oauth:grant-type:token-exchange"===l.grant_type,p="refresh_token"===l.grant_type&&u,m=Object.assign(Object.assign(Object.assign(Object.assign({},l),h&&i&&{audience:i}),h&&r&&{scope:r}),p&&{audience:i,scope:r}),y=c?R(m):JSON.stringify(m),g=(w=l.grant_type,Y.includes(w));var w;return await q(`${n}/oauth/token`,o,i||"default",r,{method:"POST",body:y,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(x(s||f)))}},t,c,u,g?d:void 0)}const ee=(...e)=>{return(t=e.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(t))).join(" ");var t},te=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),ee(o,t)};class ne{constructor(e,t="@@auth0spajs@@",n){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,i]=e.split("::");return new ne({clientId:n,scope:i,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new ne({scope:t,audience:n,clientId:o})}}class oe{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 ie{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 re{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||m}async setIdToken(e,t,n){var o;const i=this.getIdTokenCacheKey(e);await this.cache.set(i,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(i))}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,t=0,n=!1,o){var i;let r=await this.cache.get(e.toKey());if(!r){const t=await this.getCacheKeys();if(!t)return;const i=this.matchExistingCacheKey(e,t);if(i&&(r=await this.cache.get(i)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!r)return;const s=await this.nowProvider(),a=Math.floor(s/1e3);return r.expiresAt-t<a?r.body.refresh_token?this.modifiedCachedEntry(r,e):(await this.cache.remove(e.toKey()),void await(null===(i=this.keyManifest)||void 0===i?void 0:i.remove(e.toKey()))):r.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 ne({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 ne({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 ne({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=ne.fromKey(t),i=new Set(o.scope&&o.scope.split(" ")),r=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],s=o.scope&&r.reduce(((e,t)=>e&&i.has(t)),!0);return"@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&s}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=ne.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 i of o){const o=await this.cache.get(i);if((null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e){const e=Object.assign(Object.assign({},o.body),{refresh_token:t});await this.set(e)}}}}class se{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey=`a0.spajs.txs.${this.clientId}`}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain})}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain})}}const ae=e=>"number"==typeof e,ce=["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 ue=d((function(e,t){var n=c&&c.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};function o(e,t){if(!t)return"";var n="; "+e;return!0===t?n:n+"="+t}function i(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 o("Expires",e.expires?e.expires.toUTCString():"")+o("Domain",e.domain)+o("Path",e.path)+o("Secure",e.secure)+o("SameSite",e.sameSite)}(n)}function r(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,i=0;i<n.length;i++){var r=n[i].split("="),s=r.slice(1).join("=");'"'===s.charAt(0)&&(s=s.slice(1,-1));try{t[r[0].replace(o,decodeURIComponent)]=s.replace(o,decodeURIComponent)}catch(e){}}return t}function s(){return r(document.cookie)}function a(e,t,o){document.cookie=i(e,t,n({path:"/"},o))}t.__esModule=!0,t.encode=i,t.parse=r,t.getAll=s,t.get=function(e){return s()[e]},t.set=a,t.remove=function(e,t){a(e,"",n(n({},t),{expires:-1}))}}));u(ue),ue.encode,ue.parse,ue.getAll;var de=ue.get,le=ue.set,he=ue.remove;const pe={get(e){const t=de(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),le(e,JSON.stringify(t),o)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),he(e,n)}},fe={get:e=>pe.get(e)||pe.get(`_legacy_${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),le(`_legacy_${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),he(e,n),pe.remove(e,t),pe.remove(`_legacy_${e}`,t)}},me={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 ye,ge=function(e){return ye=ye||function(e,t,n){var o=void 0===t?null:t,i=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),i=0,r=n.length;i<r;++i)o[i]=n.charCodeAt(i);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),r=i.indexOf("\n",10)+1,s=i.substring(r)+(o?"//# sourceMappingURL="+o:""),a=new Blob([s],{type:"application/javascript"});return URL.createObjectURL(a)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdG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gucmVmcmVzaF90b2tlbixkLHkpLGRlbGV0ZSBoLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBvW24oZSx0KV19KShkLHkpLHAucG9zdE1lc3NhZ2Uoe29rOmsub2ssanNvbjpoLGhlYWRlcnM6bH0pfWNhdGNoKGUpe3AucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOmx9KX12YXIgTyxiLGcsX30pKX0oKTsKCg==",null,false),new Worker(ye,e)};const we={};class be{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`@@auth0spajs@@::${e}`}}const ve={memory:()=>(new ie).enclosedCache,localstorage:()=>new oe},ke=e=>ve[e],_e=e=>{const{openUrl:t,onRedirect:n}=e,o=a(e,["openUrl","onRedirect"]);return Object.assign(Object.assign({},o),{openUrl:!1===t||t?t:n})},Se=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},Ie={NONCE:"nonce",KEYPAIR:"keypair"};class Pe{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(Ie).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?`_${e}`:"auth0";return`${this.clientId}::${t}`}setNonce(e,t){return this.save(Ie.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Ie.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)))}findNonce(e){return this.find(Ie.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Ie.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(`${t}::`)))}clearNonces(){return this.deleteByClientId(Ie.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Ie.KEYPAIR,this.clientId)}}class Te{constructor(e){this.storage=new Pe(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({keyPair:e,url:t,method:n,nonce:o,accessToken:i}){const r=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(t);return V(e,r,n,o,i)}(Object.assign({keyPair:t},e))}async calculateThumbprint(){return function(e){return async function(e){if(!F(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 M(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 H("unsupported JWK kty")}return W(await crypto.subtle.digest({name:"SHA-256"},D(JSON.stringify(n))))}(e.publicKey)}(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}var Oe;!function(e){e.Bearer="Bearer",e.DPoP="DPoP"}(Oe||(Oe={}));class Ce{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`${e.replace(/\/?\/$/,"")}/${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,n=Oe.Bearer){e.headers.set("authorization",`${n} ${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,i;"string"==typeof n?(o=this.config.dpopNonceId?Oe.DPoP:Oe.Bearer,i=n):(o=n.token_type,i=n.access_token),this.setAuthorizationHeader(e,i,o),o===Oe.DPoP&&await this.setDpopProofHeader(e,i)}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 P(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const i=this.buildBaseRequest(e,t);await this.prepareRequest(i,o);const r=await this.config.fetch(i);return this.handleResponse(r,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 Ee{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t)}catch(n){throw new je({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new je(t)}}class je extends Error{constructor({type:e,status:t,title:n,detail:o,validation_errors:i}){super(o),this.name="MyAccountApiError",this.type=e,this.status=t,this.title=n,this.detail=o,this.validation_errors=i,Object.setPrototypeOf(this,je.prototype)}}const xe=new h;class Re{constructor(e){let t,n;if(this.userCache=(new ie).enclosedCache,this.activeLockKeys=new Set,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{const e=Array.from(this.activeLockKeys);for(const t of e)await xe.releaseLock(t);this.activeLockKeys.clear(),window.removeEventListener("pagehide",this._releaseLockOnPageHide)},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(!O())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===O().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 ")})(),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",!ke(t))throw new Error(`Invalid cache location "${t}"`);n=ke(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?pe:fe,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(()=>`auth0.${this.options.clientId}.is.authenticated`)(),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const o=e.useCookiesForTransactions?this.cookieStorage:me;var i;this.scope=((e,t,...n)=>{if("object"!=typeof e)return{default:ee(t,e,...n)};let o={default:ee(t,...n)};return Object.keys(e).forEach((i=>{const r=e[i];o[i]=ee(t,r,...n)})),o})(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new se(o,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||m,this.cacheManager=new re(n,n.allKeys?void 0:new be(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Te(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:`https://${i}`),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl);const r=`${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:r},detailedResponse:!0})}));this.myAccountApi=new Ee(s,r),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new ge)}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||f)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${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,i]=t;if(3!==t.length||!n||!o||!i)throw new Error("ID token could not be decoded");const r=JSON.parse(K(o)),s={__raw:e},a={};return Object.keys(r).forEach((e=>{s[e]=r[e],ce.includes(e)||(a[e]=r[e])})),{encoded:{header:n,payload:o,signature:i},header:JSON.parse(K(n)),claims:s,user:a}})(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 "${e.iss}", found "${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 "${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 "${e.aud}" but was not one of "${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 "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but found "${t.claims.aud}"`);if(e.nonce){if(!t.claims.nonce)throw 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 "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!ae(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||!ae(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!ae(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()),i=new Date(0);if(i.setUTCSeconds(t.claims.exp+n),o>i)throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${o}) is after expiration time (${i})`);if(null!=t.claims.nbf&&ae(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 (${o}) is before ${e}`)}if(null!=t.claims.auth_time&&ae(t.claims.auth_time)){const i=new Date(0);if(i.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>i)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 (${o}) is after last auth at ${i}`)}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 "${e}", found "${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 "${e}", found "${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:(i=this.options.authorizationParams.max_age,"string"!=typeof i?i:parseInt(i,10)||void 0),now:o});var i}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain})}async _prepareAuthorizeUrl(e,t,n){var o;const i=E(C()),r=E(C()),s=C(),a=await z(s),c=N(a),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),d=((e,t,n,o,i,r,s,a,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:te(t,n.scope,n.audience),response_type:"code",response_mode:a||"query",state:o,nonce:i,redirect_uri:s||e.authorizationParams.redirect_uri,code_challenge:r,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,i,r,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),l=this._authorizeUrl(d);return{nonce:r,code_verifier:s,scope:d.scope,audience:d.audience||"default",redirect_uri:d.redirect_uri,state:i,url:l}}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=${e},top=${t},width=400,height=600,resizable,scrollbars=yes,status=1`)})(),!t.popup))throw new Error("Unable to open a popup for loginWithPopup - window.open returned `null`");const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const i=await(e=>new Promise(((t,n)=>{let o;const i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(r),window.removeEventListener("message",o,!1),n(new k(e.popup)))}),1e3),r=setTimeout((()=>{clearInterval(i),n(new v(e.popup)),window.removeEventListener("message",o,!1)}),1e3*(e.timeoutInSeconds||60));o=function(s){if(s.data&&"authorization_response"===s.data.type){if(clearTimeout(r),clearInterval(i),window.removeEventListener("message",o,!1),e.popup.close(),s.data.response.error)return n(y.fromPayload(s.data.response));t(s.data.response)}},window.addEventListener("message",o)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==i.state)throw new y("state_mismatch","Invalid state");const r=(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:i.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:r})}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(t={}){var n;const o=_e(t),{openUrl:i,fragment:r,appState:s}=o,c=a(o,["openUrl","fragment","appState"]),u=(null===(n=c.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization,d=await this._prepareAuthorizeUrl(c.authorizationParams||{}),{url:l}=d,h=a(d,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},h),{appState:s,response_type:e.ResponseType.Code}),u&&{organization:u}));const p=r?`${l}#${r}`:l;i?await i(p):window.location.assign(p)}async handleRedirectCallback(t=window.location.href){const n=t.split("?").slice(1);if(0===n.length)throw new Error("There are no query params available for parsing.");const o=this.transactionManager.get();if(!o)throw new y("missing_transaction","Invalid state");this.transactionManager.remove();const i=(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}})(n.join(""));return o.response_type===e.ResponseType.ConnectCode?this._handleConnectAccountRedirectCallback(i,o):this._handleLoginRedirectCallback(i,o)}async _handleLoginRedirectCallback(t,n){const{code:o,state:i,error:r,error_description:s}=t;if(r)throw new g(r,s||r,i,n.appState);if(!n.code_verifier||n.state&&n.state!==i)throw new y("state_mismatch","Invalid state");const a=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:a}),{appState:n.appState,response_type:e.ResponseType.Code}}async _handleConnectAccountRedirectCallback(t,n){c