@auth0/auth0-spa-js
Version:
Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE
1 lines • 159 kB
JavaScript
function e(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;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},o={};Object.defineProperty(o,"__esModule",{value:!0});var r=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}();o.default=function(){return r.getInstance()};var i=t&&t.__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())}))},a=t&&t.__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=a.trys,(r=r.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])}}},s=t;Object.defineProperty(n,"__esModule",{value:!0});var c=o,u={key:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return i(s,void 0,void 0,(function(){return a(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return i(s,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return i(s,void 0,void 0,(function(){return a(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 l(e){return new Promise((function(t){return setTimeout(t,e)}))}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)]}return n}var h=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),i(this,void 0,void 0,(function(){var o,r,i,s,c,h,p;return a(this,(function(a){switch(a.label){case 0:o=Date.now()+d(4),r=Date.now()+n,i="browser-tabs-lock-key-"+t,s=void 0===this.storageHandler?u:this.storageHandler,a.label=1;case 1:return Date.now()<r?[4,l(30)]:[3,8];case 2:return a.sent(),null!==s.getItemSync(i)?[3,5]:(c=this.id+"-"+t+"-"+o,[4,l(Math.floor(25*Math.random()))]);case 3:return a.sent(),s.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:c,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return a.sent(),null!==(h=s.getItemSync(i))&&(p=JSON.parse(h)).id===this.id&&p.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?u:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:a.sent(),a.label=7;case 7:return o=Date.now()+d(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return i(this,void 0,void 0,(function(){var n=this;return a(this,(function(o){return setTimeout((function(){return i(n,void 0,void 0,(function(){var n,o,r;return a(this,(function(i){switch(i.label){case 0:return[4,c.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?u:this.storageHandler,null===(o=n.getItemSync(e))?(c.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),c.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(c.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return i(this,void 0,void 0,(function(){return a(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 i(this,void 0,void 0,(function(){return a(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 i(this,void 0,void 0,(function(){var n,o,r,i;return a(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,o="browser-tabs-lock-key-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,c.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),c.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}(),p=n.default=h;const f={timeoutInSeconds:60},m={name:"auth0-spa-js",version:"2.13.1"},y=()=>Date.now();class w extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,w.prototype)}static fromPayload(e){let{error:t,error_description:n}=e;return new w(t,n)}}class g extends w{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,g.prototype)}}class v extends w{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,v.prototype)}}class b extends w{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,b.prototype)}}class _ extends b{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,_.prototype)}}class k extends w{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,k.prototype)}}class S extends w{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,S.prototype)}}class E extends w{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,E.prototype)}}class A extends w{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(R(e,["default"]),"', scope: '").concat(R(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,A.prototype)}}class T extends w{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(R(e,["default"]),"', missing scope: '").concat(R(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,T.prototype)}}class P extends w{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,P.prototype)}}function R(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e&&!t.includes(e)?e:""}const I=()=>window.crypto,O=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(I().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},x=e=>btoa(e),C=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],j=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=C.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},D=t=>{var{clientId:n}=t,o=e(t,["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:n},o))).toString()},K=async e=>{const t=I().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},L=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),U=e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))},N=new TextEncoder,W=new TextDecoder;function z(e){return"string"==typeof e?N.encode(e):W.decode(e)}function H(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new G(`${e.name} modulusLength must be at least 2048 bits`)}async function M(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=`${V(z(JSON.stringify(e)))}.${V(z(JSON.stringify(t)))}`;return`${o}.${V(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return H(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return H(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new F}(n),n,z(o)))}`}let J;if(Uint8Array.prototype.toBase64)J=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;J=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 V(e){return J(e)}class F 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 Z(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return"PS256";throw new F("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return"RS256";throw new F("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return"ES256";throw new F("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return"Ed25519";default:throw new F("unsupported CryptoKey algorithm name")}}function q(e){return e instanceof CryptoKey}function B(e){return q(e)&&"public"===e.type}async function X(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!q(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!B(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 M({alg:Z(a),typ:"dpop+jwt",jwk:await Y(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?V(await crypto.subtle.digest("SHA-256",z(r))):void 0}),a)}async function Y(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 Q=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange","http://auth0.com/oauth/grant-type/mfa-oob","http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-recovery-code"];function $(){return async function(e,t){var n;let o;if("string"!=typeof e||0===e.length)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":o={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":o={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":o={name:"Ed25519"};break;default:throw new F}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:!1})}function ee(e){return async function(e){if(!B(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 Y(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 F("unsupported JWK kty")}return V(await crypto.subtle.digest({name:"SHA-256"},z(JSON.stringify(n))))}(e.publicKey)}function te(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 X(t,a,o,r,i)}const ne=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},oe=async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([ne(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"))}),n)}))]).finally((()=>{clearTimeout(r)}))},re=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),ie=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4,s=arguments.length>7?arguments[7]:void 0;return r?re(e,t,n,o,a,r,i,s):oe(e,o,a)};async function ae(t,n,o,r,i,a,s,c,u,l){if(u){const e=await u.generateProof({url:t,method:i.method||"GET",nonce:await u.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:e})}let d,h=null;for(let e=0;e<3;e++)try{d=await ie(t,o,r,i,a,s,n,c),h=null;break}catch(e){h=e}if(h)throw h;const p=d.json,{error:f,error_description:m}=p,y=e(p,["error","error_description"]),{headers:g,ok:v}=d;let b;if(u&&(b=g["dpop-nonce"],b&&await u.setNonce(b)),!v){const e=m||"HTTP error. Unable to fetch ".concat(t);if("mfa_required"===f)throw new E(f,e,y.mfa_token,y.mfa_requirements);if("missing_refresh_token"===f)throw new A(o,r);if("use_dpop_nonce"===f){if(!u||!b||l)throw new P(b);return ae(t,n,o,r,i,a,s,c,u,!0)}throw new w(f||"request_error",e)}return y}async function se(t,n){var{baseUrl:o,timeout:r,audience:i,scope:a,auth0Client:s,useFormData:c,useMrrt:u,dpop:l}=t,d=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const h="urn:ietf:params:oauth:grant-type:token-exchange"===d.grant_type,p="refresh_token"===d.grant_type&&u,f=Object.assign(Object.assign(Object.assign(Object.assign({},d),h&&i&&{audience:i}),h&&a&&{scope:a}),p&&{audience:i,scope:a}),y=c?D(f):JSON.stringify(f),w=(g=d.grant_type,Q.includes(g));var g;return await ae("".concat(o,"/oauth/token"),r,i||"default",a,{method:"POST",body:y,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(j(s||m)))}},n,c,u,w?l:void 0)}const ce=e=>Array.from(new Set(e)),ue=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return ce(t.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ")},le=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),ue(o,t)};class de{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 de({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new de({scope:t,audience:n,clientId:o})}}class he{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 pe{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 fe{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||y}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 de({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 de({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 de({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=de.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=de.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);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 me{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 ye=e=>"number"==typeof e,we=["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"],ge=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(L(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],we.includes(e)||(s[e]=i[e])})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(L(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&&!ye(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||!ye(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!ye(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&&ye(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&&ye(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};var ve=t&&t.__assign||function(){return ve=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},ve.apply(this,arguments)};function be(e,t){if(!t)return"";var n="; "+e;return!0===t?n:n+"="+t}function _e(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 be("Expires",e.expires?e.expires.toUTCString():"")+be("Domain",e.domain)+be("Path",e.path)+be("Secure",e.secure)+be("SameSite",e.sameSite)}(n)}function ke(){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)}var Se=function(e){return ke()[e]};function Ee(e,t,n){document.cookie=_e(e,t,ve({path:"/"},n))}var Ae=Ee;var Te=function(e,t){Ee(e,"",ve(ve({},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),Ae(e,JSON.stringify(t),o)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),Te(e,n)}},Re={get(e){const t=Pe.get(e);return t||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),Ae("".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),Te(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)}};var Oe;!function(e){e.Code="code",e.ConnectCode="connect_code"}(Oe||(Oe={}));class xe{}function Ce(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)}var je,De,Ke,Le,Ue=(je="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtsZXQgdD1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W107cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCk7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jIGU9PntsZXQgcixjLHtkYXRhOnt0aW1lb3V0OmksYXV0aDphLGZldGNoVXJsOmYsZmV0Y2hPcHRpb25zOmwsdXNlRm9ybURhdGE6cCx1c2VNcnJ0Omh9LHBvcnRzOlt1XX09ZSxkPXt9O2NvbnN0e2F1ZGllbmNlOmcsc2NvcGU6eX09YXx8e307dHJ5e2NvbnN0IGU9cD8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShsLmJvZHkpOkpTT04ucGFyc2UobC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKGM9KChlLHQpPT5vW24oZSx0KV0pKGcseSksIWMmJmgpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxnKTtlJiYhdCYmKGM9ZSl9aWYoIWMpdGhyb3cgbmV3IHQoZyx5KTtsLmJvZHk9cD9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpfWxldCBhLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixsLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoaj1pLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsaikpKSksZmV0Y2goZixPYmplY3QuYXNzaWduKHt9LGwpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBhJiZhLmFib3J0KCksdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189ay5oZWFkZXJzLGQ9Wy4uLl9dLnJlZHVjZSgoKGUsdCk9PntsZXRbcixzXT10O3JldHVybiBlW3JdPXMsZX0pLHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKChlPT57bGV0W3Qscl09ZTtyPT09TyYmKG9bdF09Yil9KSkpLCgoZSx0LHIpPT57b1tuKHQscildPWV9KShyLnJlZnJlc2hfdG9rZW4sZyx5KSxkZWxldGUgci5yZWZyZXNoX3Rva2VuKTooKGUsdCk9PntkZWxldGUgb1tuKGUsdCldfSkoZyx5KSx1LnBvc3RNZXNzYWdlKHtvazprLm9rLGpzb246cixoZWFkZXJzOmR9KX1jYXRjaChlKXt1LnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczpkfSl9dmFyIE8sYixfLGp9KSl9KCk7Cgo=",De=null,Ke=!1,function(e){return Le=Le||Ce(je,De,Ke),new Worker(Le,e)});const Ne={},We=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;for(let n=0;n<t;n++)if(await e())return!0;return!1};class ze{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 He={memory:()=>(new pe).enclosedCache,localstorage:()=>new he},Me=e=>He[e],Je=t=>{const{openUrl:n,onRedirect:o}=t,r=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},r),{openUrl:!1===n||n?n:o})},Ve=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},Fe={NONCE:"nonce",KEYPAIR:"keypair"};class Ge{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(Fe).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(Fe.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(Fe.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)))}findNonce(e){return this.find(Fe.NONCE,this.buildKey(e))}findKeyPair(){return this.find(Fe.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(Fe.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(Fe.KEYPAIR,this.clientId)}}class Ze{constructor(e){this.storage=new Ge(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 $(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return te(Object.assign({keyPair:t},e))}async calculateThumbprint(){return ee(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}var qe;!function(e){e.Bearer="Bearer",e.DPoP="DPoP"}(qe||(qe={}));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]:qe.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?qe.DPoP:qe.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===qe.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 P(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 Xe{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 Ye({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new Ye(t)}}class Ye 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,Ye.prototype)}}const Qe={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}},$e="http://auth0.com/oauth/grant-type/mfa-otp",et="http://auth0.com/oauth/grant-type/mfa-oob",tt="http://auth0.com/oauth/grant-type/mfa-recovery-code";function nt(e,t){this.v=e,this.k=t}function ot(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 rt(e){return new nt(e,0)}function it(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function at(e,t){return e.get(ot(e,t))}function st(e,t,n){it(e,t),t.set(e,n)}function ct(e,t,n){return e.set(ot(e,t),n),n}function ut(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 lt(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 dt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?lt(Object(n),!0).forEach((function(t){ut(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function ht(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 pt(e){return function(){return new ft(e.apply(this,arguments))}}function ft(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof nt;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 mt,yt;let wt;if(ft.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ft.prototype.next=function(e){return this._invoke("next",e)},ft.prototype.throw=function(e){return this._invoke("throw",e)},ft.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(mt=navigator.userAgent)||void 0===mt||null===(yt=mt.startsWith)||void 0===yt||!yt.call(mt,"Mozilla/5.0 ")){const e="v3.8.3";wt="".concat("oauth4webapi","/").concat(e)}function gt(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 vt(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const bt=Symbol(),_t=Symbol(),kt=Symbol(),St=Symbol(),Et=Symbol(),At=Symbol(),Tt=new TextEncoder,Pt=new TextDecoder;function Rt(e){return"string"==typeof e?Tt.encode(e):Pt.decode(e)}let It,Ot;if(Uint8Array.prototype.toBase64)It=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;It=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 xt(e){return"string"==typeof e?Ot(e):It(e)}Ot=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw vt("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 vt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}};class Ct extends Error{constructor(e,t){var n;super(e,t),ut(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 jt extends Error{constructor(e,t){var n;super(e,t),ut(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 Dt(e,t,n){return new jt(e,{code:t,cause:n})}function Kt(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw vt("".concat(t," must be a CryptoKey"),"ERR_INVALID_ARG_TYPE")}(e,t),"private"!==e.type)throw vt("".concat(t," must be a private CryptoKey"),"ERR_INVALID_ARG_VALUE")}function Lt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ut(e){gt(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(wt&&!t.has("user-agent")&&t.set("user-agent",wt),t.has("authorization"))throw vt('"options.headers" must not include the "authorization" header name',"ERR_INVALID_ARG_VALUE");return t}function Nt(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw vt('"options.signal" must return or be an instance of AbortSignal',"ERR_INVALID_ARG_TYPE");return t}}function Wt(e){return e.includes("//")?e.replace("//","/"):e}async function zt(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw vt('"'.concat(t,'" must be an instance of URL'),"ERR_INVALID_ARG_TYPE");en(e,!0!==(null==o?void 0:o[bt]));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[St])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Nt(r,null==o?void 0:o.signal)})}(e,"issuerIdentifier",(e=>{switch(null==t?void 0:t.algorithm){case void 0:case"oidc":!function(e,t){e.pathname=Wt("".concat(e.pathname,"/").concat(t))}(e,".well-known/openid-configuration");break;case"oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Wt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")))}(e,".well-known/oauth-authorization-server");break;default:throw vt('"options.algorithm" must be "oidc" (default), or "oauth2"',"ERR_INVALID_ARG_VALUE")}return e}),t)}function Ht(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw vt("".concat(n," must be a number"),"ERR_INVALID_ARG_TYPE",r);if(e>0)return;if(t){if(0!==e)throw vt("".concat(n," must be a non-negative number"),"ERR_INVALID_ARG_VALUE",r);return}throw vt("".concat(n," must be a positive number"),"ERR_INVALID_ARG_VALUE",r)}catch(e){if(o)throw Dt(e.message,o,r);throw e}}function Mt(e,t,n,o){try{if("string"!=typeof e)throw vt("".concat(t," must be a string"),"ERR_INVALID_ARG_TYPE",o);if(0===e.length)throw vt("".concat(t," must not be empty"),"ERR_INVALID_ARG_VALUE",o)}catch(e){if(n)throw Dt(e.message,n,o);throw e}}function Jt(e){!function(e,t){if(fn(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 Dt(t,Ln,e)}(e,t)}(e,"application/json")}function Vt(){return xt(crypto.getRandomValues(new Uint8Array(32)))}function Ft(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 Ct("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":ret