UNPKG

183 kBSource Map (JSON)View Raw
1{"version":3,"file":"auth0-spa-js.development.js","sources":["../node_modules/tslib/tslib.es6.js","../node_modules/browser-tabs-lock/processLock.js","../node_modules/browser-tabs-lock/index.js","../src/version.ts","../src/constants.ts","../src/errors.ts","../src/utils.ts","../src/worker/worker.utils.ts","../src/http.ts","../src/api.ts","../src/scope.ts","../src/cache/shared.ts","../src/cache/cache-localstorage.ts","../src/cache/cache-memory.ts","../src/cache/cache-manager.ts","../src/transaction-manager.ts","../src/jwt.ts","../node_modules/es-cookie/src/es-cookie.js","../src/storage.ts","../src/promise-utils.ts","../src/cache/key-manifest.ts","../src/Auth0Client.utils.ts","../src/Auth0Client.ts","../src/global.ts","../src/index.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ProcessLocking = /** @class */ (function () {\n function ProcessLocking() {\n var _this = this;\n this.locked = new Map();\n this.addToLocked = function (key, toAdd) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined) {\n if (toAdd === undefined) {\n _this.locked.set(key, []);\n }\n else {\n _this.locked.set(key, [toAdd]);\n }\n }\n else {\n if (toAdd !== undefined) {\n callbacks.unshift(toAdd);\n _this.locked.set(key, callbacks);\n }\n }\n };\n this.isLocked = function (key) {\n return _this.locked.has(key);\n };\n this.lock = function (key) {\n return new Promise(function (resolve, reject) {\n if (_this.isLocked(key)) {\n _this.addToLocked(key, resolve);\n }\n else {\n _this.addToLocked(key);\n resolve();\n }\n });\n };\n this.unlock = function (key) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined || callbacks.length === 0) {\n _this.locked.delete(key);\n return;\n }\n var toCall = callbacks.pop();\n _this.locked.set(key, callbacks);\n if (toCall !== undefined) {\n setTimeout(toCall, 0);\n }\n };\n }\n ProcessLocking.getInstance = function () {\n if (ProcessLocking.instance === undefined) {\n ProcessLocking.instance = new ProcessLocking();\n }\n return ProcessLocking.instance;\n };\n return ProcessLocking;\n}());\nfunction getLock() {\n return ProcessLocking.getInstance();\n}\nexports.default = getLock;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n 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;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar processLock_1 = require(\"./processLock\");\n/**\n * @author: SuperTokens (https://github.com/supertokens)\n * This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.\n * You can also check out our other projects on https://github.com/supertokens\n *\n * To contribute to this package visit https://github.com/supertokens/browser-tabs-lock\n * If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues\n *\n * If you have any questions or if you just want to say hi visit https://supertokens.io/discord\n */\n/**\n * @constant\n * @type {string}\n * @default\n * @description All the locks taken by this package will have this as prefix\n*/\nvar LOCK_STORAGE_KEY = 'browser-tabs-lock-key';\n/**\n * @function delay\n * @param {number} milliseconds - How long the delay should be in terms of milliseconds\n * @returns {Promise<void>}\n */\nfunction delay(milliseconds) {\n return new Promise(function (resolve) { return setTimeout(resolve, milliseconds); });\n}\n/**\n * @function generateRandomString\n * @params {number} length - How long the random string should be\n * @returns {string}\n * @description returns random string whose length is equal to the length passed as parameter\n */\nfunction generateRandomString(length) {\n var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';\n var randomstring = '';\n for (var i = 0; i < length; i++) {\n var INDEX = Math.floor(Math.random() * CHARS.length);\n randomstring += CHARS[INDEX];\n }\n return randomstring;\n}\n/**\n * @function getLockId\n * @returns {string}\n * @description Generates an id which will be unique for the browser tab\n */\nfunction getLockId() {\n return Date.now().toString() + generateRandomString(15);\n}\nvar SuperTokensLock = /** @class */ (function () {\n function SuperTokensLock() {\n this.acquiredIatSet = new Set();\n this.id = getLockId();\n this.acquireLock = this.acquireLock.bind(this);\n this.releaseLock = this.releaseLock.bind(this);\n this.releaseLock__private__ = this.releaseLock__private__.bind(this);\n this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);\n this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);\n if (SuperTokensLock.waiters === undefined) {\n SuperTokensLock.waiters = [];\n }\n }\n /**\n * @async\n * @memberOf Lock\n * @function acquireLock\n * @param {string} lockKey - Key for which the lock is being acquired\n * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock\n * @returns {Promise<boolean>}\n * @description Will return true if lock is being acquired, else false.\n * Also the lock can be acquired for maximum 10 secs\n */\n SuperTokensLock.prototype.acquireLock = function (lockKey, timeout) {\n if (timeout === void 0) { timeout = 5000; }\n return __awaiter(this, void 0, void 0, function () {\n var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n iat = Date.now() + generateRandomString(4);\n MAX_TIME = Date.now() + timeout;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n STORAGE = window.localStorage;\n _a.label = 1;\n case 1:\n if (!(Date.now() < MAX_TIME)) return [3 /*break*/, 8];\n return [4 /*yield*/, delay(30)];\n case 2:\n _a.sent();\n lockObj = STORAGE.getItem(STORAGE_KEY);\n if (!(lockObj === null)) return [3 /*break*/, 5];\n TIMEOUT_KEY = this.id + \"-\" + lockKey + \"-\" + iat;\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n return [4 /*yield*/, delay(Math.floor(Math.random() * 25))];\n case 3:\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n _a.sent();\n STORAGE.setItem(STORAGE_KEY, JSON.stringify({\n id: this.id,\n iat: iat,\n timeoutKey: TIMEOUT_KEY,\n timeAcquired: Date.now(),\n timeRefreshed: Date.now()\n }));\n return [4 /*yield*/, delay(30)];\n case 4:\n _a.sent(); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem\n lockObjPostDelay = STORAGE.getItem(STORAGE_KEY);\n if (lockObjPostDelay !== null) {\n lockObjPostDelay = JSON.parse(lockObjPostDelay);\n if (lockObjPostDelay.id === this.id && lockObjPostDelay.iat === iat) {\n this.acquiredIatSet.add(iat);\n this.refreshLockWhileAcquired(STORAGE_KEY, iat);\n return [2 /*return*/, true];\n }\n }\n return [3 /*break*/, 7];\n case 5:\n SuperTokensLock.lockCorrector();\n return [4 /*yield*/, this.waitForSomethingToChange(MAX_TIME)];\n case 6:\n _a.sent();\n _a.label = 7;\n case 7:\n iat = Date.now() + generateRandomString(4);\n return [3 /*break*/, 1];\n case 8: return [2 /*return*/, false];\n }\n });\n });\n };\n SuperTokensLock.prototype.refreshLockWhileAcquired = function (storageKey, iat) {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n var STORAGE, lockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, processLock_1.default().lock(iat)];\n case 1:\n _a.sent();\n if (!this.acquiredIatSet.has(iat)) {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n STORAGE = window.localStorage;\n lockObj = STORAGE.getItem(storageKey);\n if (lockObj !== null) {\n lockObj = JSON.parse(lockObj);\n lockObj.timeRefreshed = Date.now();\n STORAGE.setItem(storageKey, JSON.stringify(lockObj));\n processLock_1.default().unlock(iat);\n }\n else {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n this.refreshLockWhileAcquired(storageKey, iat);\n return [2 /*return*/];\n }\n });\n }); }, 1000);\n return [2 /*return*/];\n });\n });\n };\n SuperTokensLock.prototype.waitForSomethingToChange = function (MAX_TIME) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, new Promise(function (resolve) {\n var resolvedCalled = false;\n var startedAt = Date.now();\n var MIN_TIME_TO_WAIT = 50; // ms\n var removedListeners = false;\n function stopWaiting() {\n if (!removedListeners) {\n window.removeEventListener('storage', stopWaiting);\n SuperTokensLock.removeFromWaiting(stopWaiting);\n clearTimeout(timeOutId);\n removedListeners = true;\n }\n if (!resolvedCalled) {\n resolvedCalled = true;\n var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);\n if (timeToWait > 0) {\n setTimeout(resolve, timeToWait);\n }\n else {\n resolve();\n }\n }\n }\n window.addEventListener('storage', stopWaiting);\n SuperTokensLock.addToWaiting(stopWaiting);\n var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));\n })];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n });\n };\n SuperTokensLock.addToWaiting = function (func) {\n this.removeFromWaiting(func);\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters.push(func);\n };\n SuperTokensLock.removeFromWaiting = function (func) {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function (i) { return i !== func; });\n };\n SuperTokensLock.notifyWaiters = function () {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n var waiters = SuperTokensLock.waiters.slice(); // so that if Lock.waiters is changed it's ok.\n waiters.forEach(function (i) { return i(); });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.releaseLock__private__(lockKey)];\n case 1: return [2 /*return*/, _a.sent()];\n }\n });\n });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock__private__ = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n var STORAGE, STORAGE_KEY, lockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n STORAGE = window.localStorage;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n lockObj = STORAGE.getItem(STORAGE_KEY);\n if (lockObj === null) {\n return [2 /*return*/];\n }\n lockObj = JSON.parse(lockObj);\n if (!(lockObj.id === this.id)) return [3 /*break*/, 2];\n return [4 /*yield*/, processLock_1.default().lock(lockObj.iat)];\n case 1:\n _a.sent();\n this.acquiredIatSet.delete(lockObj.iat);\n STORAGE.removeItem(STORAGE_KEY);\n processLock_1.default().unlock(lockObj.iat);\n SuperTokensLock.notifyWaiters();\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * @function lockCorrector\n * @returns {void}\n * @description If a lock is acquired by a tab and the tab is closed before the lock is\n * released, this function will release those locks\n */\n SuperTokensLock.lockCorrector = function () {\n var MIN_ALLOWED_TIME = Date.now() - 5000;\n var STORAGE = window.localStorage;\n var KEYS = Object.keys(STORAGE);\n var notifyWaiters = false;\n for (var i = 0; i < KEYS.length; i++) {\n var LOCK_KEY = KEYS[i];\n if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {\n var lockObj = STORAGE.getItem(LOCK_KEY);\n if (lockObj !== null) {\n lockObj = JSON.parse(lockObj);\n if ((lockObj.timeRefreshed === undefined && lockObj.timeAcquired < MIN_ALLOWED_TIME) ||\n (lockObj.timeRefreshed !== undefined && lockObj.timeRefreshed < MIN_ALLOWED_TIME)) {\n STORAGE.removeItem(LOCK_KEY);\n notifyWaiters = true;\n }\n }\n }\n }\n if (notifyWaiters) {\n SuperTokensLock.notifyWaiters();\n }\n };\n SuperTokensLock.waiters = undefined;\n return SuperTokensLock;\n}());\nexports.default = SuperTokensLock;\n","export default '2.0.3';\n","import { PopupConfigOptions } from './global';\nimport version from './version';\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;\n\n/**\n * @ignore\n */\nexport const DEFAULT_POPUP_CONFIG_OPTIONS: PopupConfigOptions = {\n timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n};\n\n/**\n * @ignore\n */\nexport const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;\n\n/**\n * @ignore\n */\nexport const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;\n\n/**\n * @ignore\n */\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10000;\n\nexport const CACHE_LOCATION_MEMORY = 'memory';\nexport const CACHE_LOCATION_LOCAL_STORAGE = 'localstorage';\n\n/**\n * @ignore\n */\nexport const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = 'Missing Refresh Token';\n\n/**\n * @ignore\n */\nexport const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = 'invalid refresh token';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SCOPE = 'openid profile email';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTH0_CLIENT = {\n name: 'auth0-spa-js',\n version: version\n};\n\nexport const DEFAULT_NOW_PROVIDER = () => Date.now();\n","/**\n * Thrown when network requests to the Auth server fail.\n */\nexport class GenericError extends Error {\n constructor(public error: string, public error_description: string) {\n super(error_description);\n Object.setPrototypeOf(this, GenericError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new GenericError(error, error_description);\n }\n}\n\n/**\n * Thrown when handling the redirect callback fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class AuthenticationError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * Thrown when silent auth times out (usually due to a configuration issue) or\n * when network requests to the Auth server timeout.\n */\nexport class TimeoutError extends GenericError {\n constructor() {\n super('timeout', 'Timeout');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Error thrown when the login popup times out (if the user does not complete auth)\n */\nexport class PopupTimeoutError extends TimeoutError {\n constructor(public popup: Window) {\n super();\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupTimeoutError.prototype);\n }\n}\n\nexport class PopupCancelledError extends GenericError {\n constructor(public popup: Window) {\n super('cancelled', 'Popup closed');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupCancelledError.prototype);\n }\n}\n\n/**\n * Error thrown when the token exchange results in a `mfa_required` error\n */\nexport class MfaRequiredError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public mfa_token: string\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when there is no refresh token to use\n */\nexport class MissingRefreshTokenError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_refresh_token',\n `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);\n }\n}\n\n/**\n * Returns an empty string when value is falsy, or when it's value is included in the exclude argument.\n * @param value The value to check\n * @param exclude An array of values that should result in an empty string.\n * @returns The value, or an empty string when falsy or included in the exclude argument.\n */\nfunction valueOrEmptyString(value: string, exclude: string[] = []) {\n return value && !exclude.includes(value) ? value : '';\n}\n","import { AuthenticationResult, PopupConfigOptions } from './global';\n\nimport {\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n CLEANUP_IFRAME_TIMEOUT_IN_SECONDS\n} from './constants';\n\nimport {\n PopupTimeoutError,\n TimeoutError,\n GenericError,\n PopupCancelledError\n} from './errors';\n\nexport const parseAuthenticationResult = (\n queryString: string\n): AuthenticationResult => {\n if (queryString.indexOf('#') > -1) {\n queryString = queryString.substring(0, queryString.indexOf('#'));\n }\n\n const searchParams = new URLSearchParams(queryString);\n\n return {\n state: searchParams.get('state')!,\n code: searchParams.get('code') || undefined,\n error: searchParams.get('error') || undefined,\n error_description: searchParams.get('error_description') || undefined\n };\n};\n\nexport const runIframe = (\n authorizeUrl: string,\n eventOrigin: string,\n timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n) => {\n return new Promise<AuthenticationResult>((res, rej) => {\n const iframe = window.document.createElement('iframe');\n\n iframe.setAttribute('width', '0');\n iframe.setAttribute('height', '0');\n iframe.style.display = 'none';\n\n const removeIframe = () => {\n if (window.document.body.contains(iframe)) {\n window.document.body.removeChild(iframe);\n window.removeEventListener('message', iframeEventHandler, false);\n }\n };\n\n let iframeEventHandler: (e: MessageEvent) => void;\n\n const timeoutSetTimeoutId = setTimeout(() => {\n rej(new TimeoutError());\n removeIframe();\n }, timeoutInSeconds * 1000);\n\n iframeEventHandler = function (e: MessageEvent) {\n if (e.origin != eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') return;\n\n const eventSource = e.source;\n\n if (eventSource) {\n (eventSource as any).close();\n }\n\n e.data.response.error\n ? rej(GenericError.fromPayload(e.data.response))\n : res(e.data.response);\n\n clearTimeout(timeoutSetTimeoutId);\n window.removeEventListener('message', iframeEventHandler, false);\n\n // Delay the removal of the iframe to prevent hanging loading status\n // in Chrome: https://github.com/auth0/auth0-spa-js/issues/240\n setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000);\n };\n\n window.addEventListener('message', iframeEventHandler, false);\n window.document.body.appendChild(iframe);\n iframe.setAttribute('src', authorizeUrl);\n });\n};\n\nexport const openPopup = (url: string) => {\n const width = 400;\n const height = 600;\n const left = window.screenX + (window.innerWidth - width) / 2;\n const top = window.screenY + (window.innerHeight - height) / 2;\n\n return window.open(\n url,\n 'auth0:authorize:popup',\n `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`\n );\n};\n\nexport const runPopup = (config: PopupConfigOptions) => {\n return new Promise<AuthenticationResult>((resolve, reject) => {\n let popupEventListener: (e: MessageEvent) => void;\n\n // Check each second if the popup is closed triggering a PopupCancelledError\n const popupTimer = setInterval(() => {\n if (config.popup && config.popup.closed) {\n clearInterval(popupTimer);\n clearTimeout(timeoutId);\n window.removeEventListener('message', popupEventListener, false);\n reject(new PopupCancelledError(config.popup));\n }\n }, 1000);\n\n const timeoutId = setTimeout(() => {\n clearInterval(popupTimer);\n reject(new PopupTimeoutError(config.popup));\n window.removeEventListener('message', popupEventListener, false);\n }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);\n\n popupEventListener = function (e: MessageEvent) {\n if (!e.data || e.data.type !== 'authorization_response') {\n return;\n }\n\n clearTimeout(timeoutId);\n clearInterval(popupTimer);\n window.removeEventListener('message', popupEventListener, false);\n config.popup.close();\n\n if (e.data.response.error) {\n return reject(GenericError.fromPayload(e.data.response));\n }\n\n resolve(e.data.response);\n };\n\n window.addEventListener('message', popupEventListener);\n });\n};\n\nexport const getCrypto = () => {\n return window.crypto;\n};\n\nexport const createRandomString = () => {\n const charset =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';\n let random = '';\n const randomValues = Array.from(\n getCrypto().getRandomValues(new Uint8Array(43))\n );\n randomValues.forEach(v => (random += charset[v % charset.length]));\n return random;\n};\n\nexport const encode = (value: string) => btoa(value);\nexport const decode = (value: string) => atob(value);\n\nconst stripUndefined = (params: any) => {\n return Object.keys(params)\n .filter(k => typeof params[k] !== 'undefined')\n .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});\n};\n\nexport const createQueryParams = ({ clientId: client_id, ...params }: any) => {\n return new URLSearchParams(\n stripUndefined({ client_id, ...params })\n ).toString();\n};\n\nexport const sha256 = async (s: string) => {\n const digestOp: any = getCrypto().subtle.digest(\n { name: 'SHA-256' },\n new TextEncoder().encode(s)\n );\n\n return await digestOp;\n};\n\nconst urlEncodeB64 = (input: string) => {\n const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' };\n return input.replace(/[+/=]/g, (m: string) => b64Chars[m]);\n};\n\n// https://stackoverflow.com/questions/30106476/\nconst decodeB64 = (input: string) =>\n decodeURIComponent(\n atob(input)\n .split('')\n .map(c => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join('')\n );\n\nexport const urlDecodeB64 = (input: string) =>\n decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));\n\nexport const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {\n const ie11SafeInput = new Uint8Array(input);\n return urlEncodeB64(\n window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))\n );\n};\n\nexport const validateCrypto = () => {\n if (!getCrypto()) {\n throw new Error(\n 'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'\n );\n }\n if (typeof getCrypto().subtle === 'undefined') {\n throw new Error(`\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/master/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n `);\n }\n};\n\n/**\n * @ignore\n */\nexport const getDomain = (domainUrl: string) => {\n if (!/^https?:\\/\\//.test(domainUrl)) {\n return `https://${domainUrl}`;\n }\n\n return domainUrl;\n};\n\n/**\n * @ignore\n */\nexport const getTokenIssuer = (\n issuer: string | undefined,\n domainUrl: string\n) => {\n if (issuer) {\n return issuer.startsWith('https://') ? issuer : `https://${issuer}/`;\n }\n\n return `${domainUrl}/`;\n};\n\nexport const parseNumber = (value: any): number | undefined => {\n if (typeof value !== 'string') {\n return value;\n }\n return parseInt(value, 10) || undefined;\n};\n","import { WorkerRefreshTokenMessage } from './worker.types';\n\n/**\n * Sends the specified message to the web worker\n * @param message The message to send\n * @param to The worker to send the message to\n */\nexport const sendMessage = (message: WorkerRefreshTokenMessage, to: Worker) =>\n new Promise(function (resolve, reject) {\n const messageChannel = new MessageChannel();\n\n messageChannel.port1.onmessage = function (event) {\n // Only for fetch errors, as these get retried\n if (event.data.error) {\n reject(new Error(event.data.error));\n } else {\n resolve(event.data);\n }\n messageChannel.port1.close();\n };\n\n to.postMessage(message, [messageChannel.port2]);\n });\n","import {\n DEFAULT_FETCH_TIMEOUT_MS,\n DEFAULT_SILENT_TOKEN_RETRY_COUNT\n} from './constants';\n\nimport { sendMessage } from './worker/worker.utils';\nimport { FetchOptions } from './global';\nimport { GenericError, MfaRequiredError } from './errors';\n\nexport const createAbortController = () => new AbortController();\n\nconst dofetch = async (fetchUrl: string, fetchOptions: FetchOptions) => {\n const response = await fetch(fetchUrl, fetchOptions);\n\n return {\n ok: response.ok,\n json: await response.json()\n };\n};\n\nconst fetchWithoutWorker = async (\n fetchUrl: string,\n fetchOptions: FetchOptions,\n timeout: number\n) => {\n const controller = createAbortController();\n fetchOptions.signal = controller.signal;\n\n let timeoutId: NodeJS.Timeout;\n\n // The promise will resolve with one of these two promises (the fetch or the timeout), whichever completes first.\n return Promise.race([\n dofetch(fetchUrl, fetchOptions),\n\n new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new Error(\"Timeout when executing 'fetch'\"));\n }, timeout);\n })\n ]).finally(() => {\n clearTimeout(timeoutId);\n });\n};\n\nconst fetchWithWorker = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n timeout: number,\n worker: Worker,\n useFormData?: boolean\n) => {\n return sendMessage(\n {\n auth: {\n audience,\n scope\n },\n timeout,\n fetchUrl,\n fetchOptions,\n useFormData\n },\n worker\n );\n};\n\nexport const switchFetch = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n worker?: Worker,\n useFormData?: boolean,\n timeout = DEFAULT_FETCH_TIMEOUT_MS\n): Promise<any> => {\n if (worker) {\n return fetchWithWorker(\n fetchUrl,\n audience,\n scope,\n fetchOptions,\n timeout,\n worker,\n useFormData\n );\n } else {\n return fetchWithoutWorker(fetchUrl, fetchOptions, timeout);\n }\n};\n\nexport async function getJSON<T>(\n url: string,\n timeout: number | undefined,\n audience: string,\n scope: string,\n options: FetchOptions,\n worker?: Worker,\n useFormData?: boolean\n): Promise<T> {\n let fetchError: null | Error = null;\n let response: any;\n\n for (let i = 0; i < DEFAULT_SILENT_TOKEN_RETRY_COUNT; i++) {\n try {\n response = await switchFetch(\n url,\n audience,\n scope,\n options,\n worker,\n useFormData,\n timeout\n );\n fetchError = null;\n break;\n } catch (e) {\n // Fetch only fails in the case of a network issue, so should be\n // retried here. Failure status (4xx, 5xx, etc) return a resolved Promise\n // with the failure in the body.\n // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n fetchError = e;\n }\n }\n\n if (fetchError) {\n throw fetchError;\n }\n\n const {\n json: { error, error_description, ...data },\n ok\n } = response;\n\n if (!ok) {\n const errorMessage =\n error_description || `HTTP error. Unable to fetch ${url}`;\n\n if (error === 'mfa_required') {\n throw new MfaRequiredError(error, errorMessage, data.mfa_token);\n }\n\n throw new GenericError(error || 'request_error', errorMessage);\n }\n\n return data;\n}\n","import { TokenEndpointOptions, TokenEndpointResponse } from './global';\nimport { DEFAULT_AUTH0_CLIENT } from './constants';\nimport { getJSON } from './http';\nimport { createQueryParams } from './utils';\n\nexport async function oauthToken(\n {\n baseUrl,\n timeout,\n audience,\n scope,\n auth0Client,\n useFormData,\n ...options\n }: TokenEndpointOptions,\n worker?: Worker\n) {\n const body = useFormData\n ? createQueryParams(options)\n : JSON.stringify(options);\n\n return await getJSON<TokenEndpointResponse>(\n `${baseUrl}/oauth/token`,\n timeout,\n audience || 'default',\n scope,\n {\n method: 'POST',\n body,\n headers: {\n 'Content-Type': useFormData\n ? 'application/x-www-form-urlencoded'\n : 'application/json',\n 'Auth0-Client': btoa(\n JSON.stringify(auth0Client || DEFAULT_AUTH0_CLIENT)\n )\n }\n },\n worker,\n useFormData\n );\n}\n","/**\n * @ignore\n */\nconst dedupe = (arr: string[]) => Array.from(new Set(arr));\n\n/**\n * @ignore\n */\nexport const getUniqueScopes = (...scopes: (string | undefined)[]) => {\n return dedupe(scopes.filter(Boolean).join(' ').trim().split(/\\s+/)).join(' ');\n};\n","import { IdToken, User } from '../global';\n\nexport const CACHE_KEY_PREFIX = '@@auth0spajs@@';\nexport const CACHE_KEY_ID_TOKEN_SUFFIX = '@@user@@';\n\nexport type CacheKeyData = {\n audience?: string;\n scope?: string;\n clientId: string;\n};\n\nexport class CacheKey {\n public clientId: string;\n public scope?: string;\n public audience?: string;\n\n constructor(\n data: CacheKeyData,\n public prefix: string = CACHE_KEY_PREFIX,\n public suffix?: string\n ) {\n this.clientId = data.clientId;\n this.scope = data.scope;\n this.audience = data.audience;\n }\n\n /**\n * Converts this `CacheKey` instance into a string for use in a cache\n * @returns A string representation of the key\n */\n toKey(): string {\n return [this.prefix, this.clientId, this.audience, this.scope, this.suffix]\n .filter(Boolean)\n .join('::');\n }\n\n /**\n * Converts a cache key string into a `CacheKey` instance.\n * @param key The key to convert\n * @returns An instance of `CacheKey`\n */\n static fromKey(key: string): CacheKey {\n const [prefix, clientId, audience, scope] = key.split('::');\n\n return new CacheKey({ clientId, scope, audience }, prefix);\n }\n\n /**\n * Utility function to build a `CacheKey` instance from a cache entry\n * @param entry The entry\n * @returns An instance of `CacheKey`\n */\n static fromCacheEntry(entry: CacheEntry): CacheKey {\n const { scope, audience, client_id: clientId } = entry;\n\n return new CacheKey({\n scope,\n audience,\n clientId\n });\n }\n}\n\nexport interface DecodedToken {\n claims: IdToken;\n user: User;\n}\n\nexport interface IdTokenEntry {\n id_token: string;\n decodedToken: DecodedToken;\n}\n\nexport type CacheEntry = {\n id_token?: string;\n access_token: string;\n expires_in: number;\n decodedToken?: DecodedToken;\n audience: string;\n scope: string;\n client_id: string;\n refresh_token?: string;\n oauthTokenScope?: string;\n};\n\nexport type WrappedCacheEntry = {\n body: Partial<CacheEntry>;\n expiresAt: number;\n};\n\nexport type KeyManifestEntry = {\n keys: string[];\n};\n\nexport type Cacheable = WrappedCacheEntry | KeyManifestEntry;\n\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport interface ICache {\n set<T = Cacheable>(key: string, entry: T): MaybePromise<void>;\n get<T = Cacheable>(key: string): MaybePromise<T | undefined>;\n remove(key: string): MaybePromise<void>;\n allKeys?(): MaybePromise<string[]>;\n}\n","import { ICache, Cacheable, CACHE_KEY_PREFIX, MaybePromise } from './shared';\n\nexport class LocalStorageCache implements ICache {\n public set<T = Cacheable>(key: string, entry: T) {\n localStorage.setItem(key, JSON.stringify(entry));\n }\n\n public get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const json = window.localStorage.getItem(key);\n\n if (!json) return;\n\n try {\n const payload = JSON.parse(json) as T;\n return payload;\n /* c8 ignore next 3 */\n } catch (e) {\n return;\n }\n }\n\n public remove(key: string) {\n localStorage.removeItem(key);\n }\n\n public allKeys() {\n return Object.keys(window.localStorage).filter(key =>\n key.startsWith(CACHE_KEY_PREFIX)\n );\n }\n}\n","import { Cacheable, ICache, MaybePromise } from './shared';\n\nexport class InMemoryCache {\n public enclosedCache: ICache = (function () {\n let cache: Record<string, unknown> = {};\n\n return {\n set<T = Cacheable>(key: string, entry: T) {\n cache[key] = entry;\n },\n\n get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const cacheEntry = cache[key] as T;\n\n if (!cacheEntry) {\n return;\n }\n\n return cacheEntry;\n },\n\n remove(key: string) {\n delete cache[key];\n },\n\n allKeys(): string[] {\n return Object.keys(cache);\n }\n };\n })();\n}\n","import { DEFAULT_NOW_PROVIDER } from '../constants';\nimport { CacheKeyManifest } from './key-manifest';\n\nimport {\n CacheEntry,\n ICache,\n CacheKey,\n CACHE_KEY_PREFIX,\n WrappedCacheEntry,\n DecodedToken,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n IdTokenEntry\n} from './shared';\n\nconst DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;\n\nexport class CacheManager {\n private nowProvider: () => number | Promise<number>;\n\n constructor(\n private cache: ICache,\n private keyManifest?: CacheKeyManifest,\n nowProvider?: () => number | Promise<number>\n ) {\n this.nowProvider = nowProvider || DEFAULT_NOW_PROVIDER;\n }\n\n async setIdToken(\n clientId: string,\n idToken: string,\n decodedToken: DecodedToken\n ): Promise<void> {\n const cacheKey = this.getIdTokenCacheKey(clientId);\n await this.cache.set(cacheKey, {\n id_token: idToken,\n decodedToken\n });\n await this.keyManifest?.add(cacheKey);\n }\n\n async getIdToken(cacheKey: CacheKey): Promise<IdTokenEntry | undefined> {\n const entry = await this.cache.get<IdTokenEntry>(\n this.getIdTokenCacheKey(cacheKey.clientId)\n );\n\n if (!entry && cacheKey.scope && cacheKey.audience) {\n const entryByScope = await this.get(cacheKey);\n\n if (!entryByScope) {\n return;\n }\n\n if (!entryByScope.id_token || !entryByScope.decodedToken) {\n return;\n }\n\n return {\n id_token: entryByScope.id_token,\n decodedToken: entryByScope.decodedToken\n };\n }\n\n if (!entry) {\n return;\n }\n\n return { id_token: entry.id_token, decodedToken: entry.decodedToken };\n }\n\n async get(\n cacheKey: CacheKey,\n expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS\n ): Promise<Partial<CacheEntry> | undefined> {\n let wrappedEntry = await this.cache.get<WrappedCacheEntry>(\n cacheKey.toKey()\n );\n\n if (!wrappedEntry) {\n const keys = await this.getCacheKeys();\n\n if (!keys) return;\n\n const matchedKey = this.matchExistingCacheKey(cacheKey, keys);\n\n if (matchedKey) {\n wrappedEntry = await this.cache.get<WrappedCacheEntry>(matchedKey);\n }\n }\n\n // If we still don't have an entry, exit.\n if (!wrappedEntry) {\n return;\n }\n\n const now = await this.nowProvider();\n const nowSeconds = Math.floor(now / 1000);\n\n if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {\n if (wrappedEntry.body.refresh_token) {\n wrappedEntry.body = {\n refresh_token: wrappedEntry.body.refresh_token\n };\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n return wrappedEntry.body;\n }\n\n await this.cache.remove(cacheKey.toKey());\n await this.keyManifest?.remove(cacheKey.toKey());\n\n return;\n }\n\n return wrappedEntry.body;\n }\n\n async set(entry: CacheEntry): Promise<void> {\n const cacheKey = new CacheKey({\n clientId: entry.client_id,\n scope: entry.scope,\n audience: entry.audience\n });\n\n const wrappedEntry = await this.wrapCacheEntry(entry);\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n await this.keyManifest?.add(cacheKey.toKey());\n }\n\n async clear(clientId?: string): Promise<void> {\n const keys = await this.getCacheKeys();\n\n /* c8 ignore next */\n if (!keys) return;\n\n await keys\n .filter(key => (clientId ? key.includes(clientId) : true))\n .reduce(async (memo, key) => {\n await memo;\n await this.cache.remove(key);\n }, Promise.resolve());\n\n await this.keyManifest?.clear();\n }\n\n private async wrapCacheEntry(entry: CacheEntry): Promise<WrappedCacheEntry> {\n const now = await this.nowProvider();\n const expiresInTime = Math.floor(now / 1000) + entry.expires_in;\n\n return {\n body: entry,\n expiresAt: expiresInTime\n };\n }\n\n private async getCacheKeys(): Promise<string[] | undefined> {\n if (this.keyManifest) {\n return (await this.keyManifest.get())?.keys;\n } else if (this.cache.allKeys) {\n return this.cache.allKeys();\n }\n }\n\n /**\n * Returns the cache key to be used to store the id token\n * @param clientId The client id used to link to the id token\n * @returns The constructed cache key, as a string, to store the id token\n */\n private getIdTokenCacheKey(clientId: string) {\n return new CacheKey(\n { clientId },\n CACHE_KEY_PREFIX,\n CACHE_KEY_ID_TOKEN_SUFFIX\n ).toKey();\n }\n\n /**\n * Finds the corresponding key in the cache based on the provided cache key.\n * The keys inside the cache are in the format {prefix}::{clientId}::{audience}::{scope}.\n * The first key in the cache that satisfies the following conditions is returned\n * - `prefix` is strict equal to Auth0's internally configured `keyPrefix`\n * - `clientId` is strict equal to the `cacheKey.clientId`\n * - `audience` is strict equal to the `cacheKey.audience`\n * - `scope` contains at least all the `cacheKey.scope` values\n * *\n * @param keyToMatch The provided cache key\n * @param allKeys A list of existing cache keys\n */\n private matchExistingCacheKey(keyToMatch: CacheKey, allKeys: Array<string>) {\n return allKeys.filter(key => {\n const cacheKey = CacheKey.fromKey(key);\n const scopeSet = new Set(cacheKey.scope && cacheKey.scope.split(' '));\n const scopesToMatch = keyToMatch.scope?.split(' ') || [];\n\n const hasAllScopes =\n cacheKey.scope &&\n scopesToMatch.reduce(\n (acc, current) => acc && scopeSet.has(current),\n true\n );\n\n return (\n cacheKey.prefix === CACHE_KEY_PREFIX &&\n cacheKey.clientId === keyToMatch.clientId &&\n cacheKey.audience === keyToMatch.audience &&\n hasAllScopes\n );\n })[0];\n }\n}\n","import { ClientStorage } from './storage';\n\nconst TRANSACTION_STORAGE_KEY_PREFIX = 'a0.spajs.txs';\n\ninterface Transaction {\n nonce: string;\n scope: string;\n audience: string;\n appState?: any;\n code_verifier: string;\n redirect_uri?: string;\n organizationId?: string;\n state?: string;\n}\n\nexport class TransactionManager {\n private transaction: Transaction | undefined;\n private storageKey: string;\n\n constructor(private storage: ClientStorage, private clientId: string) {\n this.storageKey = `${TRANSACTION_STORAGE_KEY_PREFIX}.${this.clientId}`;\n this.transaction = this.storage.get(this.storageKey);\n }\n\n public create(transaction: Transaction) {\n this.transaction = transaction;\n\n this.storage.save(this.storageKey, transaction, {\n daysUntilExpire: 1\n });\n }\n\n public get(): Transaction | undefined {\n return this.transaction;\n }\n\n public remove() {\n delete this.transaction;\n this.storage.remove(this.storageKey);\n }\n}\n","import { urlDecodeB64 } from './utils';\nimport { IdToken, JWTVerifyOptions } from './global';\n\nconst isNumber = (n: any) => typeof n === 'number';\n\nconst idTokendecoded = [\n 'iss',\n 'aud',\n 'exp',\n 'nbf',\n 'iat',\n 'jti',\n 'azp',\n 'nonce',\n 'auth_time',\n 'at_hash',\n 'c_hash',\n 'acr',\n 'amr',\n 'sub_jwk',\n 'cnf',\n 'sip_from_tag',\n 'sip_date',\n 'sip_callid',\n 'sip_cseq_num',\n 'sip_via_branch',\n 'orig',\n 'dest',\n 'mky',\n 'events',\n 'toe',\n 'txn',\n 'rph',\n 'sid',\n 'vot',\n 'vtm'\n];\n\nexport const decode = (token: string) => {\n const parts = token.split('.');\n const [header, payload, signature] = parts;\n\n if (parts.length !== 3 || !header || !payload || !signature) {\n throw new Error('ID token could not be decoded');\n }\n const payloadJSON = JSON.parse(urlDecodeB64(payload));\n const claims: IdToken = { __raw: token };\n const user: any = {};\n Object.keys(payloadJSON).forEach(k => {\n claims[k] = payloadJSON[k];\n if (!idTokendecoded.includes(k)) {\n user[k] = payloadJSON[k];\n }\n });\n return {\n encoded: { header, payload, signature },\n header: JSON.parse(urlDecodeB64(header)),\n claims,\n user\n };\n};\n\nexport const verify = (options: JWTVerifyOptions) => {\n if (!options.id_token) {\n throw new Error('ID token is required but missing');\n }\n\n const decoded = decode(options.id_token);\n\n if (!decoded.claims.iss) {\n throw new Error(\n 'Issuer (iss) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.claims.iss !== options.iss) {\n throw new Error(\n `Issuer (iss) claim mismatch in the ID token; expected \"${options.iss}\", found \"${decoded.claims.iss}\"`\n );\n }\n\n if (!decoded.user.sub) {\n throw new Error(\n 'Subject (sub) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.header.alg !== 'RS256') {\n throw new Error(\n `Signature algorithm of \"${decoded.header.alg}\" is not supported. Expected the ID token to be signed with \"RS256\".`\n );\n }\n\n if (\n !decoded.claims.aud ||\n !(\n typeof decoded.claims.aud === 'string' ||\n Array.isArray(decoded.claims.aud)\n )\n ) {\n throw new Error(\n 'Audience (aud) claim must be a string or array of strings present in the ID token'\n );\n }\n if (Array.isArray(decoded.claims.aud)) {\n if (!decoded.claims.aud.includes(options.aud)) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${\n options.aud\n }\" but was not one of \"${decoded.claims.aud.join(', ')}\"`\n );\n }\n if (decoded.claims.aud.length > 1) {\n if (!decoded.claims.azp) {\n throw new Error(\n 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values'\n );\n }\n if (decoded.claims.azp !== options.aud) {\n throw new Error(\n `Authorized Party (azp) claim mismatch in the ID token; expected \"${options.aud}\", found \"${decoded.claims.azp}\"`\n );\n }\n }\n } else if (decoded.claims.aud !== options.aud) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${options.aud}\" but found \"${decoded.claims.aud}\"`\n );\n }\n if (options.nonce) {\n if (!decoded.claims.nonce) {\n throw new Error(\n 'Nonce (nonce) claim must be a string present in the ID token'\n );\n }\n if (decoded.claims.nonce !== options.nonce) {\n throw new Error(\n `Nonce (nonce) claim mismatch in the ID token; expected \"${options.nonce}\", found \"${decoded.claims.nonce}\"`\n );\n }\n }\n\n if (options.max_age && !isNumber(decoded.claims.auth_time)) {\n throw new Error(\n 'Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified'\n );\n }\n\n /* c8 ignore next 5 */\n if (decoded.claims.exp == null || !isNumber(decoded.claims.exp)) {\n throw new Error(\n 'Expiration Time (exp) claim must be a number present in the ID token'\n );\n }\n if (!isNumber(decoded.claims.iat)) {\n throw new Error(\n 'Issued At (iat) claim must be a number present in the ID token'\n );\n }\n\n const leeway = options.leeway || 60;\n const now = new Date(options.now || Date.now());\n const expDate = new Date(0);\n\n expDate.setUTCSeconds(decoded.claims.exp + leeway);\n\n if (now > expDate) {\n throw new Error(\n `Expiration Time (exp) claim error in the ID token; current time (${now}) is after expiration time (${expDate})`\n );\n }\n\n if (decoded.claims.nbf != null && isNumber(decoded.claims.nbf)) {\n const nbfDate = new Date(0);\n nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);\n if (now < nbfDate) {\n throw new Error(\n `Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${now}) is before ${nbfDate}`\n );\n }\n }\n\n if (decoded.claims.auth_time != null && isNumber(decoded.claims.auth_time)) {\n const authTimeDate = new Date(0);\n authTimeDate.setUTCSeconds(\n parseInt(decoded.claims.auth_time) + (options.max_age as number) + leeway\n );\n\n if (now > authTimeDate) {\n throw new Error(\n `Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${now}) is after last auth at ${authTimeDate}`\n );\n }\n }\n\n if (options.organizationId) {\n if (!decoded.claims.org_id) {\n throw new Error(\n 'Organization ID (org_id) claim must be a string present in the ID token'\n );\n } else if (options.organizationId !== decoded.claims.org_id) {\n throw new Error(\n `Organization ID (org_id) claim mismatch in the ID token; expected \"${options.organizationId}\", found \"${decoded.claims.org_id}\"`\n );\n }\n }\n\n return decoded;\n};\n","\"use strict\";\r\nvar __assign = (this && this.__assign) || function () {\r\n __assign = Object.assign || function(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\nexports.__esModule = true;\r\nfunction stringifyAttribute(name, value) {\r\n if (!value) {\r\n return '';\r\n }\r\n var stringified = '; ' + name;\r\n if (value === true) {\r\n return stringified; // boolean attributes shouldn't have a value\r\n }\r\n return stringified + '=' + value;\r\n}\r\nfunction stringifyAttributes(attributes) {\r\n if (typeof attributes.expires === 'number') {\r\n var expires = new Date();\r\n expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);\r\n attributes.expires = expires;\r\n }\r\n return stringifyAttribute('Expires', attributes.expires ? attributes.expires.toUTCString() : '')\r\n + stringifyAttribute('Domain', attributes.domain)\r\n + stringifyAttribute('Path', attributes.path)\r\n + stringifyAttribute('Secure', attributes.secure)\r\n + stringifyAttribute('SameSite', attributes.sameSite);\r\n}\r\nfunction encode(name, value, attributes) {\r\n return encodeURIComponent(name)\r\n .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) // allowed special characters\r\n .replace(/\\(/g, '%28').replace(/\\)/g, '%29') // replace opening and closing parens\r\n + '=' + encodeURIComponent(value)\r\n // allowed special characters\r\n .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent)\r\n + stringifyAttributes(attributes);\r\n}\r\nexports.encode = encode;\r\nfunction parse(cookieString) {\r\n var result = {};\r\n var cookies = cookieString ? cookieString.split('; ') : [];\r\n var rdecode = /(%[\\dA-F]{2})+/gi;\r\n for (var i = 0; i < cookies.length; i++) {\r\n var parts = cookies[i].split('=');\r\n var cookie = parts.slice(1).join('=');\r\n if (cookie.charAt(0) === '\"') {\r\n cookie = cookie.slice(1, -1);\r\n }\r\n try {\r\n var name_1 = parts[0].replace(rdecode, decodeURIComponent);\r\n result[name_1] = cookie.replace(rdecode, decodeURIComponent);\r\n }\r\n catch (e) {\r\n // ignore cookies with invalid name/value encoding\r\n }\r\n }\r\n return result;\r\n}\r\nexports.parse = parse;\r\nfunction getAll() {\r\n return parse(document.cookie);\r\n}\r\nexports.getAll = getAll;\r\nfunction get(name) {\r\n return getAll()[name];\r\n}\r\nexports.get = get;\r\nfunction set(name, value, attributes) {\r\n document.cookie = encode(name, value, __assign({ path: '/' }, attributes));\r\n}\r\nexports.set = set;\r\nfunction remove(name, attributes) {\r\n set(name, '', __assign(__assign({}, attributes), { expires: -1 }));\r\n}\r\nexports.remove = remove;\r\n","import * as Cookies from 'es-cookie';\n\ninterface ClientStorageOptions {\n daysUntilExpire?: number;\n cookieDomain?: string;\n}\n\n/**\n * Defines a type that handles storage to/from a storage location\n */\nexport type ClientStorage = {\n get<T extends Object>(key: string): T | undefined;\n save(key: string, value: any, options?: ClientStorageOptions): void;\n remove(key: string, options?: ClientStorageOptions): void;\n};\n\n/**\n * A storage protocol for marshalling data to/from cookies\n */\nexport const CookieStorage = {\n get<T extends Object>(key: string) {\n const value = Cookies.get(key);\n\n if (typeof value === 'undefined') {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = {\n secure: true,\n sameSite: 'none'\n };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(key, JSON.stringify(value), cookieAttributes);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n }\n} as ClientStorage;\n\n/**\n * @ignore\n */\nconst LEGACY_PREFIX = '_legacy_';\n\n/**\n * Cookie storage that creates a cookie for modern and legacy browsers.\n * See: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients\n */\nexport const CookieStorageWithLegacySameSite = {\n get<T extends Object>(key: string) {\n const value = CookieStorage.get<T>(key);\n\n if (value) {\n return value;\n }\n\n return CookieStorage.get<T>(`${LEGACY_PREFIX}${key}`);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = { secure: true };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(\n `${LEGACY_PREFIX}${key}`,\n JSON.stringify(value),\n cookieAttributes\n );\n CookieStorage.save(key, value, options);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n CookieStorage.remove(key, options);\n CookieStorage.remove(`${LEGACY_PREFIX}${key}`, options);\n }\n} as ClientStorage;\n\n/**\n * A storage protocol for marshalling data to/from session storage\n */\nexport const SessionStorage = {\n get<T extends Object>(key: string) {\n /* c8 ignore next 3 */\n if (typeof sessionStorage === 'undefined') {\n return;\n }\n\n const value = sessionStorage.getItem(key);\n\n if (value == null) {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any): void {\n sessionStorage.setItem(key, JSON.stringify(value));\n },\n\n remove(key: string) {\n sessionStorage.removeItem(key);\n }\n} as ClientStorage;\n","const singlePromiseMap: Record<string, Promise<any>> = {};\n\nexport const singlePromise = <T>(\n cb: () => Promise<T>,\n key: string\n): Promise<T> => {\n let promise: null | Promise<T> = singlePromiseMap[key];\n if (!promise) {\n promise = cb().finally(() => {\n delete singlePromiseMap[key];\n promise = null;\n });\n singlePromiseMap[key] = promise;\n }\n return promise;\n};\n\nexport const retryPromise = async (\n cb: () => Promise<boolean>,\n maxNumberOfRetries = 3\n) => {\n for (let i = 0; i < maxNumberOfRetries; i++) {\n if (await cb()) {\n return true;\n }\n }\n\n return false;\n};\n","import {\n CACHE_KEY_PREFIX,\n ICache,\n KeyManifestEntry,\n MaybePromise\n} from './shared';\n\nexport class CacheKeyManifest {\n private readonly manifestKey: string;\n\n constructor(private cache: ICache, private clientId: string) {\n this.manifestKey = this.createManifestKeyFrom(this.clientId);\n }\n\n async add(key: string): Promise<void> {\n const keys = new Set(\n (await this.cache.get<KeyManifestEntry>(this.manifestKey))?.keys || []\n );\n\n keys.add(key);\n\n await this.cache.set<KeyManifestEntry>(this.manifestKey, {\n keys: [...keys]\n });\n }\n\n async remove(key: string): Promise<void> {\n const entry = await this.cache.get<KeyManifestEntry>(this.manifestKey);\n\n if (entry) {\n const keys = new Set(entry.keys);\n keys.delete(key);\n\n if (keys.size > 0) {\n return await this.cache.set(this.manifestKey, { keys: [...keys] });\n }\n\n return await this.cache.remove(this.manifestKey);\n }\n }\n\n get(): MaybePromise<KeyManifestEntry | undefined> {\n return this.cache.get<KeyManifestEntry>(this.manifestKey);\n }\n\n clear(): MaybePromise<void> {\n return this.cache.remove(this.manifestKey);\n }\n\n private createManifestKeyFrom(clientId: string): string {\n return `${CACHE_KEY_PREFIX}::${clientId}`;\n }\n}\n","import { ICache, InMemoryCache, LocalStorageCache } from './cache';\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n LogoutOptions\n} from './global';\nimport { getUniqueScopes } from './scope';\n\n/**\n * @ignore\n */\nexport const GET_TOKEN_SILENTLY_LOCK_KEY = 'auth0.lock.getTokenSilently';\n\n/**\n * @ignore\n */\nexport const buildOrganizationHintCookieName = (clientId: string) =>\n `auth0.${clientId}.organization_hint`;\n\n/**\n * @ignore\n */\nexport const OLD_IS_AUTHENTICATED_COOKIE_NAME = 'auth0.is.authenticated';\n\n/**\n * @ignore\n */\nexport const buildIsAuthenticatedCookieName = (clientId: string) =>\n `auth0.${clientId}.is.authenticated`;\n\n/**\n * @ignore\n */\nconst cacheLocationBuilders: Record<string, () => ICache> = {\n memory: () => new InMemoryCache().enclosedCache,\n localstorage: () => new LocalStorageCache()\n};\n\n/**\n * @ignore\n */\nexport const cacheFactory = (location: string) => {\n return cacheLocationBuilders[location];\n};\n\n/**\n * @ignore\n */\nexport const getAuthorizeParams = (\n clientOptions: Auth0ClientOptions & {\n authorizationParams: AuthorizationParams;\n },\n scope: string,\n authorizationParams: AuthorizationParams,\n state: string,\n nonce: string,\n code_challenge: string,\n redirect_uri: string | undefined,\n response_mode: string | undefined\n): AuthorizeOptions => {\n return {\n client_id: clientOptions.clientId,\n ...clientOptions.authorizationParams,\n ...authorizationParams,\n scope: getUniqueScopes(scope, authorizationParams.scope),\n response_type: 'code',\n response_mode: response_mode || 'query',\n state,\n nonce,\n redirect_uri:\n redirect_uri || clientOptions.authorizationParams.redirect_uri,\n code_challenge,\n code_challenge_method: 'S256'\n };\n};\n\n/**\n * @ignore\n *\n * Function used to provide support for the deprecated onRedirect through openUrl.\n */\nexport const patchOpenUrlWithOnRedirect = <\n T extends Pick<LogoutOptions, 'openUrl' | 'onRedirect'>\n>(\n options: T\n) => {\n const { openUrl, onRedirect, ...originalOptions } = options;\n\n const result = {\n ...originalOptions,\n openUrl: openUrl === false || openUrl ? openUrl : onRedirect\n };\n\n return result as T;\n};\n","import Lock from 'browser-tabs-lock';\n\nimport {\n createQueryParams,\n runPopup,\n parseAuthenticationResult,\n encode,\n createRandomString,\n runIframe,\n sha256,\n bufferToBase64UrlEncoded,\n validateCrypto,\n openPopup,\n getDomain,\n getTokenIssuer,\n parseNumber\n} from './utils';\n\nimport { oauthToken } from './api';\n\nimport { getUniqueScopes } from './scope';\n\nimport {\n InMemoryCache,\n ICache,\n CacheKey,\n CacheManager,\n CacheEntry,\n IdTokenEntry,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n DecodedToken\n} from './cache';\n\nimport { TransactionManager } from './transaction-manager';\nimport { verify as verifyIdToken } from './jwt';\nimport {\n AuthenticationError,\n GenericError,\n MissingRefreshTokenError,\n TimeoutError\n} from './errors';\n\nimport {\n ClientStorage,\n CookieStorage,\n CookieStorageWithLegacySameSite,\n SessionStorage\n} from './storage';\n\nimport {\n CACHE_LOCATION_MEMORY,\n DEFAULT_POPUP_CONFIG_OPTIONS,\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n MISSING_REFRESH_TOKEN_ERROR_MESSAGE,\n DEFAULT_SCOPE,\n DEFAULT_SESSION_CHECK_EXPIRY_DAYS,\n DEFAULT_AUTH0_CLIENT,\n INVALID_REFRESH_TOKEN_ERROR_MESSAGE,\n DEFAULT_NOW_PROVIDER,\n DEFAULT_FETCH_TIMEOUT_MS\n} from './constants';\n\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n RedirectLoginOptions,\n PopupLoginOptions,\n PopupConfigOptions,\n RedirectLoginResult,\n GetTokenSilentlyOptions,\n GetTokenWithPopupOptions,\n LogoutOptions,\n CacheLocation,\n LogoutUrlOptions,\n User,\n IdToken,\n GetTokenSilentlyVerboseResponse,\n TokenEndpointResponse\n} from './global';\n\n// @ts-ignore\nimport TokenWorker from './worker/token.worker.ts';\nimport { singlePromise, retryPromise } from './promise-utils';\nimport { CacheKeyManifest } from './cache/key-manifest';\nimport {\n buildIsAuthenticatedCookieName,\n buildOrganizationHintCookieName,\n cacheFactory,\n getAuthorizeParams,\n GET_TOKEN_SILENTLY_LOCK_KEY,\n OLD_IS_AUTHENTICATED_COOKIE_NAME,\n patchOpenUrlWithOnRedirect\n} from './Auth0Client.utils';\n\n/**\n * @ignore\n */\ntype GetTokenSilentlyResult = TokenEndpointResponse & {\n decodedToken: ReturnType<typeof verifyIdToken>;\n scope: string;\n oauthTokenScope?: string;\n audience: string;\n};\n\n/**\n * @ignore\n */\nconst lock = new Lock();\n\n/**\n * Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).\n */\nexport class Auth0Client {\n private readonly transactionManager: TransactionManager;\n private readonly cacheManager: CacheManager;\n private readonly domainUrl: string;\n private readonly tokenIssuer: string;\n private readonly scope: string;\n private readonly cookieStorage: ClientStorage;\n private readonly sessionCheckExpiryDays: number;\n private readonly orgHintCookieName: string;\n private readonly isAuthenticatedCookieName: string;\n private readonly nowProvider: () => number | Promise<number>;\n private readonly httpTimeoutMs: number;\n private readonly options: Auth0ClientOptions & {\n authorizationParams: AuthorizationParams;\n };\n private readonly userCache: ICache = new InMemoryCache().enclosedCache;\n\n private worker?: Worker;\n\n private readonly defaultOptions: Partial<Auth0ClientOptions> = {\n authorizationParams: {\n scope: DEFAULT_SCOPE\n },\n useRefreshTokensFallback: false,\n useFormData: true\n };\n\n constructor(options: Auth0ClientOptions) {\n this.options = {\n ...this.defaultOptions,\n ...options,\n authorizationParams: {\n ...this.defaultOptions.authorizationParams,\n ...options.authorizationParams\n }\n };\n\n typeof window !== 'undefined' && validateCrypto();\n\n if (options.cache && options.cacheLocation) {\n console.warn(\n 'Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.'\n );\n }\n\n let cacheLocation: CacheLocation | undefined;\n let cache: ICache;\n\n if (options.cache) {\n cache = options.cache;\n } else {\n cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY;\n\n if (!cacheFactory(cacheLocation)) {\n throw new Error(`Invalid cache location \"${cacheLocation}\"`);\n }\n\n cache = cacheFactory(cacheLocation)();\n }\n\n this.httpTimeoutMs = options.httpTimeoutInSeconds\n ? options.httpTimeoutInSeconds * 1000\n : DEFAULT_FETCH_TIMEOUT_MS;\n\n this.cookieStorage =\n options.legacySameSiteCookie === false\n ? CookieStorage\n : CookieStorageWithLegacySameSite;\n\n this.orgHintCookieName = buildOrganizationHintCookieName(\n this.options.clientId\n );\n\n this.isAuthenticatedCookieName = buildIsAuthenticatedCookieName(\n this.options.clientId\n );\n\n this.sessionCheckExpiryDays =\n options.sessionCheckExpiryDays || DEFAULT_SESSION_CHECK_EXPIRY_DAYS;\n\n const transactionStorage = options.useCookiesForTransactions\n ? this.cookieStorage\n : SessionStorage;\n\n // Construct the scopes based on the following:\n // 1. Always include `openid`\n // 2. Include the scopes provided in `authorizationParams. This defaults to `profile email`\n // 3. Add `offline_access` if `useRefreshTokens` is enabled\n this.scope = getUniqueScopes(\n 'openid',\n this.options.authorizationParams.scope,\n this.options.useRefreshTokens ? 'offline_access' : ''\n );\n\n this.transactionManager = new TransactionManager(\n transactionStorage,\n this.options.clientId\n );\n\n this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER;\n\n this.cacheManager = new CacheManager(\n cache,\n !cache.allKeys\n ? new CacheKeyManifest(cache, this.options.clientId)\n : undefined,\n this.nowProvider\n );\n\n this.domainUrl = getDomain(this.options.domain);\n this.tokenIssuer = getTokenIssuer(this.options.issuer, this.domainUrl);\n\n // Don't use web workers unless using refresh tokens in memory\n if (\n typeof window !== 'undefined' &&\n window.Worker &&\n this.options.useRefreshTokens &&\n cacheLocation === CACHE_LOCATION_MEMORY\n ) {\n this.worker = new TokenWorker();\n }\n }\n\n private _url(path: string) {\n const auth0Client = encodeURIComponent(\n btoa(JSON.stringify(this.options.auth0Client || DEFAULT_AUTH0_CLIENT))\n );\n return `${this.domainUrl}${path}&auth0Client=${auth0Client}`;\n }\n\n private _authorizeUrl(authorizeOptions: AuthorizeOptions) {\n return this._url(`/authorize?${createQueryParams(authorizeOptions)}`);\n }\n\n private async _verifyIdToken(\n id_token: string,\n nonce?: string,\n organizationId?: string\n ) {\n const now = await this.nowProvider();\n\n return verifyIdToken({\n iss: this.tokenIssuer,\n aud: this.options.clientId,\n id_token,\n nonce,\n organizationId,\n leeway: this.options.leeway,\n max_age: parseNumber(this.options.authorizationParams.max_age),\n now\n });\n }\n\n private _processOrgIdHint(organizationId?: string) {\n if (organizationId) {\n this.cookieStorage.save(this.orgHintCookieName, organizationId, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n } else {\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n }\n }\n\n private async _prepareAuthorizeUrl(\n authorizationParams: AuthorizationParams,\n authorizeOptions?: Partial<AuthorizeOptions>,\n fallbackRedirectUri?: string\n ): Promise<{\n scope: string;\n audience: string;\n redirect_uri?: string;\n nonce: string;\n code_verifier: string;\n state: string;\n url: string;\n }> {\n const state = encode(createRandomString());\n const nonce = encode(createRandomString());\n const code_verifier = createRandomString();\n const code_challengeBuffer = await sha256(code_verifier);\n const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);\n\n const params = getAuthorizeParams(\n this.options,\n this.scope,\n authorizationParams,\n state,\n nonce,\n code_challenge,\n authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n fallbackRedirectUri,\n authorizeOptions?.response_mode\n );\n\n const url = this._authorizeUrl(params);\n\n return {\n nonce,\n code_verifier,\n scope: params.scope,\n audience: params.audience || 'default',\n redirect_uri: params.redirect_uri,\n state,\n url\n };\n }\n\n /**\n * ```js\n * try {\n * await auth0.loginWithPopup(options);\n * } catch(e) {\n * if (e instanceof PopupCancelledError) {\n * // Popup was closed before login completed\n * }\n * }\n * ```\n *\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * IMPORTANT: This method has to be called from an event handler\n * that was started by the user like a button click, for example,\n * otherwise the popup will be blocked in most browsers.\n *\n * @param options\n * @param config\n */\n public async loginWithPopup(\n options?: PopupLoginOptions,\n config?: PopupConfigOptions\n ) {\n options = options || {};\n config = config || {};\n\n if (!config.popup) {\n config.popup = openPopup('');\n\n if (!config.popup) {\n throw new Error(\n 'Unable to open a popup for loginWithPopup - window.open returned `null`'\n );\n }\n }\n\n const params = await this._prepareAuthorizeUrl(\n options.authorizationParams || {},\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n config.popup.location.href = params.url;\n\n const codeResult = await runPopup({\n ...config,\n timeoutInSeconds:\n config.timeoutInSeconds ||\n this.options.authorizeTimeoutInSeconds ||\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n });\n\n if (params.state !== codeResult.state) {\n throw new Error('Invalid state');\n }\n\n const organizationId =\n options.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n await this._requestToken(\n {\n audience: params.audience,\n scope: params.scope,\n code_verifier: params.code_verifier,\n grant_type: 'authorization_code',\n code: codeResult.code as string,\n redirect_uri: params.redirect_uri\n },\n {\n nonceIn: params.nonce,\n organizationId\n }\n );\n }\n\n /**\n * ```js\n * const user = await auth0.getUser();\n * ```\n *\n * Returns the user information if available (decoded\n * from the `id_token`).\n *\n * @typeparam TUser The type to return, has to extend {@link User}.\n */\n public async getUser<TUser extends User>(): Promise<TUser | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.user as TUser;\n }\n\n /**\n * ```js\n * const claims = await auth0.getIdTokenClaims();\n * ```\n *\n * Returns all claims from the id_token if available.\n */\n public async getIdTokenClaims(): Promise<IdToken | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.claims;\n }\n\n /**\n * ```js\n * await auth0.loginWithRedirect(options);\n * ```\n *\n * Performs a redirect to `/authorize` using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated.\n *\n * @param options\n */\n public async loginWithRedirect<TAppState = any>(\n options: RedirectLoginOptions<TAppState> = {}\n ) {\n const { openUrl, fragment, appState, ...urlOptions } =\n patchOpenUrlWithOnRedirect(options);\n\n const organizationId =\n urlOptions.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n const { url, ...transaction } = await this._prepareAuthorizeUrl(\n urlOptions.authorizationParams || {}\n );\n\n this.transactionManager.create({\n ...transaction,\n appState,\n ...(organizationId && { organizationId })\n });\n\n const urlWithFragment = fragment ? `${url}#${fragment}` : url;\n\n if (openUrl) {\n await openUrl(urlWithFragment);\n } else {\n window.location.assign(urlWithFragment);\n }\n }\n\n /**\n * After the browser redirects back to the callback page,\n * call `handleRedirectCallback` to handle success and error\n * responses from Auth0. If the response is successful, results\n * will be valid according to their expiration times.\n */\n public async handleRedirectCallback<TAppState = any>(\n url: string = window.location.href\n ): Promise<RedirectLoginResult<TAppState>> {\n const queryStringFragments = url.split('?').slice(1);\n\n if (queryStringFragments.length === 0) {\n throw new Error('There are no query params available for parsing.');\n }\n\n const { state, code, error, error_description } = parseAuthenticationResult(\n queryStringFragments.join('')\n );\n\n const transaction = this.transactionManager.get();\n\n if (!transaction) {\n throw new Error('Invalid state');\n }\n\n this.transactionManager.remove();\n\n if (error) {\n throw new AuthenticationError(\n error,\n error_description || error,\n state,\n transaction.appState\n );\n }\n\n // Transaction should have a `code_verifier` to do PKCE for CSRF protection\n if (\n !transaction.code_verifier ||\n (transaction.state && transaction.state !== state)\n ) {\n throw new Error('Invalid state');\n }\n\n const organizationId = transaction.organizationId;\n const nonceIn = transaction.nonce;\n const redirect_uri = transaction.redirect_uri;\n\n await this._requestToken(\n {\n audience: transaction.audience,\n scope: transaction.scope,\n code_verifier: transaction.code_verifier,\n grant_type: 'authorization_code',\n code: code as string,\n ...(redirect_uri ? { redirect_uri } : {})\n },\n { nonceIn, organizationId }\n );\n\n return {\n appState: transaction.appState\n };\n }\n\n /**\n * ```js\n * await auth0.checkSession();\n * ```\n *\n * Check if the user is logged in using `getTokenSilently`. The difference\n * with `getTokenSilently` is that this doesn't return a token, but it will\n * pre-fill the token cache.\n *\n * This method also heeds the `auth0.{clientId}.is.authenticated` cookie, as an optimization\n * to prevent calling Auth0 unnecessarily. If the cookie is not present because\n * there was no previous login (or it has expired) then tokens will not be refreshed.\n *\n * It should be used for silently logging in the user when you instantiate the\n * `Auth0Client` constructor. You should not need this if you are using the\n * `createAuth0Client` factory.\n *\n * **Note:** the cookie **may not** be present if running an app using a private tab, as some\n * browsers clear JS cookie data and local storage when the tab or page is closed, or on page reload. This effectively\n * means that `checkSession` could silently return without authenticating the user on page refresh when\n * using a private tab, despite having previously logged in. As a workaround, use `getTokenSilently` instead\n * and handle the possible `login_required` error [as shown in the readme](https://github.com/auth0/auth0-spa-js#creating-the-client).\n *\n * @param options\n */\n public async checkSession(options?: GetTokenSilentlyOptions) {\n if (!this.cookieStorage.get(this.isAuthenticatedCookieName)) {\n if (!this.cookieStorage.get(OLD_IS_AUTHENTICATED_COOKIE_NAME)) {\n return;\n } else {\n // Migrate the existing cookie to the new name scoped by client ID\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this.cookieStorage.remove(OLD_IS_AUTHENTICATED_COOKIE_NAME);\n }\n }\n\n try {\n await this.getTokenSilently(options);\n } catch (_) {}\n }\n\n /**\n * Fetches a new access token and returns the response from the /oauth/token endpoint, omitting the refresh token.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions & { detailedResponse: true }\n ): Promise<GetTokenSilentlyVerboseResponse>;\n\n /**\n * Fetches a new access token and returns it.\n *\n * @param options\n */\n public async getTokenSilently(\n options?: GetTokenSilentlyOptions\n ): Promise<string>;\n\n /**\n * Fetches a new access token, and either returns just the access token (the default) or the response from the /oauth/token endpoint, depending on the `detailedResponse` option.\n *\n * ```js\n * const token = await auth0.getTokenSilently(options);\n * ```\n *\n * If there's a valid token stored and it has more than 60 seconds\n * remaining before expiration, return the token. Otherwise, attempt\n * to obtain a new token.\n *\n * A new token will be obtained either by opening an iframe or a\n * refresh token (if `useRefreshTokens` is `true`).\n\n * If iframes are used, opens an iframe with the `/authorize` URL\n * using the parameters provided as arguments. Random and secure `state`\n * and `nonce` parameters will be auto-generated. If the response is successful,\n * results will be validated according to their expiration times.\n *\n * If refresh tokens are used, the token endpoint is called directly with the\n * 'refresh_token' grant. If no refresh token is available to make this call,\n * the SDK will only fall back to using an iframe to the '/authorize' URL if \n * the `useRefreshTokensFallback` setting has been set to `true`. By default this\n * setting is `false`.\n *\n * This method may use a web worker to perform the token call if the in-memory\n * cache is used.\n *\n * If an `audience` value is given to this function, the SDK always falls\n * back to using an iframe to make the token exchange.\n *\n * Note that in all cases, falling back to an iframe requires access to\n * the `auth0` cookie.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions = {}\n ): Promise<undefined | string | GetTokenSilentlyVerboseResponse> {\n const localOptions: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n } = {\n cacheMode: 'on',\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: getUniqueScopes(this.scope, options.authorizationParams?.scope)\n }\n };\n\n const result = await singlePromise(\n () => this._getTokenSilently(localOptions),\n `${this.options.clientId}::${localOptions.authorizationParams.audience}::${localOptions.authorizationParams.scope}`\n );\n\n return options.detailedResponse ? result : result?.access_token;\n }\n\n private async _getTokenSilently(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const { cacheMode, ...getTokenOptions } = options;\n\n // Check the cache before acquiring the lock to avoid the latency of\n // `lock.acquireLock` when the cache is populated.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience: getTokenOptions.authorizationParams.audience || 'default',\n clientId: this.options.clientId\n });\n\n if (entry) {\n return entry;\n }\n }\n\n if (cacheMode === 'cache-only') {\n return;\n }\n\n if (\n await retryPromise(\n () => lock.acquireLock(GET_TOKEN_SILENTLY_LOCK_KEY, 5000),\n 10\n )\n ) {\n try {\n window.addEventListener('pagehide', this._releaseLockOnPageHide);\n\n // Check the cache a second time, because it may have been populated\n // by a previous call while this call was waiting to acquire the lock.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience: getTokenOptions.authorizationParams.audience || 'default',\n clientId: this.options.clientId\n });\n\n if (entry) {\n return entry;\n }\n }\n\n const authResult = this.options.useRefreshTokens\n ? await this._getTokenUsingRefreshToken(getTokenOptions)\n : await this._getTokenFromIFrame(getTokenOptions);\n\n const { id_token, access_token, oauthTokenScope, expires_in } =\n authResult;\n\n return {\n id_token,\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n };\n } finally {\n await lock.releaseLock(GET_TOKEN_SILENTLY_LOCK_KEY);\n window.removeEventListener('pagehide', this._releaseLockOnPageHide);\n }\n } else {\n throw new TimeoutError();\n }\n }\n\n /**\n * ```js\n * const token = await auth0.getTokenWithPopup(options);\n * ```\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * @param options\n * @param config\n */\n public async getTokenWithPopup(\n options: GetTokenWithPopupOptions = {},\n config: PopupConfigOptions = {}\n ) {\n const localOptions = {\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: getUniqueScopes(this.scope, options.authorizationParams?.scope)\n }\n };\n\n config = {\n ...DEFAULT_POPUP_CONFIG_OPTIONS,\n ...config\n };\n\n await this.loginWithPopup(localOptions, config);\n\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: localOptions.authorizationParams.scope,\n audience: localOptions.authorizationParams.audience || 'default',\n clientId: this.options.clientId\n })\n );\n\n return cache!.access_token;\n }\n\n /**\n * ```js\n * const isAuthenticated = await auth0.isAuthenticated();\n * ```\n *\n * Returns `true` if there's valid information stored,\n * otherwise returns `false`.\n *\n */\n public async isAuthenticated() {\n const user = await this.getUser();\n return !!user;\n }\n\n /**\n * ```js\n * await auth0.buildLogoutUrl(options);\n * ```\n *\n * Builds a URL to the logout endpoint using the parameters provided as arguments.\n * @param options\n */\n private _buildLogoutUrl(options: LogoutUrlOptions): string {\n if (options.clientId !== null) {\n options.clientId = options.clientId || this.options.clientId;\n } else {\n delete options.clientId;\n }\n\n const { federated, ...logoutOptions } = options.logoutParams || {};\n const federatedQuery = federated ? `&federated` : '';\n const url = this._url(\n `/v2/logout?${createQueryParams({\n clientId: options.clientId,\n ...logoutOptions\n })}`\n );\n\n return url + federatedQuery;\n }\n\n /**\n * ```js\n * await auth0.logout(options);\n * ```\n *\n * Clears the application session and performs a redirect to `/v2/logout`, using\n * the parameters provided as arguments, to clear the Auth0 session.\n *\n * If the `federated` option is specified it also clears the Identity Provider session.\n * [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).\n *\n * @param options\n */\n public async logout(options: LogoutOptions = {}): Promise<void> {\n const { openUrl, ...logoutOptions } = patchOpenUrlWithOnRedirect(options);\n\n if (options.clientId === null) {\n await this.cacheManager.clear();\n } else {\n await this.cacheManager.clear(options.clientId || this.options.clientId);\n }\n\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.cookieStorage.remove(this.isAuthenticatedCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);\n\n const url = this._buildLogoutUrl(logoutOptions);\n\n if (openUrl) {\n await openUrl(url);\n } else if (openUrl !== false) {\n window.location.assign(url);\n }\n }\n\n private async _getTokenFromIFrame(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const params: AuthorizationParams & { scope: string } = {\n ...options.authorizationParams,\n prompt: 'none'\n };\n\n const orgIdHint = this.cookieStorage.get<string>(this.orgHintCookieName);\n\n if (orgIdHint && !params.organization) {\n params.organization = orgIdHint;\n }\n\n const {\n url,\n state: stateIn,\n nonce: nonceIn,\n code_verifier,\n redirect_uri,\n scope,\n audience\n } = await this._prepareAuthorizeUrl(\n params,\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n try {\n // When a browser is running in a Cross-Origin Isolated context, using iframes is not possible.\n // It doesn't throw an error but times out instead, so we should exit early and inform the user about the reason.\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if ((window as any).crossOriginIsolated) {\n throw new GenericError(\n 'login_required',\n 'The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.'\n );\n }\n\n const authorizeTimeout =\n options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;\n\n const codeResult = await runIframe(url, this.domainUrl, authorizeTimeout);\n\n if (stateIn !== codeResult.state) {\n throw new Error('Invalid state');\n }\n\n const tokenResult = await this._requestToken(\n {\n ...options.authorizationParams,\n code_verifier,\n code: codeResult.code as string,\n grant_type: 'authorization_code',\n redirect_uri,\n timeout: options.authorizationParams.timeout || this.httpTimeoutMs\n },\n {\n nonceIn\n }\n );\n\n return {\n ...tokenResult,\n scope: scope,\n oauthTokenScope: tokenResult.scope,\n audience: audience\n };\n } catch (e) {\n if (e.error === 'login_required') {\n this.logout({\n openUrl: false\n });\n }\n throw e;\n }\n }\n\n private async _getTokenUsingRefreshToken(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: options.authorizationParams.scope,\n audience: options.authorizationParams.audience || 'default',\n clientId: this.options.clientId\n })\n );\n\n // If you don't have a refresh token in memory\n // and you don't have a refresh token in web worker memory\n // and useRefreshTokensFallback was explicitly enabled\n // fallback to an iframe\n if ((!cache || !cache.refresh_token) && !this.worker) {\n if (this.options.useRefreshTokensFallback) {\n return await this._getTokenFromIFrame(options);\n }\n\n throw new MissingRefreshTokenError(\n options.authorizationParams.audience || 'default',\n options.authorizationParams.scope\n );\n }\n\n const redirect_uri =\n options.authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n window.location.origin;\n\n const timeout =\n typeof options.timeoutInSeconds === 'number'\n ? options.timeoutInSeconds * 1000\n : null;\n\n try {\n const tokenResult = await this._requestToken({\n ...options.authorizationParams,\n grant_type: 'refresh_token',\n refresh_token: cache && cache.refresh_token,\n redirect_uri,\n ...(timeout && { timeout })\n });\n\n return {\n ...tokenResult,\n scope: options.authorizationParams.scope,\n oauthTokenScope: tokenResult.scope,\n audience: options.authorizationParams.audience || 'default'\n };\n } catch (e) {\n if (\n // The web worker didn't have a refresh token in memory so\n // fallback to an iframe.\n (e.message.indexOf(MISSING_REFRESH_TOKEN_ERROR_MESSAGE) > -1 ||\n // A refresh token was found, but is it no longer valid\n // and useRefreshTokensFallback is explicitly enabled. Fallback to an iframe.\n (e.message &&\n e.message.indexOf(INVALID_REFRESH_TOKEN_ERROR_MESSAGE) > -1)) &&\n this.options.useRefreshTokensFallback\n ) {\n return await this._getTokenFromIFrame(options);\n }\n\n throw e;\n }\n }\n\n private async _saveEntryInCache(\n entry: CacheEntry & { id_token: string; decodedToken: DecodedToken }\n ) {\n const { id_token, decodedToken, ...entryWithoutIdToken } = entry;\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {\n id_token,\n decodedToken\n });\n\n await this.cacheManager.setIdToken(\n this.options.clientId,\n entry.id_token,\n entry.decodedToken\n );\n\n await this.cacheManager.set(entryWithoutIdToken);\n }\n\n private async _getIdTokenFromCache() {\n const audience = this.options.authorizationParams.audience || 'default';\n\n const cache = await this.cacheManager.getIdToken(\n new CacheKey({\n clientId: this.options.clientId,\n audience,\n scope: this.scope\n })\n );\n\n const currentCache = this.userCache.get<IdTokenEntry>(\n CACHE_KEY_ID_TOKEN_SUFFIX\n ) as IdTokenEntry;\n\n // If the id_token in the cache matches the value we previously cached in memory return the in-memory\n // value so that object comparison will work\n if (cache && cache.id_token === currentCache?.id_token) {\n return currentCache;\n }\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);\n return cache;\n }\n\n private async _getEntryFromCache({\n scope,\n audience,\n clientId\n }: {\n scope: string;\n audience: string;\n clientId: string;\n }): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const entry = await this.cacheManager.get(\n new CacheKey({\n scope,\n audience,\n clientId\n }),\n 60 // get a new token if within 60 seconds of expiring\n );\n\n if (entry && entry.access_token) {\n const { access_token, oauthTokenScope, expires_in } = entry as CacheEntry;\n const cache = await this._getIdTokenFromCache();\n return (\n cache && {\n id_token: cache.id_token,\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n }\n );\n }\n }\n\n /**\n * Releases any lock acquired by the current page that's not released yet\n *\n * Get's called on the `pagehide` event.\n * https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event\n */\n private _releaseLockOnPageHide = async () => {\n await lock.releaseLock(GET_TOKEN_SILENTLY_LOCK_KEY);\n\n window.removeEventListener('pagehide', this._releaseLockOnPageHide);\n };\n\n private async _requestToken(\n options: PKCERequestTokenOptions | RefreshTokenRequestTokenOptions,\n additionalParameters?: RequestTokenAdditionalParameters\n ) {\n const { nonceIn, organizationId } = additionalParameters || {};\n const authResult = await oauthToken(\n {\n baseUrl: this.domainUrl,\n client_id: this.options.clientId,\n auth0Client: this.options.auth0Client,\n useFormData: this.options.useFormData,\n timeout: this.httpTimeoutMs,\n ...options\n },\n this.worker\n );\n\n const decodedToken = await this._verifyIdToken(\n authResult.id_token,\n nonceIn,\n organizationId\n );\n\n await this._saveEntryInCache({\n ...authResult,\n decodedToken,\n scope: options.scope,\n audience: options.audience || 'default',\n ...(authResult.scope ? { oauthTokenScope: authResult.scope } : null),\n client_id: this.options.clientId\n });\n\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this._processOrgIdHint(decodedToken.claims.org_id);\n\n return { ...authResult, decodedToken };\n }\n}\n\ninterface BaseRequestTokenOptions {\n audience?: string;\n scope: string;\n timeout?: number;\n redirect_uri?: string;\n}\n\ninterface PKCERequestTokenOptions extends BaseRequestTokenOptions {\n code: string;\n grant_type: 'authorization_code';\n code_verifier: string;\n}\n\ninterface RefreshTokenRequestTokenOptions extends BaseRequestTokenOptions {\n grant_type: 'refresh_token';\n refresh_token?: string;\n}\n\ninterface RequestTokenAdditionalParameters {\n nonceIn?: string;\n organizationId?: string;\n}\n","import { ICache } from './cache';\n\nexport interface AuthorizationParams {\n /**\n * - `'page'`: displays the UI with a full page view\n * - `'popup'`: displays the UI with a popup window\n * - `'touch'`: displays the UI in a way that leverages a touch interface\n * - `'wap'`: displays the UI with a \"feature phone\" type interface\n */\n display?: 'page' | 'popup' | 'touch' | 'wap';\n\n /**\n * - `'none'`: do not prompt user for login or consent on reauthentication\n * - `'login'`: prompt user for reauthentication\n * - `'consent'`: prompt user for consent before processing request\n * - `'select_account'`: prompt user to select an account\n */\n prompt?: 'none' | 'login' | 'consent' | 'select_account';\n\n /**\n * Maximum allowable elapsed time (in seconds) since authentication.\n * If the last time the user authenticated is greater than this value,\n * the user must be reauthenticated.\n */\n max_age?: string | number;\n\n /**\n * The space-separated list of language tags, ordered by preference.\n * For example: `'fr-CA fr en'`.\n */\n ui_locales?: string;\n\n /**\n * Previously issued ID Token.\n */\n id_token_hint?: string;\n\n /**\n * Provides a hint to Auth0 as to what flow should be displayed.\n * The default behavior is to show a login page but you can override\n * this by passing 'signup' to show the signup page instead.\n *\n * This only affects the New Universal Login Experience.\n */\n screen_hint?: 'signup' | 'login' | string;\n\n /**\n * The user's email address or other identifier. When your app knows\n * which user is trying to authenticate, you can provide this parameter\n * to pre-fill the email box or select the right session for sign-in.\n *\n * This currently only affects the classic Lock experience.\n */\n login_hint?: string;\n\n acr_values?: string;\n\n /**\n * The default scope to be used on authentication requests.\n *\n * This defaults to `profile email` if not set. If you are setting extra scopes and require\n * `profile` and `email` to be included then you must include them in the provided scope.\n *\n * Note: The `openid` scope is **always applied** regardless of this setting.\n */\n scope?: string;\n\n /**\n * The default audience to be used for requesting API access.\n */\n audience?: string;\n\n /**\n * The name of the connection configured for your application.\n * If null, it will redirect to the Auth0 Login Page and show\n * the Login Widget.\n */\n connection?: string;\n\n /**\n * The Id of an organization to log in to.\n *\n * This will specify an `organization` parameter in your user's login request and will add a step to validate\n * the `org_id` claim in your user's ID Token.\n */\n organization?: string;\n\n /**\n * The Id of an invitation to accept. This is available from the user invitation URL that is given when participating in a user invitation flow.\n */\n invitation?: string;\n\n /**\n * The default URL where Auth0 will redirect your browser to with\n * the authentication result. It must be whitelisted in\n * the \"Allowed Callback URLs\" field in your Auth0 Application's\n * settings. If not provided here, it should be provided in the other\n * methods that provide authentication.\n */\n redirect_uri?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n}\n\ninterface BaseLoginOptions {\n /**\n * URL parameters that will be sent back to the Authorization Server. This can be known parameters\n * defined by Auth0 or custom parameters that you define.\n */\n authorizationParams?: AuthorizationParams;\n}\n\nexport interface Auth0ClientOptions extends BaseLoginOptions {\n /**\n * Your Auth0 account domain such as `'example.auth0.com'`,\n * `'example.eu.auth0.com'` or , `'example.mycompany.com'`\n * (when using [custom domains](https://auth0.com/docs/custom-domains))\n */\n domain: string;\n /**\n * The issuer to be used for validation of JWTs, optionally defaults to the domain above\n */\n issuer?: string;\n /**\n * The Client ID found on your Application settings page\n */\n clientId: string;\n /**\n * The value in seconds used to account for clock skew in JWT expirations.\n * Typically, this value is no more than a minute or two at maximum.\n * Defaults to 60s.\n */\n leeway?: number;\n\n /**\n * The location to use when storing cache data. Valid values are `memory` or `localstorage`.\n * The default setting is `memory`.\n *\n * Read more about [changing storage options in the Auth0 docs](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options)\n */\n cacheLocation?: CacheLocation;\n\n /**\n * Specify a custom cache implementation to use for token storage and retrieval. This setting takes precedence over `cacheLocation` if they are both specified.\n */\n cache?: ICache;\n\n /**\n * If true, refresh tokens are used to fetch new access tokens from the Auth0 server. If false, the legacy technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` is used.\n * The default setting is `false`.\n *\n * **Note**: Use of refresh tokens must be enabled by an administrator on your Auth0 client application.\n */\n useRefreshTokens?: boolean;\n\n /**\n * If true, fallback to the technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` when unable to use refresh tokens. If false, the iframe fallback is not used and\n * errors relating to a failed `refresh_token` grant should be handled appropriately. The default setting is `false`.\n *\n * **Note**: There might be situations where doing silent auth with a Web Message response from an iframe is not possible,\n * like when you're serving your application from the file system or a custom protocol (like in a Desktop or Native app).\n * In situations like this you can disable the iframe fallback and handle the failed `refresh_token` grant and prompt the user to login interactively with `loginWithRedirect` or `loginWithPopup`.\"\n *\n * E.g. Using the `file:` protocol in an Electron application does not support that legacy technique.\n *\n * @example\n * let token: string;\n * try {\n * token = await auth0.getTokenSilently();\n * } catch (e) {\n * if (e.error === 'missing_refresh_token' || e.error === 'invalid_grant') {\n * auth0.loginWithRedirect();\n * }\n * }\n */\n useRefreshTokensFallback?: boolean;\n\n /**\n * A maximum number of seconds to wait before declaring background calls to /authorize as failed for timeout\n * Defaults to 60s.\n */\n authorizeTimeoutInSeconds?: number;\n\n /**\n * Specify the timeout for HTTP calls using `fetch`. The default is 10 seconds.\n */\n httpTimeoutInSeconds?: number;\n\n /**\n * Internal property to send information about the client to the authorization server.\n * @internal\n */\n auth0Client?: {\n name: string;\n version: string;\n env?: { [key: string]: string };\n };\n\n /**\n * Sets an additional cookie with no SameSite attribute to support legacy browsers\n * that are not compatible with the latest SameSite changes.\n * This will log a warning on modern browsers, you can disable the warning by setting\n * this to false but be aware that some older useragents will not work,\n * See https://www.chromium.org/updates/same-site/incompatible-clients\n * Defaults to true\n */\n legacySameSiteCookie?: boolean;\n\n /**\n * If `true`, the SDK will use a cookie when storing information about the auth transaction while\n * the user is going through the authentication flow on the authorization server.\n *\n * The default is `false`, in which case the SDK will use session storage.\n *\n * @notes\n *\n * You might want to enable this if you rely on your users being able to authenticate using flows that\n * may end up spanning across multiple tabs (e.g. magic links) or you cannot otherwise rely on session storage being available.\n */\n useCookiesForTransactions?: boolean;\n\n /**\n * Number of days until the cookie `auth0.is.authenticated` will expire\n * Defaults to 1.\n */\n sessionCheckExpiryDays?: number;\n\n /**\n * The domain the cookie is accessible from. If not set, the cookie is scoped to\n * the current domain, including the subdomain.\n *\n * Note: setting this incorrectly may cause silent authentication to stop working\n * on page load.\n *\n *\n * To keep a user logged in across multiple subdomains set this to your\n * top-level domain and prefixed with a `.` (eg: `.example.com`).\n */\n cookieDomain?: string;\n\n /**\n * If true, data to the token endpoint is transmitted as x-www-form-urlencoded data, if false it will be transmitted as JSON. The default setting is `true`.\n *\n * **Note:** Setting this to `false` may affect you if you use Auth0 Rules and are sending custom, non-primitive data. If you disable this,\n * please verify that your Auth0 Rules continue to work as intended.\n */\n useFormData?: boolean;\n\n /**\n * Modify the value used as the current time during the token validation.\n *\n * **Note**: Using this improperly can potentially compromise the token validation.\n */\n nowProvider?: () => Promise<number> | number;\n}\n\n/**\n * The possible locations where tokens can be stored\n */\nexport type CacheLocation = 'memory' | 'localstorage';\n\n/**\n * @ignore\n */\nexport interface AuthorizeOptions extends AuthorizationParams {\n response_type: string;\n response_mode: string;\n redirect_uri?: string;\n nonce: string;\n state: string;\n scope: string;\n code_challenge: string;\n code_challenge_method: string;\n}\n\nexport interface RedirectLoginOptions<TAppState = any>\n extends BaseLoginOptions {\n /**\n * Used to store state before doing the redirect\n */\n appState?: TAppState;\n /**\n * Used to add to the URL fragment before redirecting\n */\n fragment?: string;\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * async openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n */\n openUrl?: (url: string) => Promise<void>;\n}\n\nexport interface RedirectLoginResult<TAppState = any> {\n /**\n * State stored when the redirect request was made\n */\n appState?: TAppState;\n}\n\nexport interface PopupLoginOptions extends BaseLoginOptions {}\n\nexport interface PopupConfigOptions {\n /**\n * The number of seconds to wait for a popup response before\n * throwing a timeout error. Defaults to 60s\n */\n timeoutInSeconds?: number;\n\n /**\n * Accepts an already-created popup window to use. If not specified, the SDK\n * will create its own. This may be useful for platforms like iOS that have\n * security restrictions around when popups can be invoked (e.g. from a user click event)\n */\n popup?: any;\n}\n\nexport interface GetTokenSilentlyOptions {\n /**\n * When `off`, ignores the cache and always sends a\n * request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n\n /**\n * Parameters that will be sent back to Auth0 as part of a request.\n */\n authorizationParams?: {\n /**\n * There's no actual redirect when getting a token silently,\n * but, according to the spec, a `redirect_uri` param is required.\n * Auth0 uses this parameter to validate that the current `origin`\n * matches the `redirect_uri` `origin` when sending the response.\n * It must be whitelisted in the \"Allowed Web Origins\" in your\n * Auth0 Application's settings.\n */\n redirect_uri?: string;\n\n /**\n * The scope that was used in the authentication request\n */\n scope?: string;\n\n /**\n * The audience that was used in the authentication request\n */\n audience?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n\n /** A maximum number of seconds to wait before declaring the background /authorize call as failed for timeout\n * Defaults to 60s.\n */\n timeoutInSeconds?: number;\n\n /**\n * If true, the full response from the /oauth/token endpoint (or the cache, if the cache was used) is returned\n * (minus `refresh_token` if one was issued). Otherwise, just the access token is returned.\n *\n * The default is `false`.\n */\n detailedResponse?: boolean;\n}\n\nexport interface GetTokenWithPopupOptions extends PopupLoginOptions {\n /**\n * When `off`, ignores the cache and always sends a request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n}\n\nexport interface LogoutUrlOptions {\n /**\n * The `clientId` of your application.\n *\n * If this property is not set, then the `clientId` that was used during initialization of the SDK is sent to the logout endpoint.\n *\n * If this property is set to `null`, then no client ID value is sent to the logout endpoint.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n clientId?: string | null;\n\n /**\n * Parameters to pass to the logout endpoint. This can be known parameters defined by Auth0 or custom parameters\n * you wish to provide.\n */\n logoutParams?: {\n /**\n * When supported by the upstream identity provider,\n * forces the user to logout of their identity provider\n * and from Auth0.\n * [Read more about how federated logout works at Auth0](https://auth0.com/docs/logout/guides/logout-idps)\n */\n federated?: boolean;\n /**\n * The URL where Auth0 will redirect your browser to after the logout.\n *\n * **Note**: If the `client_id` parameter is included, the\n * `returnTo` URL that is provided must be listed in the\n * Application's \"Allowed Logout URLs\" in the Auth0 dashboard.\n * However, if the `client_id` parameter is not included, the\n * `returnTo` URL must be listed in the \"Allowed Logout URLs\" at\n * the account level in the Auth0 dashboard.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n returnTo?: string;\n\n /**\n * If you need to send custom parameters to the logout endpoint, make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n}\n\nexport interface LogoutOptions extends LogoutUrlOptions {\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * await auth0.logout({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * Set to `false` to disable the redirect, or provide a function to handle the actual redirect yourself.\n *\n * @example\n * await auth0.logout({\n * async openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n */\n openUrl?: false | ((url: string) => Promise<void>);\n}\n\n/**\n * @ignore\n */\nexport interface AuthenticationResult {\n state: string;\n code?: string;\n error?: string;\n error_description?: string;\n}\n\n/**\n * @ignore\n */\nexport interface TokenEndpointOptions {\n baseUrl: string;\n client_id: string;\n grant_type: string;\n timeout?: number;\n auth0Client: any;\n useFormData?: boolean;\n [key: string]: any;\n}\n\nexport type TokenEndpointResponse = {\n id_token: string;\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n scope?: string;\n};\n\n/**\n * @ignore\n */\nexport interface OAuthTokenOptions extends TokenEndpointOptions {\n code_verifier: string;\n code: string;\n redirect_uri: string;\n audience: string;\n scope: string;\n}\n\n/**\n * @ignore\n */\nexport interface RefreshTokenOptions extends TokenEndpointOptions {\n refresh_token: string;\n}\n\n/**\n * @ignore\n */\nexport interface JWTVerifyOptions {\n iss: string;\n aud: string;\n id_token: string;\n nonce?: string;\n leeway?: number;\n max_age?: number;\n organizationId?: string;\n now?: number;\n}\n\nexport interface IdToken {\n __raw: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n iss?: string;\n aud?: string;\n exp?: number;\n nbf?: number;\n iat?: number;\n jti?: string;\n azp?: string;\n nonce?: string;\n auth_time?: string;\n at_hash?: string;\n c_hash?: string;\n acr?: string;\n amr?: string;\n sub_jwk?: string;\n cnf?: string;\n sid?: string;\n org_id?: string;\n [key: string]: any;\n}\n\nexport class User {\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n sub?: string;\n [key: string]: any;\n}\n\n/**\n * @ignore\n */\nexport type FetchOptions = {\n method?: string;\n headers?: Record<string, string>;\n credentials?: 'include' | 'omit';\n body?: string;\n signal?: AbortSignal;\n};\n\nexport type GetTokenSilentlyVerboseResponse = Omit<\n TokenEndpointResponse,\n 'refresh_token'\n>;\n","import { Auth0Client } from './Auth0Client';\nimport { Auth0ClientOptions } from './global';\n\nimport './global';\n\nexport * from './global';\n\n/**\n * Asynchronously creates the Auth0Client instance and calls `checkSession`.\n *\n * **Note:** There are caveats to using this in a private browser tab, which may not silently authenticae\n * a user on page refresh. Please see [the checkSession docs](https://auth0.github.io/auth0-spa-js/classes/Auth0Client.html#checksession) for more info.\n *\n * @param options The client options\n * @returns An instance of Auth0Client\n */\nexport async function createAuth0Client(options: Auth0ClientOptions) {\n const auth0 = new Auth0Client(options);\n await auth0.checkSession();\n return auth0;\n}\n\nexport { Auth0Client };\n\nexport {\n GenericError,\n AuthenticationError,\n TimeoutError,\n PopupTimeoutError,\n PopupCancelledError,\n MfaRequiredError,\n MissingRefreshTokenError\n} from './errors';\n\nexport {\n ICache,\n LocalStorageCache,\n InMemoryCache,\n Cacheable,\n DecodedToken,\n CacheEntry,\n WrappedCacheEntry,\n KeyManifestEntry,\n MaybePromise,\n CacheKey,\n CacheKeyData\n} from './cache';\n"],"names":["__rest","s","e","t","p","Object","prototype","hasOwnProperty","call","indexOf","getOwnPropertySymbols","i","length","propertyIsEnumerable","defineProperty","exports","value","ProcessLocking","_this","this","locked","Map","addToLocked","key","toAdd","callbacks","get","undefined","set","unshift","isLocked","has","lock","Promise","resolve","reject","unlock","delete","toCall","pop","setTimeout","getInstance","instance","getLock","default","__awaiter","thisArg","_arguments","P","generator","fulfilled","step","next","rejected","result","done","then","apply","__generator","body","_","label","sent","trys","ops","f","y","g","verb","throw","return","Symbol","iterator","n","v","op","TypeError","push","LOCK_STORAGE_KEY","delay","milliseconds","generateRandomString","CHARS","randomstring","INDEX","Math","floor","random","getLockId","Date","now","toString","SuperTokensLock","acquiredIatSet","Set","id","acquireLock","bind","releaseLock","releaseLock__private__","waitForSomethingToChange","refreshLockWhileAcquired","waiters","lockKey","timeout","iat","MAX_TIME","STORAGE_KEY","STORAGE","lockObj","TIMEOUT_KEY","lockObjPostDelay","_a","window","localStorage","getItem","setItem","JSON","stringify","timeoutKey","timeAcquired","timeRefreshed","parse","add","lockCorrector","storageKey","processLock_1","resolvedCalled","startedAt","MIN_TIME_TO_WAIT","removedListeners","stopWaiting","removeEventListener","removeFromWaiting","clearTimeout","timeOutId","timeToWait","addEventListener","addToWaiting","max","func","filter","notifyWaiters","slice","forEach","removeItem","MIN_ALLOWED_TIME","KEYS","keys","LOCK_KEY","includes","version","DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS","DEFAULT_POPUP_CONFIG_OPTIONS","timeoutInSeconds","DEFAULT_SILENT_TOKEN_RETRY_COUNT","CLEANUP_IFRAME_TIMEOUT_IN_SECONDS","DEFAULT_FETCH_TIMEOUT_MS","CACHE_LOCATION_MEMORY","MISSING_REFRESH_TOKEN_ERROR_MESSAGE","INVALID_REFRESH_TOKEN_ERROR_MESSAGE","DEFAULT_SCOPE","DEFAULT_SESSION_CHECK_EXPIRY_DAYS","DEFAULT_AUTH0_CLIENT","name","DEFAULT_NOW_PROVIDER","GenericError","Error","constructor","error","error_description","super","setPrototypeOf","static","AuthenticationError","state","appState","TimeoutError","PopupTimeoutError","popup","PopupCancelledError","MfaRequiredError","mfa_token","MissingRefreshTokenError","audience","scope","valueOrEmptyString","exclude","parseAuthenticationResult","queryString","substring","searchParams","URLSearchParams","code","runIframe","authorizeUrl","eventOrigin","res","rej","iframe","document","createElement","setAttribute","style","display","removeIframe","contains","removeChild","iframeEventHandler","timeoutSetTimeoutId","origin","data","type","eventSource","source","close","response","fromPayload","appendChild","openPopup","url","width","height","left","screenX","innerWidth","top","screenY","innerHeight","open","runPopup","config","popupEventListener","popupTimer","setInterval","closed","clearInterval","timeoutId","getCrypto","crypto","createRandomString","charset","randomValues","Array","from","getRandomValues","Uint8Array","encode","btoa","stripUndefined","params","k","reduce","acc","assign","createQueryParams","clientId","client_id","sha256","async","digestOp","subtle","digest","TextEncoder","urlEncodeB64","input","b64Chars","replace","m","decodeB64","decodeURIComponent","atob","split","map","c","charCodeAt","join","urlDecodeB64","bufferToBase64UrlEncoded","ie11SafeInput","String","fromCharCode","validateCrypto","getDomain","domainUrl","test","getTokenIssuer","issuer","startsWith","parseNumber","parseInt","sendMessage","message","to","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","createAbortController","AbortController","dofetch","fetchUrl","fetchOptions","fetch","ok","json","fetchWithoutWorker","controller","signal","race","abort","finally","fetchWithWorker","worker","useFormData","auth","switchFetch","getJSON","options","fetchError","errorMessage","oauthToken","baseUrl","auth0Client","method","headers","dedupe","arr","getUniqueScopes","scopes","Boolean","trim","CACHE_KEY_PREFIX","CACHE_KEY_ID_TOKEN_SUFFIX","CacheKey","prefix","suffix","toKey","entry","LocalStorageCache","payload","remove","allKeys","InMemoryCache","enclosedCache","cache","cacheEntry","DEFAULT_EXPIRY_ADJUSTMENT_SECONDS","CacheManager","keyManifest","nowProvider","idToken","decodedToken","cacheKey","getIdTokenCacheKey","id_token","entryByScope","expiryAdjustmentSeconds","wrappedEntry","getCacheKeys","matchedKey","matchExistingCacheKey","nowSeconds","expiresAt","refresh_token","wrapCacheEntry","memo","clear","expiresInTime","expires_in","keyToMatch","fromKey","scopeSet","scopesToMatch","hasAllScopes","current","TRANSACTION_STORAGE_KEY_PREFIX","TransactionManager","storage","transaction","create","save","daysUntilExpire","isNumber","idTokendecoded","decode","token","parts","header","signature","payloadJSON","claims","__raw","user","encoded","verify","decoded","iss","sub","alg","aud","isArray","azp","nonce","max_age","auth_time","exp","leeway","expDate","setUTCSeconds","nbf","nbfDate","authTimeDate","organizationId","org_id","__assign","arguments","__esModule","stringifyAttribute","stringified","stringifyAttributes","attributes","expires","setMilliseconds","getMilliseconds","toUTCString","domain","path","secure","sameSite","encodeURIComponent","cookieString","cookies","rdecode","cookie","charAt","name_1","getAll","CookieStorage","Cookies.get","cookieAttributes","location","protocol","cookieDomain","Cookies.set","Cookies.remove","LEGACY_PREFIX","CookieStorageWithLegacySameSite","SessionStorage","sessionStorage","singlePromiseMap","singlePromise","cb","promise","retryPromise","maxNumberOfRetries","CacheKeyManifest","manifestKey","createManifestKeyFrom","size","GET_TOKEN_SILENTLY_LOCK_KEY","buildOrganizationHintCookieName","OLD_IS_AUTHENTICATED_COOKIE_NAME","buildIsAuthenticatedCookieName","cacheLocationBuilders","memory","localstorage","cacheFactory","getAuthorizeParams","clientOptions","authorizationParams","code_challenge","redirect_uri","response_mode","response_type","code_challenge_method","patchOpenUrlWithOnRedirect","openUrl","onRedirect","originalOptions","Lock","Auth0Client","userCache","defaultOptions","useRefreshTokensFallback","_releaseLockOnPageHide","cacheLocation","console","warn","httpTimeoutMs","httpTimeoutInSeconds","cookieStorage","legacySameSiteCookie","orgHintCookieName","isAuthenticatedCookieName","sessionCheckExpiryDays","transactionStorage","useCookiesForTransactions","useRefreshTokens","transactionManager","cacheManager","tokenIssuer","Worker","TokenWorker","_url","_authorizeUrl","authorizeOptions","verifyIdToken","_processOrgIdHint","fallbackRedirectUri","code_verifier","code_challengeBuffer","_prepareAuthorizeUrl","href","codeResult","authorizeTimeoutInSeconds","organization","_requestToken","grant_type","nonceIn","_getIdTokenFromCache","_b","fragment","urlOptions","_c","urlWithFragment","queryStringFragments","getTokenSilently","localOptions","cacheMode","_getTokenSilently","detailedResponse","access_token","getTokenOptions","_getEntryFromCache","authResult","_getTokenUsingRefreshToken","_getTokenFromIFrame","oauthTokenScope","loginWithPopup","getUser","_buildLogoutUrl","logoutParams","federated","logoutOptions","federatedQuery","prompt","orgIdHint","stateIn","crossOriginIsolated","authorizeTimeout","tokenResult","logout","entryWithoutIdToken","setIdToken","getIdToken","currentCache","additionalParameters","_verifyIdToken","_saveEntryInCache","User","createAuth0Client","auth0","checkSession"],"mappings":";;;;;IA0CO,SAASA,OAAOC,GAAGC;QACtB,IAAIC,IAAI,CAAA;QACR,KAAK,IAAIC,KAAKH,GAAG,IAAII,OAAOC,UAAUC,eAAeC,KAAKP,GAAGG,MAAMF,EAAEO,QAAQL,KAAK,GAC9ED,EAAEC,KAAKH,EAAEG;QACb,IAAIH,KAAK,eAAeI,OAAOK,0BAA0B,YACrD,KAAK,IAAIC,IAAI,GAAGP,IAAIC,OAAOK,sBAAsBT,IAAIU,IAAIP,EAAEQ,QAAQD,KAAK;YACpE,IAAIT,EAAEO,QAAQL,EAAEO,MAAM,KAAKN,OAAOC,UAAUO,qBAAqBL,KAAKP,GAAGG,EAAEO,KACvER,EAAEC,EAAEO,MAAMV,EAAEG,EAAEO;AACrB;QACL,OAAOR;AACX;;;;;;;;;;;QCnDAE,OAAOS,eAAeC,SAAS,cAAc;YAAEC,OAAO;;QACtD,IAAIC,iBAAgC;YAChC,SAASA;gBACL,IAAIC,QAAQC;gBACZA,KAAKC,SAAS,IAAIC;gBAClBF,KAAKG,cAAc,SAAUC,KAAKC;oBAC9B,IAAIC,YAAYP,MAAME,OAAOM,IAAIH;oBACjC,IAAIE,cAAcE,WAAW;wBACzB,IAAIH,UAAUG,WAAW;4BACrBT,MAAME,OAAOQ,IAAIL,KAAK;AACzB,+BACI;4BACDL,MAAME,OAAOQ,IAAIL,KAAK,EAACC;AAC1B;AACJ,2BACI;wBACD,IAAIA,UAAUG,WAAW;4BACrBF,UAAUI,QA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