UNPKG

@auth0/auth0-react

Version:

Auth0 SDK for React Single Page Applications (SPA)

114 lines (102 loc) 81.1 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.reactAuth0 = {}, global.React)); })(this, (function (exports, React) { 'use strict'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; 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 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;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var i=o((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()};}));n(i);var r=n(o((function(e,n){var o=t&&t.__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());}))},r=t&&t.__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=s.trys,(i=i.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])}}},s=t;Object.defineProperty(n,"__esModule",{value:!0});var a="browser-tabs-lock-key",c={key:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return o(s,void 0,void 0,(function(){return r(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return o(s,void 0,void 0,(function(){return r(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 u(e){return new Promise((function(t){return setTimeout(t,e)}))}function h(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var d=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+h(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),o(this,void 0,void 0,(function(){var o,i,s,d,l,p,m;return r(this,(function(r){switch(r.label){case 0:o=Date.now()+h(4),i=Date.now()+n,s=a+"-"+t,d=void 0===this.storageHandler?c:this.storageHandler,r.label=1;case 1:return Date.now()<i?[4,u(30)]:[3,8];case 2:return r.sent(),null!==d.getItemSync(s)?[3,5]:(l=this.id+"-"+t+"-"+o,[4,u(Math.floor(25*Math.random()))]);case 3:return r.sent(),d.setItemSync(s,JSON.stringify({id:this.id,iat:o,timeoutKey:l,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,u(30)];case 4:return r.sent(),null!==(p=d.getItemSync(s))&&(m=JSON.parse(p)).id===this.id&&m.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(s,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?c:this.storageHandler),[4,this.waitForSomethingToChange(i)];case 6:r.sent(),r.label=7;case 7:return o=Date.now()+h(4),[3,1];case 8:return [2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return o(this,void 0,void 0,(function(){var n=this;return r(this,(function(s){return setTimeout((function(){return o(n,void 0,void 0,(function(){var n,o,s;return r(this,(function(r){switch(r.label){case 0:return [4,i.default().lock(t)];case 1:return r.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?c:this.storageHandler,null===(o=n.getItemSync(e))?(i.default().unlock(t),[2]):((s=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(s)),i.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(i.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return o(this,void 0,void 0,(function(){return r(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 o(this,void 0,void 0,(function(){return r(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 o(this,void 0,void 0,(function(){var n,o,s,u;return r(this,(function(r){switch(r.label){case 0:return n=void 0===this.storageHandler?c:this.storageHandler,o=a+"-"+t,null===(s=n.getItemSync(o))?[2]:(u=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(u.iat)];case 1:r.sent(),this.acquiredIatSet.delete(u.iat),n.removeItemSync(o),i.default().unlock(u.iat),e.notifyWaiters(),r.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,i=[],r=0;;){var s=o.keySync(r);if(null===s)break;i.push(s),r++;}for(var c=!1,u=0;u<i.length;u++){var h=i[u];if(h.includes(a)){var d=o.getItemSync(h);if(null!==d){var l=JSON.parse(d);(void 0===l.timeRefreshed&&l.timeAcquired<n||void 0!==l.timeRefreshed&&l.timeRefreshed<n)&&(o.removeItemSync(h),c=!0);}}}c&&e.notifyWaiters();},e.waiters=void 0,e}();n.default=d;})));const s={timeoutInSeconds:60},a={name:"auth0-spa-js",version:"2.4.1"},c=()=>Date.now();class u extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,u.prototype);}static fromPayload({error:e,error_description:t}){return new u(e,t)}}class h extends u{constructor(e,t,n,o=null){super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,h.prototype);}}class d extends u{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,d.prototype);}}class l extends d{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,l.prototype);}}class p extends u{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,p.prototype);}}class m extends u{constructor(e,t,n){super(e,t),this.mfa_token=n,Object.setPrototypeOf(this,m.prototype);}}class f extends u{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${w(e,["default"])}', scope: '${w(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,f.prototype);}}class g extends u{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,g.prototype);}}function w(e,t=[]){return e&&!t.includes(e)?e:""}const y=()=>window.crypto,b=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(y().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},k=e=>btoa(e),v=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()},_=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),I=new TextEncoder,S=new TextDecoder;function T(e){return "string"==typeof e?I.encode(e):S.decode(e)}function O(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new C(`${e.name} modulusLength must be at least 2048 bits`)}async function P(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=`${j(T(JSON.stringify(e)))}.${j(T(JSON.stringify(t)))}`;return `${o}.${j(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return {name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return O(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return O(e.algorithm),{name:e.algorithm.name};case"Ed25519":return {name:e.algorithm.name}}throw new K}(n),n,T(o)))}`}let x;if(Uint8Array.prototype.toBase64)x=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else {const e=32768;x=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 j(e){return x(e)}class K 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 C 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 E(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return "PS256";throw new K("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return "RS256";throw new K("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return "ES256";throw new K("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return "Ed25519";default:throw new K("unsupported CryptoKey algorithm name")}}function z(e){return e instanceof CryptoKey}function D(e){return z(e)&&"public"===e.type}async function N(e,t,n,o,i,r){const s=null==e?void 0:e.privateKey,a=null==e?void 0:e.publicKey;if(!z(c=s)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!D(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 P({alg:E(s),typ:"dpop+jwt",jwk:await U(a)},Object.assign(Object.assign({},r),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:i?j(await crypto.subtle.digest("SHA-256",T(i))):void 0}),s)}async function U(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 Z=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange"];function R(){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 K}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:!1})}function H(e){return async function(e){if(!D(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 U(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 K("unsupported JWK kty")}return j(await crypto.subtle.digest({name:"SHA-256"},T(JSON.stringify(n))))}(e.publicKey)}function A({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 N(e,r,n,o,i)}const W=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;},L=async(e,t,n)=>{const o=new AbortController;let i;return t.signal=o.signal,Promise.race([W(e,t),new Promise(((e,t)=>{i=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),n);}))]).finally((()=>{clearTimeout(i);}))},V=async(e,t,n,o,i,r,s)=>{return a={auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:o,useFormData:s},c=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();},c.postMessage(a,[n.port2]);}));var a,c;},X=async(e,t,n,o,i,r,s=1e4)=>i?V(e,t,n,o,s,i,r):L(e,o,s);async function F(t,n,o,i,r,s,a,c,h){if(c){const e=await c.generateProof({url:t,method:r.method||"GET",nonce:await c.getNonce()});r.headers=Object.assign(Object.assign({},r.headers),{dpop:e});}let d,l=null;for(let e=0;e<3;e++)try{d=await X(t,o,i,r,s,a,n),l=null;break}catch(e){l=e;}if(l)throw l;const p=d.json,{error:w,error_description:y}=p,b=e(p,["error","error_description"]),{headers:k,ok:v}=d;let _;if(c&&(_=k["dpop-nonce"],_&&await c.setNonce(_)),!v){const e=y||`HTTP error. Unable to fetch ${t}`;if("mfa_required"===w)throw new m(w,e,b.mfa_token);if("missing_refresh_token"===w)throw new f(o,i);if("use_dpop_nonce"===w){if(!c||!_||h)throw new g(_);return F(t,n,o,i,r,s,a,c,!0)}throw new u(w||"request_error",e)}return b}async function J(t,n){var{baseUrl:o,timeout:i,audience:r,scope:s,auth0Client:c,useFormData:u,dpop:h}=t,d=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","dpop"]);const l="urn:ietf:params:oauth:grant-type:token-exchange"===d.grant_type,p=Object.assign(Object.assign(Object.assign({},d),l&&r&&{audience:r}),l&&s&&{scope:s}),m=u?v(p):JSON.stringify(p),f=(g=d.grant_type,Z.includes(g));var g;return await F(`${o}/oauth/token`,i,r||"default",s,{method:"POST",body:m,headers:{"Content-Type":u?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(c||a))}},n,u,f?h:void 0)}const G=(...e)=>{return (t=e.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(t))).join(" ");var t;};class M{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 M({clientId:n,scope:i,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new M({scope:t,audience:n,clientId:o})}}class Y{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 ${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 B{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||c;}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){var n;let o=await this.cache.get(e.toKey());if(!o){const t=await this.getCacheKeys();if(!t)return;const n=this.matchExistingCacheKey(e,t);n&&(o=await this.cache.get(n));}if(!o)return;const i=await this.nowProvider(),r=Math.floor(i/1e3);return o.expiresAt-t<r?o.body.refresh_token?(o.body={refresh_token:o.body.refresh_token},await this.cache.set(e.toKey(),o),o.body):(await this.cache.remove(e.toKey()),void await(null===(n=this.keyManifest)||void 0===n?void 0:n.remove(e.toKey()))):o.body}async set(e){var t;const n=new M({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 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 M({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=M.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]}}class q{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 Q=e=>"number"==typeof e,ee=["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"],te=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(_(o)),s={__raw:e},a={};return Object.keys(r).forEach((e=>{s[e]=r[e],ee.includes(e)||(a[e]=r[e]);})),{encoded:{header:n,payload:o,signature:i},header:JSON.parse(_(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&&!Q(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||!Q(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!Q(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&&Q(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&&Q(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};var ne=o((function(e,n){var o=t&&t.__assign||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){if(!t)return "";var n="; "+e;return !0===t?n:n+"="+t}function r(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 i("Expires",e.expires?e.expires.toUTCString():"")+i("Domain",e.domain)+i("Path",e.path)+i("Secure",e.secure)+i("SameSite",e.sameSite)}(n)}function s(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 a(){return s(document.cookie)}function c(e,t,n){document.cookie=r(e,t,o({path:"/"},n));}n.__esModule=!0,n.encode=r,n.parse=s,n.getAll=a,n.get=function(e){return a()[e]},n.set=c,n.remove=function(e,t){c(e,"",o(o({},t),{expires:-1}));};}));n(ne),ne.encode,ne.parse,ne.getAll;var oe=ne.get,ie=ne.set,re=ne.remove;const se={get(e){const t=oe(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),ie(e,JSON.stringify(t),o);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n);}},ae={get(e){const t=se.get(e);return t||se.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),ie(`_legacy_${e}`,JSON.stringify(t),o),se.save(e,t,n);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n),se.remove(e,t),se.remove(`_legacy_${e}`,t);}},ce={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);}};function ue(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)}var he,de,le,pe,me=(he="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHIsdCl7c3VwZXIodCksdGhpcy5lcnJvcj1yLHRoaXMuZXJyb3JfZGVzY3JpcHRpb249dCxPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnR9KXtyZXR1cm4gbmV3IGUocix0KX19Y2xhc3MgciBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7dChlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7dChzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsci5wcm90b3R5cGUpfX1mdW5jdGlvbiB0KGUscj1bXSl7cmV0dXJuIGUmJiFyLmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDpyfT1lLHQ9ZnVuY3Rpb24oZSxyKXt2YXIgdD17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmci5pbmRleE9mKHMpPDAmJih0W3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspci5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYodFtzW29dXT1lW3Nbb11dKX1yZXR1cm4gdH0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHI9PnZvaWQgMCE9PWVbcl0pKS5yZWR1Y2UoKChyLHQpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse1t0XTplW3RdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnJ9LHQpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSxyKT0+YCR7ZX18JHtyfWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDp0LGZldGNoVXJsOmMsZmV0Y2hPcHRpb25zOmksdXNlRm9ybURhdGE6YX0scG9ydHM6W3BdfSk9PntsZXQgZix1PXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6aH09dHx8e307dHJ5e2NvbnN0IHQ9YT8oZT0+e2NvbnN0IHI9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSx0PXt9O3JldHVybiByLmZvckVhY2goKChlLHIpPT57dFtyXT1lfSkpLHR9KShpLmJvZHkpOkpTT04ucGFyc2UoaS5ib2R5KTtpZighdC5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT10LmdyYW50X3R5cGUpe2NvbnN0IGU9KChlLHIpPT5vW24oZSxyKV0pKGQsaCk7aWYoIWUpdGhyb3cgbmV3IHIoZCxoKTtpLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpfWxldCB5LE87ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKHk9bmV3IEFib3J0Q29udHJvbGxlcixpLnNpZ25hbD15LnNpZ25hbCk7dHJ5e089YXdhaXQgUHJvbWlzZS5yYWNlKFsoZz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsZykpKSksZmV0Y2goYyxPYmplY3QuYXNzaWduKHt9LGkpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFPKXJldHVybiB5JiZ5LmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2w9Ty5oZWFkZXJzLHU9Wy4uLmxdLnJlZHVjZSgoKGUsW3IsdF0pPT4oZVtyXT10LGUpKSx7fSksZj1hd2FpdCBPLmpzb24oKSxmLnJlZnJlc2hfdG9rZW4/KCgoZSxyLHQpPT57b1tuKHIsdCldPWV9KShmLnJlZnJlc2hfdG9rZW4sZCxoKSxkZWxldGUgZi5yZWZyZXNoX3Rva2VuKTooKGUscik9PntkZWxldGUgb1tuKGUscildfSkoZCxoKSxwLnBvc3RNZXNzYWdlKHtvazpPLm9rLGpzb246ZixoZWFkZXJzOnV9KX1jYXRjaChlKXtwLnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczp1fSl9dmFyIGwsZ30pKX0oKTsKCg==",de=null,le=!1,function(e){return pe=pe||ue(he,de,le),new Worker(pe,e)});const fe={};class ge{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 we={memory:()=>(new $).enclosedCache,localstorage:()=>new Y},ye=e=>we[e],be=t=>{const{openUrl:n,onRedirect:o}=t,i=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},i),{openUrl:!1===n||n?n:o})},ke={NONCE:"nonce",KEYPAIR:"keypair"};class ve{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(ke).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(ke.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(ke.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)));}findNonce(e){return this.find(ke.NONCE,this.buildKey(e))}findKeyPair(){return this.find(ke.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(ke.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(ke.KEYPAIR,this.clientId)}}class _e{constructor(e){this.storage=new ve(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 R(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return A(Object.assign({keyPair:t},e))}async calculateThumbprint(){return H(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()]);}}class Ie{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(){return this.config.getAccessToken?this.config.getAccessToken():this.hooks.getAccessToken()}buildBaseRequest(e,t){const n=new Request(e,t);return this.config.baseUrl?new Request(this.buildUrl(this.config.baseUrl,n.url),n):n}async setAuthorizationHeader(e,t){e.headers.set("authorization",`${this.config.dpopNonceId?"DPoP":"Bearer"} ${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){const t=await this.getAccessToken();this.setAuthorizationHeader(e,t),await this.setDpopProofHeader(e,t);}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;return this.getHeader(e.headers,"www-authenticate").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 g(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n){const o=this.buildBaseRequest(e,t);await this.prepareRequest(o);const i=await this.config.fetch(o);return this.handleResponse(i,n)}fetchWithAuth(e,t){const n={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},n),{onUseDpopNonceError:void 0}))};return this.internalFetchWithAuth(e,t,n)}}const Se=new r;class Te{constructor(e){let t,n;if(this.userCache=(new $).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{await Se.releaseLock("auth0.lock.getTokenSilently"),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(!y())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===y().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",!ye(t))throw new Error(`Invalid cache location "${t}"`);n=ye(t)();}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?se:ae,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const o=e.useCookiesForTransactions?this.cookieStorage:ce;var i;this.scope=G("openid",this.options.authorizationParams.scope,this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new q(o,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||c,this.cacheManager=new B(n,n.allKeys?void 0:new ge(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new _e(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),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new me);}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||a)));return `${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${v(e)}`)}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return te({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=k(b()),r=k(b()),s=b(),a=(e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))})(await(async e=>{const t=y().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t})(s)),c=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),u=((e,t,n,o,i,r,s,a,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:G(t,n.scope),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,a,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,c),h=this._authorizeUrl(u);return {nonce:r,code_verifier:s,scope:u.scope,audience:u.audience||"default",redirect_uri:u.redirect_uri,state:i,url:h}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup",`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(""),!t.popup))throw new 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 p(e.popup)));}),1e3),r=setTimeout((()=>{clearInterval(i),n(new l(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(u.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 u("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=be(t),{openUrl:i,fragment:r,appState:s}=o,a=e(o,["openUrl","fragment","appState"]),c=(null===(n=a.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization,u=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:h}=u,d=e(u,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},d),{appState:s}),c&&{organization:c}));const l=r?`${h}#${r}`:h;i?await i(l):window.location.assign(l);}async handleRedirectCallback(e=window.location.href){const t=e.split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const{state:n,code:o,error:i,error_description:r}=(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,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(t.join("")),s=this.transactionManager.get();if(!s)throw new u("missing_transaction","Invalid state");if(this.transactionManager.remove(),i)throw new h(i,r||i,n,s.appState);if(!s.code_verifier||s.state&&s.state!==n)throw new u("state_mismatch","Invalid state");const a=s.organization,c=s.nonce,d=s.redirect_uri;return await this._requestToken(Object.assign({audience:s.audience,scope:s.scope,code_verifier:s.code_verifier,grant_type:"authorization_code",code:o},d?{redirect_uri:d}:{}),{nonceIn:c,organization:a}),{appState:s.appState}}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated");}try{await this.getTokenSilently(e);}catch(e){}}as