/* @preserve
 * The MIT License (MIT)
 * 
 * Copyright (c) 2013-2015 Petka Antonov
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */
/**
 * bluebird build version 3.3.4
 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function (t) { if ("object" == typeof exports && "undefined" != typeof module) module.exports = t(); else if ("function" == typeof define && define.amd) define([], t); else { var e; "undefined" != typeof window ? e = window : "undefined" != typeof global ? e = global : "undefined" != typeof self && (e = self), e.Promise = t() } }(function () { var t, e, n; return function r(t, e, n) { function i(s, a) { if (!e[s]) { if (!t[s]) { var c = "function" == typeof _dereq_ && _dereq_; if (!a && c) return c(s, !0); if (o) return o(s, !0); var l = new Error("Cannot find module '" + s + "'"); throw l.code = "MODULE_NOT_FOUND", l } var u = e[s] = { exports: {} }; t[s][0].call(u.exports, function (e) { var n = t[s][1][e]; return i(n ? n : e) }, u, u.exports, r, t, e, n) } return e[s].exports } for (var o = "function" == typeof _dereq_ && _dereq_, s = 0; s < n.length; s++)i(n[s]); return i }({ 1: [function (t, e, n) { "use strict"; e.exports = function (t) { function e(t) { var e = new n(t), r = e.promise(); return e.setHowMany(1), e.setUnwrap(), e.init(), r } var n = t._SomePromiseArray; t.any = function (t) { return e(t) }, t.prototype.any = function () { return e(this) } } }, {}], 2: [function (t, e, n) { "use strict"; function r() { this._isTickUsed = !1, this._lateQueue = new u(16), this._normalQueue = new u(16), this._haveDrainedQueues = !1, this._trampolineEnabled = !0; var t = this; this.drainQueues = function () { t._drainQueues() }, this._schedule = l } function i(t, e, n) { this._lateQueue.push(t, e, n), this._queueTick() } function o(t, e, n) { this._normalQueue.push(t, e, n), this._queueTick() } function s(t) { this._normalQueue._pushOne(t), this._queueTick() } var a; try { throw new Error } catch (c) { a = c } var l = t("./schedule"), u = t("./queue"), p = t("./util"); r.prototype.enableTrampoline = function () { this._trampolineEnabled = !0 }, r.prototype.disableTrampolineIfNecessary = function () { p.hasDevTools && (this._trampolineEnabled = !1) }, r.prototype.haveItemsQueued = function () { return this._isTickUsed || this._haveDrainedQueues }, r.prototype.fatalError = function (t, e) { e ? (process.stderr.write("Fatal " + (t instanceof Error ? t.stack : t) + "\n"), process.exit(2)) : this.throwLater(t) }, r.prototype.throwLater = function (t, e) { if (1 === arguments.length && (e = t, t = function () { throw e }), "undefined" != typeof setTimeout) setTimeout(function () { t(e) }, 0); else try { this._schedule(function () { t(e) }) } catch (n) { throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n") } }, p.hasDevTools ? (r.prototype.invokeLater = function (t, e, n) { this._trampolineEnabled ? i.call(this, t, e, n) : this._schedule(function () { setTimeout(function () { t.call(e, n) }, 100) }) }, r.prototype.invoke = function (t, e, n) { this._trampolineEnabled ? o.call(this, t, e, n) : this._schedule(function () { t.call(e, n) }) }, r.prototype.settlePromises = function (t) { this._trampolineEnabled ? s.call(this, t) : this._schedule(function () { t._settlePromises() }) }) : (r.prototype.invokeLater = i, r.prototype.invoke = o, r.prototype.settlePromises = s), r.prototype.invokeFirst = function (t, e, n) { this._normalQueue.unshift(t, e, n), this._queueTick() }, r.prototype._drainQueue = function (t) { for (; t.length() > 0;) { var e = t.shift(); if ("function" == typeof e) { var n = t.shift(), r = t.shift(); e.call(n, r) } else e._settlePromises() } }, r.prototype._drainQueues = function () { this._drainQueue(this._normalQueue), this._reset(), this._haveDrainedQueues = !0, this._drainQueue(this._lateQueue) }, r.prototype._queueTick = function () { this._isTickUsed || (this._isTickUsed = !0, this._schedule(this.drainQueues)) }, r.prototype._reset = function () { this._isTickUsed = !1 }, e.exports = r, e.exports.firstLineError = a }, { "./queue": 26, "./schedule": 29, "./util": 36 }], 3: [function (t, e, n) { "use strict"; e.exports = function (t, e, n, r) { var i = !1, o = function (t, e) { this._reject(e) }, s = function (t, e) { e.promiseRejectionQueued = !0, e.bindingPromise._then(o, o, null, this, t) }, a = function (t, e) { 0 === (50397184 & this._bitField) && this._resolveCallback(e.target) }, c = function (t, e) { e.promiseRejectionQueued || this._reject(t) }; t.prototype.bind = function (o) { i || (i = !0, t.prototype._propagateFrom = r.propagateFromFunction(), t.prototype._boundValue = r.boundValueFunction()); var l = n(o), u = new t(e); u._propagateFrom(this, 1); var p = this._target(); if (u._setBoundTo(l), l instanceof t) { var h = { promiseRejectionQueued: !1, promise: u, target: p, bindingPromise: l }; p._then(e, s, void 0, u, h), l._then(a, c, void 0, u, h), u._setOnCancel(l) } else u._resolveCallback(p); return u }, t.prototype._setBoundTo = function (t) { void 0 !== t ? (this._bitField = 2097152 | this._bitField, this._boundTo = t) : this._bitField = -2097153 & this._bitField }, t.prototype._isBound = function () { return 2097152 === (2097152 & this._bitField) }, t.bind = function (e, n) { return t.resolve(n).bind(e) } } }, {}], 4: [function (t, e, n) { "use strict"; function r() { try { Promise === o && (Promise = i) } catch (t) { } return o } var i; "undefined" != typeof Promise && (i = Promise); var o = t("./promise")(); o.noConflict = r, e.exports = o }, { "./promise": 22 }], 5: [function (t, e, n) { "use strict"; var r = Object.create; if (r) { var i = r(null), o = r(null); i[" size"] = o[" size"] = 0 } e.exports = function (e) { function n(t, n) { var r; if (null != t && (r = t[n]), "function" != typeof r) { var i = "Object " + a.classString(t) + " has no method '" + a.toString(n) + "'"; throw new e.TypeError(i) } return r } function r(t) { var e = this.pop(), r = n(t, e); return r.apply(t, this) } function i(t) { return t[this] } function o(t) { var e = +this; return 0 > e && (e = Math.max(0, e + t.length)), t[e] } var s, a = t("./util"), c = a.canEvaluate; a.isIdentifier; e.prototype.call = function (t) { var e = [].slice.call(arguments, 1); return e.push(t), this._then(r, void 0, void 0, e, void 0) }, e.prototype.get = function (t) { var e, n = "number" == typeof t; if (n) e = o; else if (c) { var r = s(t); e = null !== r ? r : i } else e = i; return this._then(e, void 0, void 0, t, void 0) } } }, { "./util": 36 }], 6: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i) { var o = t("./util"), s = o.tryCatch, a = o.errorObj, c = e._async; e.prototype["break"] = e.prototype.cancel = function () { if (!i.cancellation()) return this._warn("cancellation is disabled"); for (var t = this, e = t; t.isCancellable();) { if (!t._cancelBy(e)) { e._isFollowing() ? e._followee().cancel() : e._cancelBranched(); break } var n = t._cancellationParent; if (null == n || !n.isCancellable()) { t._isFollowing() ? t._followee().cancel() : t._cancelBranched(); break } t._isFollowing() && t._followee().cancel(), e = t, t = n } }, e.prototype._branchHasCancelled = function () { this._branchesRemainingToCancel-- }, e.prototype._enoughBranchesHaveCancelled = function () { return void 0 === this._branchesRemainingToCancel || this._branchesRemainingToCancel <= 0 }, e.prototype._cancelBy = function (t) { return t === this ? (this._branchesRemainingToCancel = 0, this._invokeOnCancel(), !0) : (this._branchHasCancelled(), this._enoughBranchesHaveCancelled() ? (this._invokeOnCancel(), !0) : !1) }, e.prototype._cancelBranched = function () { this._enoughBranchesHaveCancelled() && this._cancel() }, e.prototype._cancel = function () { this.isCancellable() && (this._setCancelled(), c.invoke(this._cancelPromises, this, void 0)) }, e.prototype._cancelPromises = function () { this._length() > 0 && this._settlePromises() }, e.prototype._unsetOnCancel = function () { this._onCancelField = void 0 }, e.prototype.isCancellable = function () { return this.isPending() && !this.isCancelled() }, e.prototype._doInvokeOnCancel = function (t, e) { if (o.isArray(t)) for (var n = 0; n < t.length; ++n)this._doInvokeOnCancel(t[n], e); else if (void 0 !== t) if ("function" == typeof t) { if (!e) { var r = s(t).call(this._boundValue()); r === a && (this._attachExtraTrace(r.e), c.throwLater(r.e)) } } else t._resultCancelled(this) }, e.prototype._invokeOnCancel = function () { var t = this._onCancel(); this._unsetOnCancel(), c.invoke(this._doInvokeOnCancel, this, t) }, e.prototype._invokeInternalOnCancel = function () { this.isCancellable() && (this._doInvokeOnCancel(this._onCancel(), !0), this._unsetOnCancel()) }, e.prototype._resultCancelled = function () { this.cancel() } } }, { "./util": 36 }], 7: [function (t, e, n) { "use strict"; e.exports = function (e) { function n(t, n, a) { return function (c) { var l = a._boundValue(); t: for (var u = 0; u < t.length; ++u) { var p = t[u]; if (p === Error || null != p && p.prototype instanceof Error) { if (c instanceof p) return o(n).call(l, c) } else if ("function" == typeof p) { var h = o(p).call(l, c); if (h === s) return h; if (h) return o(n).call(l, c) } else if (r.isObject(c)) { for (var f = i(p), _ = 0; _ < f.length; ++_) { var d = f[_]; if (p[d] != c[d]) continue t } return o(n).call(l, c) } } return e } } var r = t("./util"), i = t("./es5").keys, o = r.tryCatch, s = r.errorObj; return n } }, { "./es5": 13, "./util": 36 }], 8: [function (t, e, n) { "use strict"; e.exports = function (t) { function e() { this._trace = new e.CapturedTrace(r()) } function n() { return i ? new e : void 0 } function r() { var t = o.length - 1; return t >= 0 ? o[t] : void 0 } var i = !1, o = []; return t.prototype._promiseCreated = function () { }, t.prototype._pushContext = function () { }, t.prototype._popContext = function () { return null }, t._peekContext = t.prototype._peekContext = function () { }, e.prototype._pushContext = function () { void 0 !== this._trace && (this._trace._promiseCreated = null, o.push(this._trace)) }, e.prototype._popContext = function () { if (void 0 !== this._trace) { var t = o.pop(), e = t._promiseCreated; return t._promiseCreated = null, e } return null }, e.CapturedTrace = null, e.create = n, e.deactivateLongStackTraces = function () { }, e.activateLongStackTraces = function () { var n = t.prototype._pushContext, o = t.prototype._popContext, s = t._peekContext, a = t.prototype._peekContext, c = t.prototype._promiseCreated; e.deactivateLongStackTraces = function () { t.prototype._pushContext = n, t.prototype._popContext = o, t._peekContext = s, t.prototype._peekContext = a, t.prototype._promiseCreated = c, i = !1 }, i = !0, t.prototype._pushContext = e.prototype._pushContext, t.prototype._popContext = e.prototype._popContext, t._peekContext = t.prototype._peekContext = r, t.prototype._promiseCreated = function () { var t = this._peekContext(); t && null == t._promiseCreated && (t._promiseCreated = this) } }, e } }, {}], 9: [function (t, e, n) { "use strict"; e.exports = function (e, n) { function r(t, e) { return { promise: e } } function i() { return !1 } function o(t, e, n) { var r = this; try { t(e, n, function (t) { if ("function" != typeof t) throw new TypeError("onCancel must be a function, got: " + H.toString(t)); r._attachCancellationCallback(t) }) } catch (i) { return i } } function s(t) { if (!this.isCancellable()) return this; var e = this._onCancel(); void 0 !== e ? H.isArray(e) ? e.push(t) : this._setOnCancel([e, t]) : this._setOnCancel(t) } function a() { return this._onCancelField } function c(t) { this._onCancelField = t } function l() { this._cancellationParent = void 0, this._onCancelField = void 0 } function u(t, e) { if (0 !== (1 & e)) { this._cancellationParent = t; var n = t._branchesRemainingToCancel; void 0 === n && (n = 0), t._branchesRemainingToCancel = n + 1 } 0 !== (2 & e) && t._isBound() && this._setBoundTo(t._boundTo) } function p(t, e) { 0 !== (2 & e) && t._isBound() && this._setBoundTo(t._boundTo) } function h() { var t = this._boundTo; return void 0 !== t && t instanceof e ? t.isFulfilled() ? t.value() : void 0 : t } function f() { this._trace = new O(this._peekContext()) } function _(t, e) { if (N(t)) { var n = this._trace; if (void 0 !== n && e && (n = n._parent), void 0 !== n) n.attachExtraTrace(t); else if (!t.__stackCleaned__) { var r = j(t); H.notEnumerableProp(t, "stack", r.message + "\n" + r.stack.join("\n")), H.notEnumerableProp(t, "__stackCleaned__", !0) } } } function d(t, e, n, r, i) { if (void 0 === t && null !== e && z) { if (void 0 !== i && i._returnedNonUndefined()) return; var o = r._bitField; if (0 === (65535 & o)) return; n && (n += " "); var s = "a promise was created in a " + n + "handler but was not returned from it"; r._warn(s, !0, e) } } function v(t, e) { var n = t + " is deprecated and will be removed in a future version."; return e && (n += " Use " + e + " instead."), y(n) } function y(t, n, r) { if (rt.warnings) { var i, o = new L(t); if (n) r._attachExtraTrace(o); else if (rt.longStackTraces && (i = e._peekContext())) i.attachExtraTrace(o); else { var s = j(o); o.stack = s.message + "\n" + s.stack.join("\n") } Y("warning", o) || k(o, "", !0) } } function g(t, e) { for (var n = 0; n < e.length - 1; ++n)e[n].push("From previous event:"), e[n] = e[n].join("\n"); return n < e.length && (e[n] = e[n].join("\n")), t + "\n" + e.join("\n") } function m(t) { for (var e = 0; e < t.length; ++e)(0 === t[e].length || e + 1 < t.length && t[e][0] === t[e + 1][0]) && (t.splice(e, 1), e--) } function b(t) { for (var e = t[0], n = 1; n < t.length; ++n) { for (var r = t[n], i = e.length - 1, o = e[i], s = -1, a = r.length - 1; a >= 0; --a)if (r[a] === o) { s = a; break } for (var a = s; a >= 0; --a) { var c = r[a]; if (e[i] !== c) break; e.pop(), i-- } e = r } } function w(t) { for (var e = [], n = 0; n < t.length; ++n) { var r = t[n], i = "    (No stack trace)" === r || B.test(r), o = i && tt(r); i && !o && (q && " " !== r.charAt(0) && (r = "    " + r), e.push(r)) } return e } function C(t) { for (var e = t.stack.replace(/\s+$/g, "").split("\n"), n = 0; n < e.length; ++n) { var r = e[n]; if ("    (No stack trace)" === r || B.test(r)) break } return n > 0 && (e = e.slice(n)), e } function j(t) { var e = t.stack, n = t.toString(); return e = "string" == typeof e && e.length > 0 ? C(t) : ["    (No stack trace)"], { message: n, stack: w(e) } } function k(t, e, n) { if ("undefined" != typeof console) { var r; if (H.isObject(t)) { var i = t.stack; r = e + M(i, t) } else r = e + String(t); "function" == typeof D ? D(r, n) : ("function" == typeof console.log || "object" == typeof console.log) && console.log(r) } } function E(t, e, n, r) { var i = !1; try { "function" == typeof e && (i = !0, "rejectionHandled" === t ? e(r) : e(n, r)) } catch (o) { I.throwLater(o) } "unhandledRejection" === t ? Y(t, n, r) || i || k(n, "Unhandled rejection ") : Y(t, r) } function F(t) { var e; if ("function" == typeof t) e = "[function " + (t.name || "anonymous") + "]"; else { e = t && "function" == typeof t.toString ? t.toString() : H.toString(t); var n = /\[object [a-zA-Z0-9$_]+\]/; if (n.test(e)) try { var r = JSON.stringify(t); e = r } catch (i) { } 0 === e.length && (e = "(empty array)") } return "(<" + x(e) + ">, no stack trace)" } function x(t) { var e = 41; return t.length < e ? t : t.substr(0, e - 3) + "..." } function T() { return "function" == typeof nt } function R(t) { var e = t.match(et); return e ? { fileName: e[1], line: parseInt(e[2], 10) } : void 0 } function P(t, e) { if (T()) { for (var n, r, i = t.stack.split("\n"), o = e.stack.split("\n"), s = -1, a = -1, c = 0; c < i.length; ++c) { var l = R(i[c]); if (l) { n = l.fileName, s = l.line; break } } for (var c = 0; c < o.length; ++c) { var l = R(o[c]); if (l) { r = l.fileName, a = l.line; break } } 0 > s || 0 > a || !n || !r || n !== r || s >= a || (tt = function (t) { if (U.test(t)) return !0; var e = R(t); return e && e.fileName === n && s <= e.line && e.line <= a ? !0 : !1 }) } } function O(t) { this._parent = t, this._promisesCreated = 0; var e = this._length = 1 + (void 0 === t ? 0 : t._length); nt(this, O), e > 32 && this.uncycle() } var S, A, D, V = e._getDomain, I = e._async, L = t("./errors").Warning, H = t("./util"), N = H.canAttachTrace, U = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/, B = null, M = null, q = !1, Q = !(0 == H.env("BLUEBIRD_DEBUG") || !H.env("BLUEBIRD_DEBUG") && "development" !== H.env("NODE_ENV")), $ = !(0 == H.env("BLUEBIRD_WARNINGS") || !Q && !H.env("BLUEBIRD_WARNINGS")), G = !(0 == H.env("BLUEBIRD_LONG_STACK_TRACES") || !Q && !H.env("BLUEBIRD_LONG_STACK_TRACES")), z = 0 != H.env("BLUEBIRD_W_FORGOTTEN_RETURN") && ($ || !!H.env("BLUEBIRD_W_FORGOTTEN_RETURN")); e.prototype.suppressUnhandledRejections = function () { var t = this._target(); t._bitField = -1048577 & t._bitField | 524288 }, e.prototype._ensurePossibleRejectionHandled = function () { 0 === (524288 & this._bitField) && (this._setRejectionIsUnhandled(), I.invokeLater(this._notifyUnhandledRejection, this, void 0)) }, e.prototype._notifyUnhandledRejectionIsHandled = function () { E("rejectionHandled", S, void 0, this) }, e.prototype._setReturnedNonUndefined = function () { this._bitField = 268435456 | this._bitField }, e.prototype._returnedNonUndefined = function () { return 0 !== (268435456 & this._bitField) }, e.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var t = this._settledValue(); this._setUnhandledRejectionIsNotified(), E("unhandledRejection", A, t, this) } }, e.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = 262144 | this._bitField }, e.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = -262145 & this._bitField }, e.prototype._isUnhandledRejectionNotified = function () { return (262144 & this._bitField) > 0 }, e.prototype._setRejectionIsUnhandled = function () { this._bitField = 1048576 | this._bitField }, e.prototype._unsetRejectionIsUnhandled = function () { this._bitField = -1048577 & this._bitField, this._isUnhandledRejectionNotified() && (this._unsetUnhandledRejectionIsNotified(), this._notifyUnhandledRejectionIsHandled()) }, e.prototype._isRejectionUnhandled = function () { return (1048576 & this._bitField) > 0 }, e.prototype._warn = function (t, e, n) { return y(t, e, n || this) }, e.onPossiblyUnhandledRejection = function (t) { var e = V(); A = "function" == typeof t ? null === e ? t : e.bind(t) : void 0 }, e.onUnhandledRejectionHandled = function (t) { var e = V(); S = "function" == typeof t ? null === e ? t : e.bind(t) : void 0 }; var X = function () { }; e.longStackTraces = function () { if (I.haveItemsQueued() && !rt.longStackTraces) throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n"); if (!rt.longStackTraces && T()) { var t = e.prototype._captureStackTrace, r = e.prototype._attachExtraTrace; rt.longStackTraces = !0, X = function () { if (I.haveItemsQueued() && !rt.longStackTraces) throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n"); e.prototype._captureStackTrace = t, e.prototype._attachExtraTrace = r, n.deactivateLongStackTraces(), I.enableTrampoline(), rt.longStackTraces = !1 }, e.prototype._captureStackTrace = f, e.prototype._attachExtraTrace = _, n.activateLongStackTraces(), I.disableTrampolineIfNecessary() } }, e.hasLongStackTraces = function () { return rt.longStackTraces && T() }; var W = function () { try { var t = document.createEvent("CustomEvent"); return t.initCustomEvent("testingtheevent", !1, !0, {}), H.global.dispatchEvent(t), function (t, e) { var n = document.createEvent("CustomEvent"); return n.initCustomEvent(t.toLowerCase(), !1, !0, e), !H.global.dispatchEvent(n) } } catch (e) { } return function () { return !1 } }(), K = function () { return H.isNode ? function () { return process.emit.apply(process, arguments) } : H.global ? function (t) { var e = "on" + t.toLowerCase(), n = H.global[e]; return n ? (n.apply(H.global, [].slice.call(arguments, 1)), !0) : !1 } : function () { return !1 } }(), J = { promiseCreated: r, promiseFulfilled: r, promiseRejected: r, promiseResolved: r, promiseCancelled: r, promiseChained: function (t, e, n) { return { promise: e, child: n } }, warning: function (t, e) { return { warning: e } }, unhandledRejection: function (t, e, n) { return { reason: e, promise: n } }, rejectionHandled: r }, Y = function (t) { var e = !1; try { e = K.apply(null, arguments) } catch (n) { I.throwLater(n), e = !0 } var r = !1; try { r = W(t, J[t].apply(null, arguments)) } catch (n) { I.throwLater(n), r = !0 } return r || e }; e.config = function (t) { if (t = Object(t), "longStackTraces" in t && (t.longStackTraces ? e.longStackTraces() : !t.longStackTraces && e.hasLongStackTraces() && X()), "warnings" in t) { var n = t.warnings; rt.warnings = !!n, z = rt.warnings, H.isObject(n) && "wForgottenReturn" in n && (z = !!n.wForgottenReturn) } if ("cancellation" in t && t.cancellation && !rt.cancellation) { if (I.haveItemsQueued()) throw new Error("cannot enable cancellation after promises are in use"); e.prototype._clearCancellationData = l, e.prototype._propagateFrom = u, e.prototype._onCancel = a, e.prototype._setOnCancel = c, e.prototype._attachCancellationCallback = s, e.prototype._execute = o, Z = u, rt.cancellation = !0 } "monitoring" in t && (t.monitoring && !rt.monitoring ? (rt.monitoring = !0, e.prototype._fireEvent = Y) : !t.monitoring && rt.monitoring && (rt.monitoring = !1, e.prototype._fireEvent = i)) }, e.prototype._fireEvent = i, e.prototype._execute = function (t, e, n) { try { t(e, n) } catch (r) { return r } }, e.prototype._onCancel = function () { }, e.prototype._setOnCancel = function (t) { }, e.prototype._attachCancellationCallback = function (t) { }, e.prototype._captureStackTrace = function () { }, e.prototype._attachExtraTrace = function () { }, e.prototype._clearCancellationData = function () { }, e.prototype._propagateFrom = function (t, e) { }; var Z = p, tt = function () { return !1 }, et = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; H.inherits(O, Error), n.CapturedTrace = O, O.prototype.uncycle = function () { var t = this._length; if (!(2 > t)) { for (var e = [], n = {}, r = 0, i = this; void 0 !== i; ++r)e.push(i), i = i._parent; t = this._length = r; for (var r = t - 1; r >= 0; --r) { var o = e[r].stack; void 0 === n[o] && (n[o] = r) } for (var r = 0; t > r; ++r) { var s = e[r].stack, a = n[s]; if (void 0 !== a && a !== r) { a > 0 && (e[a - 1]._parent = void 0, e[a - 1]._length = 1), e[r]._parent = void 0, e[r]._length = 1; var c = r > 0 ? e[r - 1] : this; t - 1 > a ? (c._parent = e[a + 1], c._parent.uncycle(), c._length = c._parent._length + 1) : (c._parent = void 0, c._length = 1); for (var l = c._length + 1, u = r - 2; u >= 0; --u)e[u]._length = l, l++; return } } } }, O.prototype.attachExtraTrace = function (t) { if (!t.__stackCleaned__) { this.uncycle(); for (var e = j(t), n = e.message, r = [e.stack], i = this; void 0 !== i;)r.push(w(i.stack.split("\n"))), i = i._parent; b(r), m(r), H.notEnumerableProp(t, "stack", g(n, r)), H.notEnumerableProp(t, "__stackCleaned__", !0) } }; var nt = function () { var t = /^\s*at\s*/, e = function (t, e) { return "string" == typeof t ? t : void 0 !== e.name && void 0 !== e.message ? e.toString() : F(e) }; if ("number" == typeof Error.stackTraceLimit && "function" == typeof Error.captureStackTrace) { Error.stackTraceLimit += 6, B = t, M = e; var n = Error.captureStackTrace; return tt = function (t) { return U.test(t) }, function (t, e) { Error.stackTraceLimit += 6, n(t, e), Error.stackTraceLimit -= 6 } } var r = new Error; if ("string" == typeof r.stack && r.stack.split("\n")[0].indexOf("stackDetection@") >= 0) return B = /@/, M = e, q = !0, function (t) { t.stack = (new Error).stack }; var i; try { throw new Error } catch (o) { i = "stack" in o } return "stack" in r || !i || "number" != typeof Error.stackTraceLimit ? (M = function (t, e) { return "string" == typeof t ? t : "object" != typeof e && "function" != typeof e || void 0 === e.name || void 0 === e.message ? F(e) : e.toString() },null): (B = t, M = e,function(t){ Error.stackTraceLimit += 6; try { throw new Error } catch (e) { t.stack = e.stack } Error.stackTraceLimit -= 6 }) }([]); "undefined" != typeof console && "undefined" != typeof console.warn && (D = function (t) { console.warn(t) }, H.isNode && process.stderr.isTTY ? D = function (t, e) { var n = e ? "[33m" : "[31m"; console.warn(n + t + "[0m\n") } : H.isNode || "string" != typeof (new Error).stack || (D = function (t, e) { console.warn("%c" + t, e ? "color: darkorange" : "color: red") })); var rt = { warnings: $, longStackTraces: !1, cancellation: !1, monitoring: !1 }; return G && e.longStackTraces(), { longStackTraces: function () { return rt.longStackTraces }, warnings: function () { return rt.warnings }, cancellation: function () { return rt.cancellation }, monitoring: function () { return rt.monitoring }, propagateFromFunction: function () { return Z }, boundValueFunction: function () { return h }, checkForgottenReturns: d, setBounds: P, warn: y, deprecated: v, CapturedTrace: O, fireDomEvent: W, fireGlobalEvent: K }}}, { "./errors": 12, "./util": 36 }], 10: [function (t, e, n) { "use strict"; e.exports = function (t) { function e() { return this.value } function n() { throw this.reason } t.prototype["return"] = t.prototype.thenReturn = function (n) { return n instanceof t && n.suppressUnhandledRejections(), this._then(e, void 0, void 0, { value: n }, void 0) }, t.prototype["throw"] = t.prototype.thenThrow = function (t) { return this._then(n, void 0, void 0, { reason: t }, void 0) }, t.prototype.catchThrow = function (t) { if (arguments.length <= 1) return this._then(void 0, n, void 0, { reason: t }, void 0); var e = arguments[1], r = function () { throw e }; return this.caught(t, r) }, t.prototype.catchReturn = function (n) { if (arguments.length <= 1) return n instanceof t && n.suppressUnhandledRejections(), this._then(void 0, e, void 0, { value: n }, void 0); var r = arguments[1]; r instanceof t && r.suppressUnhandledRejections(); var i = function () { return r }; return this.caught(n, i) } } }, {}], 11: [function (t, e, n) { "use strict"; e.exports = function (t, e) { function n() { return o(this) } function r(t, n) { return i(t, n, e, e) } var i = t.reduce, o = t.all; t.prototype.each = function (t) { return this.mapSeries(t)._then(n, void 0, void 0, this, void 0) }, t.prototype.mapSeries = function (t) { return i(this, t, e, e) }, t.each = function (t, e) { return r(t, e)._then(n, void 0, void 0, t, void 0) }, t.mapSeries = r } }, {}], 12: [function (t, e, n) { "use strict"; function r(t, e) { function n(r) { return this instanceof n ? (p(this, "message", "string" == typeof r ? r : e), p(this, "name", t), void (Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : Error.call(this))) : new n(r) } return u(n, Error), n } function i(t) { return this instanceof i ? (p(this, "name", "OperationalError"), p(this, "message", t), this.cause = t, this.isOperational = !0, void (t instanceof Error ? (p(this, "message", t.message), p(this, "stack", t.stack)) : Error.captureStackTrace && Error.captureStackTrace(this, this.constructor))) : new i(t) } var o, s, a = t("./es5"), c = a.freeze, l = t("./util"), u = l.inherits, p = l.notEnumerableProp, h = r("Warning", "warning"), f = r("CancellationError", "cancellation error"), _ = r("TimeoutError", "timeout error"), d = r("AggregateError", "aggregate error"); try { o = TypeError, s = RangeError } catch (v) { o = r("TypeError", "type error"), s = r("RangeError", "range error") } for (var y = "join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "), g = 0; g < y.length; ++g)"function" == typeof Array.prototype[y[g]] && (d.prototype[y[g]] = Array.prototype[y[g]]); a.defineProperty(d.prototype, "length", { value: 0, configurable: !1, writable: !0, enumerable: !0 }), d.prototype.isOperational = !0; var m = 0; d.prototype.toString = function () { var t = Array(4 * m + 1).join(" "), e = "\n" + t + "AggregateError of:\n"; m++ , t = Array(4 * m + 1).join(" "); for (var n = 0; n < this.length; ++n) { for (var r = this[n] === this ? "[Circular AggregateError]" : this[n] + "", i = r.split("\n"), o = 0; o < i.length; ++o)i[o] = t + i[o]; r = i.join("\n"), e += r + "\n" } return m-- , e }, u(i, Error); var b = Error.__BluebirdErrorTypes__; b || (b = c({ CancellationError: f, TimeoutError: _, OperationalError: i, RejectionError: i, AggregateError: d }), a.defineProperty(Error, "__BluebirdErrorTypes__", { value: b, writable: !1, enumerable: !1, configurable: !1 })), e.exports = { Error: Error, TypeError: o, RangeError: s, CancellationError: b.CancellationError, OperationalError: b.OperationalError, TimeoutError: b.TimeoutError, AggregateError: b.AggregateError, Warning: h } }, { "./es5": 13, "./util": 36 }], 13: [function (t, e, n) { var r = function () { "use strict"; return void 0 === this }(); if (r) e.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: r, propertyIsWritable: function (t, e) { var n = Object.getOwnPropertyDescriptor(t, e); return !(n && !n.writable && !n.set) } }; else { var i = {}.hasOwnProperty, o = {}.toString, s = {}.constructor.prototype, a = function (t) { var e = []; for (var n in t) i.call(t, n) && e.push(n); return e }, c = function (t, e) { return { value: t[e] } }, l = function (t, e, n) { return t[e] = n.value, t }, u = function (t) { return t }, p = function (t) { try { return Object(t).constructor.prototype } catch (e) { return s } }, h = function (t) { try { return "[object Array]" === o.call(t) } catch (e) { return !1 } }; e.exports = { isArray: h, keys: a, names: a, defineProperty: l, getDescriptor: c, freeze: u, getPrototypeOf: p, isES5: r, propertyIsWritable: function () { return !0 } } } }, {}], 14: [function (t, e, n) { "use strict"; e.exports = function (t, e) { var n = t.map; t.prototype.filter = function (t, r) { return n(this, t, r, e) }, t.filter = function (t, r, i) { return n(t, r, i, e) } } }, {}], 15: [function (t, e, n) { "use strict"; e.exports = function (e, n) { function r(t, e, n) { this.promise = t, this.type = e, this.handler = n, this.called = !1, this.cancelPromise = null } function i(t) { this.finallyHandler = t } function o(t, e) { return null != t.cancelPromise ? (arguments.length > 1 ? t.cancelPromise._reject(e) : t.cancelPromise._cancel(), t.cancelPromise = null, !0) : !1 } function s() { return c.call(this, this.promise._target()._settledValue()) } function a(t) { return o(this, t) ? void 0 : (p.e = t, p) } function c(t) { var r = this.promise, c = this.handler; if (!this.called) { this.called = !0; var l = this.isFinallyHandler() ? c.call(r._boundValue()) : c.call(r._boundValue(), t); if (void 0 !== l) { r._setReturnedNonUndefined(); var h = n(l, r); if (h instanceof e) { if (null != this.cancelPromise) { if (h.isCancelled()) { var f = new u("late cancellation observer"); return r._attachExtraTrace(f), p.e = f, p } h.isPending() && h._attachCancellationCallback(new i(this)) } return h._then(s, a, void 0, this, void 0) } } } return r.isRejected() ? (o(this), p.e = t, p) : (o(this), t) } var l = t("./util"), u = e.CancellationError, p = l.errorObj; return r.prototype.isFinallyHandler = function () { return 0 === this.type }, i.prototype._resultCancelled = function () { o(this.finallyHandler) }, e.prototype._passThrough = function (t, e, n, i) { return "function" != typeof t ? this.then() : this._then(n, i, void 0, new r(this, e, t), void 0) }, e.prototype.lastly = e.prototype["finally"] = function (t) { return this._passThrough(t, 0, c, c) }, e.prototype.tap = function (t) { return this._passThrough(t, 1, c) }, r } }, { "./util": 36 }], 16: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i, o, s) { function a(t, n, r) { for (var o = 0; o < n.length; ++o) { r._pushContext(); var s = f(n[o])(t); if (r._popContext(), s === h) { r._pushContext(); var a = e.reject(h.e); return r._popContext(), a } var c = i(s, r); if (c instanceof e) return c } return null } function c(t, n, i, o) { var s = this._promise = new e(r); s._captureStackTrace(), s._setOnCancel(this), this._stack = o, this._generatorFunction = t, this._receiver = n, this._generator = void 0, this._yieldHandlers = "function" == typeof i ? [i].concat(_) : _, this._yieldedPromise = null } var l = t("./errors"), u = l.TypeError, p = t("./util"), h = p.errorObj, f = p.tryCatch, _ = []; p.inherits(c, o), c.prototype._isResolved = function () { return null === this._promise }, c.prototype._cleanup = function () { this._promise = this._generator = null }, c.prototype._promiseCancelled = function () { if (!this._isResolved()) { var t, n = "undefined" != typeof this._generator["return"]; if (n) this._promise._pushContext(), t = f(this._generator["return"]).call(this._generator, void 0), this._promise._popContext(); else { var r = new e.CancellationError("generator .return() sentinel"); e.coroutine.returnSentinel = r, this._promise._attachExtraTrace(r), this._promise._pushContext(), t = f(this._generator["throw"]).call(this._generator, r), this._promise._popContext(), t === h && t.e === r && (t = null) } var i = this._promise; this._cleanup(), t === h ? i._rejectCallback(t.e, !1) : i.cancel() } }, c.prototype._promiseFulfilled = function (t) { this._yieldedPromise = null, this._promise._pushContext(); var e = f(this._generator.next).call(this._generator, t); this._promise._popContext(), this._continue(e) }, c.prototype._promiseRejected = function (t) { this._yieldedPromise = null, this._promise._attachExtraTrace(t), this._promise._pushContext(); var e = f(this._generator["throw"]).call(this._generator, t); this._promise._popContext(), this._continue(e) }, c.prototype._resultCancelled = function () { if (this._yieldedPromise instanceof e) { var t = this._yieldedPromise; this._yieldedPromise = null, this._promiseCancelled(), t.cancel() } }, c.prototype.promise = function () { return this._promise }, c.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver), this._receiver = this._generatorFunction = void 0, this._promiseFulfilled(void 0) }, c.prototype._continue = function (t) { var n = this._promise; if (t === h) return this._cleanup(), n._rejectCallback(t.e, !1); var r = t.value; if (t.done === !0) return this._cleanup(), n._resolveCallback(r); var o = i(r, this._promise); if (!(o instanceof e) && (o = a(o, this._yieldHandlers, this._promise), null === o)) return void this._promiseRejected(new u("A value %s was yielded that could not be treated as a promise\n\n    See http://goo.gl/MqrFmX\n\n".replace("%s", r) + "From coroutine:\n" + this._stack.split("\n").slice(1, -7).join("\n"))); o = o._target(); var s = o._bitField; 0 === (50397184 & s) ? (this._yieldedPromise = o, o._proxy(this, null)) : 0 !== (33554432 & s) ? this._promiseFulfilled(o._value()) : 0 !== (16777216 & s) ? this._promiseRejected(o._reason()) : this._promiseCancelled() }, e.coroutine = function (t, e) { if ("function" != typeof t) throw new u("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n"); var n = Object(e).yieldHandler, r = c, i = (new Error).stack; return function () { var e = t.apply(this, arguments), o = new r(void 0, void 0, n, i), s = o.promise(); return o._generator = e, o._promiseFulfilled(void 0), s } }, e.coroutine.addYieldHandler = function (t) { if ("function" != typeof t) throw new u("expecting a function but got " + p.classString(t)); _.push(t) }, e.spawn = function (t) { if (s.deprecated("Promise.spawn()", "Promise.coroutine()"), "function" != typeof t) return n("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n"); var r = new c(t, this), i = r.promise(); return r._run(e.spawn), i } } }, { "./errors": 12, "./util": 36 }], 17: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i) { var o = t("./util"); o.canEvaluate, o.tryCatch, o.errorObj; e.join = function () { var t, e = arguments.length - 1; if (e > 0 && "function" == typeof arguments[e]) { t = arguments[e]; var r } var i = [].slice.call(arguments); t && i.pop(); var r = new n(i).promise(); return void 0 !== t ? r.spread(t) : r } } }, { "./util": 36 }], 18: [function (t, e, n) {
    "use strict"; e.exports = function (e, n, r, i, o, s) {
        function a(t, e, n, r) { this.constructor$(t), this._promise._captureStackTrace(); var i = l(); this._callback = null === i ? e : i.bind(e), this._preservedValues = r === o ? new Array(this.length()) : null, this._limit = n, this._inFlight = 0, this._queue = n >= 1 ? [] : f, this._init$(void 0, -2) } function c(t, e, n, i) { if ("function" != typeof e) return r("expecting a function but got " + u.classString(e)); var o = "object" == typeof n && null !== n ? n.concurrency : 0; return o = "number" == typeof o && isFinite(o) && o >= 1 ? o : 0, new a(t, e, o, i).promise() } var l = e._getDomain, u = t("./util"), p = u.tryCatch, h = u.errorObj, f = []; u.inherits(a, n), a.prototype._init = function () { }, a.prototype._promiseFulfilled = function (t, n) {
            var r = this._values, o = this.length(), a = this._preservedValues, c = this._limit; if (0 > n) { if (n = -1 * n - 1, r[n] = t, c >= 1 && (this._inFlight-- , this._drainQueue(), this._isResolved())) return !0 } else { if (c >= 1 && this._inFlight >= c) return r[n] = t, this._queue.push(n), !1; null !== a && (a[n] = t); var l = this._promise, u = this._callback, f = l._boundValue(); l._pushContext(); var _ = p(u).call(f, t, n, o), d = l._popContext(); if (s.checkForgottenReturns(_, d, null !== a ? "Promise.filter" : "Promise.map", l), _ === h) return this._reject(_.e), !0; var v = i(_, this._promise); if (v instanceof e) { v = v._target(); var y = v._bitField; if (0 === (50397184 & y)) return c >= 1 && this._inFlight++ , r[n] = v, v._proxy(this, -1 * (n + 1)), !1; if (0 === (33554432 & y)) return 0 !== (16777216 & y) ? (this._reject(v._reason()), !0) : (this._cancel(), !0); _ = v._value() } r[n] = _ } var g = ++this._totalResolved; return g >= o ? (null !== a ? this._filter(r, a) : this._resolve(r), !0) : !1
        }, a.prototype._drainQueue = function () { for (var t = this._queue, e = this._limit, n = this._values; t.length > 0 && this._inFlight < e;) { if (this._isResolved()) return; var r = t.pop(); this._promiseFulfilled(n[r], r) } }, a.prototype._filter = function (t, e) { for (var n = e.length, r = new Array(n), i = 0, o = 0; n > o; ++o)t[o] && (r[i++] = e[o]); r.length = i, this._resolve(r) }, a.prototype.preservedValues = function () { return this._preservedValues }, e.prototype.map = function (t, e) { return c(this, t, e, null) }, e.map = function (t, e, n, r) { return c(t, e, n, r) }
    }
}, { "./util": 36 }], 19: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i, o) { var s = t("./util"), a = s.tryCatch; e.method = function (t) { if ("function" != typeof t) throw new e.TypeError("expecting a function but got " + s.classString(t)); return function () { var r = new e(n); r._captureStackTrace(), r._pushContext(); var i = a(t).apply(this, arguments), s = r._popContext(); return o.checkForgottenReturns(i, s, "Promise.method", r), r._resolveFromSyncValue(i), r } }, e.attempt = e["try"] = function (t) { if ("function" != typeof t) return i("expecting a function but got " + s.classString(t)); var r = new e(n); r._captureStackTrace(), r._pushContext(); var c; if (arguments.length > 1) { o.deprecated("calling Promise.try with more than 1 argument"); var l = arguments[1], u = arguments[2]; c = s.isArray(l) ? a(t).apply(u, l) : a(t).call(u, l) } else c = a(t)(); var p = r._popContext(); return o.checkForgottenReturns(c, p, "Promise.try", r), r._resolveFromSyncValue(c), r }, e.prototype._resolveFromSyncValue = function (t) { t === s.errorObj ? this._rejectCallback(t.e, !1) : this._resolveCallback(t, !0) } } }, { "./util": 36 }], 20: [function (t, e, n) { "use strict"; function r(t) { return t instanceof Error && u.getPrototypeOf(t) === Error.prototype } function i(t) { var e; if (r(t)) { e = new l(t), e.name = t.name, e.message = t.message, e.stack = t.stack; for (var n = u.keys(t), i = 0; i < n.length; ++i) { var o = n[i]; p.test(o) || (e[o] = t[o]) } return e } return s.markAsOriginatingFromRejection(t), t } function o(t, e) { return function (n, r) { if (null !== t) { if (n) { var o = i(a(n)); t._attachExtraTrace(o), t._reject(o) } else if (e) { var s = [].slice.call(arguments, 1); t._fulfill(s) } else t._fulfill(r); t = null } } } var s = t("./util"), a = s.maybeWrapAsError, c = t("./errors"), l = c.OperationalError, u = t("./es5"), p = /^(?:name|message|stack|cause)$/; e.exports = o }, { "./errors": 12, "./es5": 13, "./util": 36 }], 21: [function (t, e, n) { "use strict"; e.exports = function (e) { function n(t, e) { var n = this; if (!o.isArray(t)) return r.call(n, t, e); var i = a(e).apply(n._boundValue(), [null].concat(t)); i === c && s.throwLater(i.e) } function r(t, e) { var n = this, r = n._boundValue(), i = void 0 === t ? a(e).call(r, null) : a(e).call(r, null, t); i === c && s.throwLater(i.e) } function i(t, e) { var n = this; if (!t) { var r = new Error(t + ""); r.cause = t, t = r } var i = a(e).call(n._boundValue(), t); i === c && s.throwLater(i.e) } var o = t("./util"), s = e._async, a = o.tryCatch, c = o.errorObj; e.prototype.asCallback = e.prototype.nodeify = function (t, e) { if ("function" == typeof t) { var o = r; void 0 !== e && Object(e).spread && (o = n), this._then(o, i, void 0, this, t) } return this } } }, { "./util": 36 }], 22: [function (t, e, n) { "use strict"; e.exports = function () { function e() { } function n(t, e) { if ("function" != typeof e) throw new y("expecting a function but got " + h.classString(e)); if (t.constructor !== r) throw new y("the promise constructor cannot be invoked directly\n\n    See http://goo.gl/MqrFmX\n") } function r(t) { this._bitField = 0, this._fulfillmentHandler0 = void 0, this._rejectionHandler0 = void 0, this._promise0 = void 0, this._receiver0 = void 0, t !== m && (n(this, t), this._resolveFromExecutor(t)), this._promiseCreated(), this._fireEvent("promiseCreated", this) } function i(t) { this.promise._resolveCallback(t) } function o(t) { this.promise._rejectCallback(t, !1) } function s(t) { var e = new r(m); e._fulfillmentHandler0 = t, e._rejectionHandler0 = t, e._promise0 = t, e._receiver0 = t } var a, c = function () { return new y("circular promise resolution chain\n\n    See http://goo.gl/MqrFmX\n") }, l = function () { return new r.PromiseInspection(this._target()) }, u = function (t) { return r.reject(new y(t)) }, p = {}, h = t("./util"); a = h.isNode ? function () { var t = process.domain; return void 0 === t && (t = null), t } : function () { return null }, h.notEnumerableProp(r, "_getDomain", a); var f = t("./es5"), _ = t("./async"), d = new _; f.defineProperty(r, "_async", { value: d }); var v = t("./errors"), y = r.TypeError = v.TypeError; r.RangeError = v.RangeError; var g = r.CancellationError = v.CancellationError; r.TimeoutError = v.TimeoutError, r.OperationalError = v.OperationalError, r.RejectionError = v.OperationalError, r.AggregateError = v.AggregateError; var m = function () { }, b = {}, w = {}, C = t("./thenables")(r, m), j = t("./promise_array")(r, m, C, u, e), k = t("./context")(r), E = k.create, F = t("./debuggability")(r, k), x = (F.CapturedTrace, t("./finally")(r, C)), T = t("./catch_filter")(w), R = t("./nodeback"), P = h.errorObj, O = h.tryCatch; return r.prototype.toString = function () { return "[object Promise]" }, r.prototype.caught = r.prototype["catch"] = function (t) { var e = arguments.length; if (e > 1) { var n, r = new Array(e - 1), i = 0; for (n = 0; e - 1 > n; ++n) { var o = arguments[n]; if (!h.isObject(o)) return u("expecting an object but got " + h.classString(o)); r[i++] = o } return r.length = i, t = arguments[n], this.then(void 0, T(r, t, this)) } return this.then(void 0, t) }, r.prototype.reflect = function () { return this._then(l, l, void 0, this, void 0) }, r.prototype.then = function (t, e) { if (F.warnings() && arguments.length > 0 && "function" != typeof t && "function" != typeof e) { var n = ".then() only accepts functions but was passed: " + h.classString(t); arguments.length > 1 && (n += ", " + h.classString(e)), this._warn(n) } return this._then(t, e, void 0, void 0, void 0) }, r.prototype.done = function (t, e) { var n = this._then(t, e, void 0, void 0, void 0); n._setIsFinal() }, r.prototype.spread = function (t) { return "function" != typeof t ? u("expecting a function but got " + h.classString(t)) : this.all()._then(t, void 0, void 0, b, void 0) }, r.prototype.toJSON = function () { var t = { isFulfilled: !1, isRejected: !1, fulfillmentValue: void 0, rejectionReason: void 0 }; return this.isFulfilled() ? (t.fulfillmentValue = this.value(), t.isFulfilled = !0) : this.isRejected() && (t.rejectionReason = this.reason(), t.isRejected = !0), t }, r.prototype.all = function () { return arguments.length > 0 && this._warn(".all() was passed arguments but it does not take any"), new j(this).promise() }, r.prototype.error = function (t) { return this.caught(h.originatesFromRejection, t) }, r.is = function (t) { return t instanceof r }, r.fromNode = r.fromCallback = function (t) { var e = new r(m); e._captureStackTrace(); var n = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : !1, i = O(t)(R(e, n)); return i === P && e._rejectCallback(i.e, !0), e._isFateSealed() || e._setAsyncGuaranteed(), e }, r.all = function (t) { return new j(t).promise() }, r.cast = function (t) { var e = C(t); return e instanceof r || (e = new r(m), e._captureStackTrace(), e._setFulfilled(), e._rejectionHandler0 = t), e }, r.resolve = r.fulfilled = r.cast, r.reject = r.rejected = function (t) { var e = new r(m); return e._captureStackTrace(), e._rejectCallback(t, !0), e }, r.setScheduler = function (t) { if ("function" != typeof t) throw new y("expecting a function but got " + h.classString(t)); var e = d._schedule; return d._schedule = t, e }, r.prototype._then = function (t, e, n, i, o) { var s = void 0 !== o, c = s ? o : new r(m), l = this._target(), u = l._bitField; s || (c._propagateFrom(this, 3), c._captureStackTrace(), void 0 === i && 0 !== (2097152 & this._bitField) && (i = 0 !== (50397184 & u) ? this._boundValue() : l === this ? void 0 : this._boundTo), this._fireEvent("promiseChained", this, c)); var p = a(); if (0 !== (50397184 & u)) { var h, f, _ = l._settlePromiseCtx; 0 !== (33554432 & u) ? (f = l._rejectionHandler0, h = t) : 0 !== (16777216 & u) ? (f = l._fulfillmentHandler0, h = e, l._unsetRejectionIsUnhandled()) : (_ = l._settlePromiseLateCancellationObserver, f = new g("late cancellation observer"), l._attachExtraTrace(f), h = e), d.invoke(_, l, { handler: null === p ? h : "function" == typeof h && p.bind(h), promise: c, receiver: i, value: f }) } else l._addCallbacks(t, e, c, i, p); return c }, r.prototype._length = function () { return 65535 & this._bitField }, r.prototype._isFateSealed = function () { return 0 !== (117506048 & this._bitField) }, r.prototype._isFollowing = function () { return 67108864 === (67108864 & this._bitField) }, r.prototype._setLength = function (t) { this._bitField = -65536 & this._bitField | 65535 & t }, r.prototype._setFulfilled = function () { this._bitField = 33554432 | this._bitField, this._fireEvent("promiseFulfilled", this) }, r.prototype._setRejected = function () { this._bitField = 16777216 | this._bitField, this._fireEvent("promiseRejected", this) }, r.prototype._setFollowing = function () { this._bitField = 67108864 | this._bitField, this._fireEvent("promiseResolved", this) }, r.prototype._setIsFinal = function () { this._bitField = 4194304 | this._bitField }, r.prototype._isFinal = function () { return (4194304 & this._bitField) > 0 }, r.prototype._unsetCancelled = function () { this._bitField = -65537 & this._bitField }, r.prototype._setCancelled = function () { this._bitField = 65536 | this._bitField, this._fireEvent("promiseCancelled", this) }, r.prototype._setAsyncGuaranteed = function () { this._bitField = 134217728 | this._bitField }, r.prototype._receiverAt = function (t) { var e = 0 === t ? this._receiver0 : this[4 * t - 4 + 3]; return e === p ? void 0 : void 0 === e && this._isBound() ? this._boundValue() : e }, r.prototype._promiseAt = function (t) { return this[4 * t - 4 + 2] }, r.prototype._fulfillmentHandlerAt = function (t) { return this[4 * t - 4 + 0] }, r.prototype._rejectionHandlerAt = function (t) { return this[4 * t - 4 + 1] }, r.prototype._boundValue = function () { }, r.prototype._migrateCallback0 = function (t) { var e = (t._bitField, t._fulfillmentHandler0), n = t._rejectionHandler0, r = t._promise0, i = t._receiverAt(0); void 0 === i && (i = p), this._addCallbacks(e, n, r, i, null) }, r.prototype._migrateCallbackAt = function (t, e) { var n = t._fulfillmentHandlerAt(e), r = t._rejectionHandlerAt(e), i = t._promiseAt(e), o = t._receiverAt(e); void 0 === o && (o = p), this._addCallbacks(n, r, i, o, null) }, r.prototype._addCallbacks = function (t, e, n, r, i) { var o = this._length(); if (o >= 65531 && (o = 0, this._setLength(0)), 0 === o) this._promise0 = n, this._receiver0 = r, "function" == typeof t && (this._fulfillmentHandler0 = null === i ? t : i.bind(t)), "function" == typeof e && (this._rejectionHandler0 = null === i ? e : i.bind(e)); else { var s = 4 * o - 4; this[s + 2] = n, this[s + 3] = r, "function" == typeof t && (this[s + 0] = null === i ? t : i.bind(t)), "function" == typeof e && (this[s + 1] = null === i ? e : i.bind(e)) } return this._setLength(o + 1), o }, r.prototype._proxy = function (t, e) { this._addCallbacks(void 0, void 0, e, t, null) }, r.prototype._resolveCallback = function (t, e) { if (0 === (117506048 & this._bitField)) { if (t === this) return this._rejectCallback(c(), !1); var n = C(t, this); if (!(n instanceof r)) return this._fulfill(t); e && this._propagateFrom(n, 2); var i = n._target(); if (i === this) return void this._reject(c()); var o = i._bitField; if (0 === (50397184 & o)) { var s = this._length(); s > 0 && i._migrateCallback0(this); for (var a = 1; s > a; ++a)i._migrateCallbackAt(this, a); this._setFollowing(), this._setLength(0), this._setFollowee(i) } else if (0 !== (33554432 & o)) this._fulfill(i._value()); else if (0 !== (16777216 & o)) this._reject(i._reason()); else { var l = new g("late cancellation observer"); i._attachExtraTrace(l), this._reject(l) } } }, r.prototype._rejectCallback = function (t, e, n) { var r = h.ensureErrorObject(t), i = r === t; if (!i && !n && F.warnings()) { var o = "a promise was rejected with a non-error: " + h.classString(t); this._warn(o, !0) } this._attachExtraTrace(r, e ? i : !1), this._reject(t) }, r.prototype._resolveFromExecutor = function (t) { var e = this; this._captureStackTrace(), this._pushContext(); var n = !0, r = this._execute(t, function (t) { e._resolveCallback(t) }, function (t) { e._rejectCallback(t, n) }); n = !1, this._popContext(), void 0 !== r && e._rejectCallback(r, !0) }, r.prototype._settlePromiseFromHandler = function (t, e, n, r) { var i = r._bitField; if (0 === (65536 & i)) { r._pushContext(); var o; e === b ? n && "number" == typeof n.length ? o = O(t).apply(this._boundValue(), n) : (o = P, o.e = new y("cannot .spread() a non-array: " + h.classString(n))) : o = O(t).call(e, n); var s = r._popContext(); i = r._bitField, 0 === (65536 & i) && (o === w ? r._reject(n) : o === P ? r._rejectCallback(o.e, !1) : (F.checkForgottenReturns(o, s, "", r, this), r._resolveCallback(o))) } }, r.prototype._target = function () { for (var t = this; t._isFollowing();)t = t._followee(); return t }, r.prototype._followee = function () { return this._rejectionHandler0 }, r.prototype._setFollowee = function (t) { this._rejectionHandler0 = t }, r.prototype._settlePromise = function (t, n, i, o) { var s = t instanceof r, a = this._bitField, c = 0 !== (134217728 & a); 0 !== (65536 & a) ? (s && t._invokeInternalOnCancel(), i instanceof x && i.isFinallyHandler() ? (i.cancelPromise = t, O(n).call(i, o) === P && t._reject(P.e)) : n === l ? t._fulfill(l.call(i)) : i instanceof e ? i._promiseCancelled(t) : s || t instanceof j ? t._cancel() : i.cancel()) : "function" == typeof n ? s ? (c && t._setAsyncGuaranteed(), this._settlePromiseFromHandler(n, i, o, t)) : n.call(i, o, t) : i instanceof e ? i._isResolved() || (0 !== (33554432 & a) ? i._promiseFulfilled(o, t) : i._promiseRejected(o, t)) : s && (c && t._setAsyncGuaranteed(), 0 !== (33554432 & a) ? t._fulfill(o) : t._reject(o)) }, r.prototype._settlePromiseLateCancellationObserver = function (t) { var e = t.handler, n = t.promise, i = t.receiver, o = t.value; "function" == typeof e ? n instanceof r ? this._settlePromiseFromHandler(e, i, o, n) : e.call(i, o, n) : n instanceof r && n._reject(o) }, r.prototype._settlePromiseCtx = function (t) { this._settlePromise(t.promise, t.handler, t.receiver, t.value) }, r.prototype._settlePromise0 = function (t, e, n) { var r = this._promise0, i = this._receiverAt(0); this._promise0 = void 0, this._receiver0 = void 0, this._settlePromise(r, t, i, e) }, r.prototype._clearCallbackDataAtIndex = function (t) { var e = 4 * t - 4; this[e + 2] = this[e + 3] = this[e + 0] = this[e + 1] = void 0 }, r.prototype._fulfill = function (t) { var e = this._bitField; if (!((117506048 & e) >>> 16)) { if (t === this) { var n = c(); return this._attachExtraTrace(n), this._reject(n) } this._setFulfilled(), this._rejectionHandler0 = t, (65535 & e) > 0 && (0 !== (134217728 & e) ? this._settlePromises() : d.settlePromises(this)) } }, r.prototype._reject = function (t) { var e = this._bitField; if (!((117506048 & e) >>> 16)) return this._setRejected(), this._fulfillmentHandler0 = t, this._isFinal() ? d.fatalError(t, h.isNode) : void ((65535 & e) > 0 ? d.settlePromises(this) : this._ensurePossibleRejectionHandled()) }, r.prototype._fulfillPromises = function (t, e) { for (var n = 1; t > n; n++) { var r = this._fulfillmentHandlerAt(n), i = this._promiseAt(n), o = this._receiverAt(n); this._clearCallbackDataAtIndex(n), this._settlePromise(i, r, o, e) } }, r.prototype._rejectPromises = function (t, e) { for (var n = 1; t > n; n++) { var r = this._rejectionHandlerAt(n), i = this._promiseAt(n), o = this._receiverAt(n); this._clearCallbackDataAtIndex(n), this._settlePromise(i, r, o, e) } }, r.prototype._settlePromises = function () { var t = this._bitField, e = 65535 & t; if (e > 0) { if (0 !== (16842752 & t)) { var n = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, n, t), this._rejectPromises(e, n) } else { var r = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, r, t), this._fulfillPromises(e, r) } this._setLength(0) } this._clearCancellationData() }, r.prototype._settledValue = function () { var t = this._bitField; return 0 !== (33554432 & t) ? this._rejectionHandler0 : 0 !== (16777216 & t) ? this._fulfillmentHandler0 : void 0 }, r.defer = r.pending = function () { F.deprecated("Promise.defer", "new Promise"); var t = new r(m); return { promise: t, resolve: i, reject: o } }, h.notEnumerableProp(r, "_makeSelfResolutionError", c), t("./method")(r, m, C, u, F), t("./bind")(r, m, C, F), t("./cancel")(r, j, u, F), t("./direct_resolve")(r), t("./synchronous_inspection")(r), t("./join")(r, j, C, m, F), r.Promise = r, t("./map.js")(r, j, u, C, m, F), t("./using.js")(r, u, C, E, m, F), t("./timers.js")(r, m, F), t("./generators.js")(r, u, m, C, e, F), t("./nodeify.js")(r), t("./call_get.js")(r), t("./props.js")(r, j, C, u), t("./race.js")(r, m, C, u), t("./reduce.js")(r, j, u, C, m, F), t("./settle.js")(r, j, F), t("./some.js")(r, j, u), t("./promisify.js")(r, m), t("./any.js")(r), t("./each.js")(r, m), t("./filter.js")(r, m), h.toFastProperties(r), h.toFastProperties(r.prototype), s({ a: 1 }), s({ b: 2 }), s({ c: 3 }), s(1), s(function () { }), s(void 0), s(!1), s(new r(m)), F.setBounds(_.firstLineError, h.lastLineError), r } }, { "./any.js": 1, "./async": 2, "./bind": 3, "./call_get.js": 5, "./cancel": 6, "./catch_filter": 7, "./context": 8, "./debuggability": 9, "./direct_resolve": 10, "./each.js": 11, "./errors": 12, "./es5": 13, "./filter.js": 14, "./finally": 15, "./generators.js": 16, "./join": 17, "./map.js": 18, "./method": 19, "./nodeback": 20, "./nodeify.js": 21, "./promise_array": 23, "./promisify.js": 24, "./props.js": 25, "./race.js": 27, "./reduce.js": 28, "./settle.js": 30, "./some.js": 31, "./synchronous_inspection": 32, "./thenables": 33, "./timers.js": 34, "./using.js": 35, "./util": 36 }], 23: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i, o) { function s(t) { switch (t) { case -2: return []; case -3: return {} } } function a(t) { var r = this._promise = new e(n); t instanceof e && r._propagateFrom(t, 3), r._setOnCancel(this), this._values = t, this._length = 0, this._totalResolved = 0, this._init(void 0, -2) } var c = t("./util"); c.isArray; return c.inherits(a, o), a.prototype.length = function () { return this._length }, a.prototype.promise = function () { return this._promise }, a.prototype._init = function l(t, n) { var o = r(this._values, this._promise); if (o instanceof e) { o = o._target(); var a = o._bitField; if (this._values = o, 0 === (50397184 & a)) return this._promise._setAsyncGuaranteed(), o._then(l, this._reject, void 0, this, n); if (0 === (33554432 & a)) return 0 !== (16777216 & a) ? this._reject(o._reason()) : this._cancel(); o = o._value() } if (o = c.asArray(o), null === o) { var u = i("expecting an array or an iterable object but got " + c.classString(o)).reason(); return void this._promise._rejectCallback(u, !1) } return 0 === o.length ? void (-5 === n ? this._resolveEmptyArray() : this._resolve(s(n))) : void this._iterate(o) }, a.prototype._iterate = function (t) { var n = this.getActualLength(t.length); this._length = n, this._values = this.shouldCopyValues() ? new Array(n) : this._values; for (var i = this._promise, o = !1, s = null, a = 0; n > a; ++a) { var c = r(t[a], i); c instanceof e ? (c = c._target(), s = c._bitField) : s = null, o ? null !== s && c.suppressUnhandledRejections() : null !== s ? 0 === (50397184 & s) ? (c._proxy(this, a), this._values[a] = c) : o = 0 !== (33554432 & s) ? this._promiseFulfilled(c._value(), a) : 0 !== (16777216 & s) ? this._promiseRejected(c._reason(), a) : this._promiseCancelled(a) : o = this._promiseFulfilled(c, a) } o || i._setAsyncGuaranteed() }, a.prototype._isResolved = function () { return null === this._values }, a.prototype._resolve = function (t) { this._values = null, this._promise._fulfill(t) }, a.prototype._cancel = function () { !this._isResolved() && this._promise.isCancellable() && (this._values = null, this._promise._cancel()) }, a.prototype._reject = function (t) { this._values = null, this._promise._rejectCallback(t, !1) }, a.prototype._promiseFulfilled = function (t, e) { this._values[e] = t; var n = ++this._totalResolved; return n >= this._length ? (this._resolve(this._values), !0) : !1 }, a.prototype._promiseCancelled = function () { return this._cancel(), !0 }, a.prototype._promiseRejected = function (t) { return this._totalResolved++ , this._reject(t), !0 }, a.prototype._resultCancelled = function () { if (!this._isResolved()) { var t = this._values; if (this._cancel(), t instanceof e) t.cancel(); else for (var n = 0; n < t.length; ++n)t[n] instanceof e && t[n].cancel() } }, a.prototype.shouldCopyValues = function () { return !0 }, a.prototype.getActualLength = function (t) { return t }, a } }, { "./util": 36 }], 24: [function (t, e, n) { "use strict"; e.exports = function (e, n) { function r(t) { return !C.test(t) } function i(t) { try { return t.__isPromisified__ === !0 } catch (e) { return !1 } } function o(t, e, n) { var r = f.getDataPropertyOrDefault(t, e + n, b); return r ? i(r) : !1 } function s(t, e, n) { for (var r = 0; r < t.length; r += 2) { var i = t[r]; if (n.test(i)) for (var o = i.replace(n, ""), s = 0; s < t.length; s += 2)if (t[s] === o) throw new g("Cannot promisify an API that has normal methods with '%s'-suffix\n\n    See http://goo.gl/MqrFmX\n".replace("%s", e)) } } function a(t, e, n, r) { for (var a = f.inheritedDataKeys(t), c = [], l = 0; l < a.length; ++l) { var u = a[l], p = t[u], h = r === j ? !0 : j(u, p, t); "function" != typeof p || i(p) || o(t, u, e) || !r(u, p, t, h) || c.push(u, p) } return s(c, e, n), c } function c(t, r, i, o, s, a) { function c() { var i = r; r === h && (i = this); var o = new e(n); o._captureStackTrace(); var s = "string" == typeof u && this !== l ? this[u] : t, c = _(o, a); try { s.apply(i, d(arguments, c)) } catch (p) { o._rejectCallback(v(p), !0, !0) } return o._isFateSealed() || o._setAsyncGuaranteed(), o } var l = function () { return this }(), u = t; return "string" == typeof u && (t = o), f.notEnumerableProp(c, "__isPromisified__", !0), c } function l(t, e, n, r, i) { for (var o = new RegExp(k(e) + "$"), s = a(t, e, o, n), c = 0, l = s.length; l > c; c += 2) { var u = s[c], p = s[c + 1], _ = u + e; if (r === E) t[_] = E(u, h, u, p, e, i); else { var d = r(p, function () { return E(u, h, u, p, e, i) }); f.notEnumerableProp(d, "__isPromisified__", !0), t[_] = d } } return f.toFastProperties(t), t } function u(t, e, n) { return E(t, e, void 0, t, null, n) } var p, h = {}, f = t("./util"), _ = t("./nodeback"), d = f.withAppended, v = f.maybeWrapAsError, y = f.canEvaluate, g = t("./errors").TypeError, m = "Async", b = { __isPromisified__: !0 }, w = ["arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__"], C = new RegExp("^(?:" + w.join("|") + ")$"), j = function (t) { return f.isIdentifier(t) && "_" !== t.charAt(0) && "constructor" !== t }, k = function (t) { return t.replace(/([$])/, "\\$") }, E = y ? p : c; e.promisify = function (t, e) { if ("function" != typeof t) throw new g("expecting a function but got " + f.classString(t)); if (i(t)) return t; e = Object(e); var n = void 0 === e.context ? h : e.context, o = !!e.multiArgs, s = u(t, n, o); return f.copyDescriptors(t, s, r), s }, e.promisifyAll = function (t, e) { if ("function" != typeof t && "object" != typeof t) throw new g("the target of promisifyAll must be an object or a function\n\n    See http://goo.gl/MqrFmX\n"); e = Object(e); var n = !!e.multiArgs, r = e.suffix; "string" != typeof r && (r = m); var i = e.filter; "function" != typeof i && (i = j); var o = e.promisifier; if ("function" != typeof o && (o = E), !f.isIdentifier(r)) throw new RangeError("suffix must be a valid identifier\n\n    See http://goo.gl/MqrFmX\n"); for (var s = f.inheritedDataKeys(t), a = 0; a < s.length; ++a) { var c = t[s[a]]; "constructor" !== s[a] && f.isClass(c) && (l(c.prototype, r, i, o, n), l(c, r, i, o, n)) } return l(t, r, i, o, n) } } }, { "./errors": 12, "./nodeback": 20, "./util": 36 }], 25: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i) { function o(t) { var e, n = !1; if (void 0 !== a && t instanceof a) e = p(t), n = !0; else { var r = u.keys(t), i = r.length; e = new Array(2 * i); for (var o = 0; i > o; ++o) { var s = r[o]; e[o] = t[s], e[o + i] = s } } this.constructor$(e), this._isMap = n, this._init$(void 0, -3) } function s(t) { var n, s = r(t); return l(s) ? (n = s instanceof e ? s._then(e.props, void 0, void 0, void 0, void 0) : new o(s).promise(), s instanceof e && n._propagateFrom(s, 2), n) : i("cannot await properties of a non-object\n\n    See http://goo.gl/MqrFmX\n") } var a, c = t("./util"), l = c.isObject, u = t("./es5"); "function" == typeof Map && (a = Map); var p = function () { function t(t, r) { this[e] = t, this[e + n] = r, e++ } var e = 0, n = 0; return function (r) { n = r.size, e = 0; var i = new Array(2 * r.size); return r.forEach(t, i), i } }(), h = function (t) { for (var e = new a, n = t.length / 2 | 0, r = 0; n > r; ++r) { var i = t[n + r], o = t[r]; e.set(i, o) } return e }; c.inherits(o, n), o.prototype._init = function () { }, o.prototype._promiseFulfilled = function (t, e) { this._values[e] = t; var n = ++this._totalResolved; if (n >= this._length) { var r; if (this._isMap) r = h(this._values); else { r = {}; for (var i = this.length(), o = 0, s = this.length(); s > o; ++o)r[this._values[o + i]] = this._values[o] } return this._resolve(r), !0 } return !1 }, o.prototype.shouldCopyValues = function () { return !1 }, o.prototype.getActualLength = function (t) { return t >> 1 }, e.prototype.props = function () { return s(this) }, e.props = function (t) { return s(t) } } }, { "./es5": 13, "./util": 36 }], 26: [function (t, e, n) { "use strict"; function r(t, e, n, r, i) { for (var o = 0; i > o; ++o)n[o + r] = t[o + e], t[o + e] = void 0 } function i(t) { this._capacity = t, this._length = 0, this._front = 0 } i.prototype._willBeOverCapacity = function (t) { return this._capacity < t }, i.prototype._pushOne = function (t) { var e = this.length(); this._checkCapacity(e + 1); var n = this._front + e & this._capacity - 1; this[n] = t, this._length = e + 1 }, i.prototype._unshiftOne = function (t) { var e = this._capacity; this._checkCapacity(this.length() + 1); var n = this._front, r = (n - 1 & e - 1 ^ e) - e; this[r] = t, this._front = r, this._length = this.length() + 1 }, i.prototype.unshift = function (t, e, n) { this._unshiftOne(n), this._unshiftOne(e), this._unshiftOne(t) }, i.prototype.push = function (t, e, n) { var r = this.length() + 3; if (this._willBeOverCapacity(r)) return this._pushOne(t), this._pushOne(e), void this._pushOne(n); var i = this._front + r - 3; this._checkCapacity(r); var o = this._capacity - 1; this[i + 0 & o] = t, this[i + 1 & o] = e, this[i + 2 & o] = n, this._length = r }, i.prototype.shift = function () { var t = this._front, e = this[t]; return this[t] = void 0, this._front = t + 1 & this._capacity - 1, this._length-- , e }, i.prototype.length = function () { return this._length }, i.prototype._checkCapacity = function (t) { this._capacity < t && this._resizeTo(this._capacity << 1) }, i.prototype._resizeTo = function (t) { var e = this._capacity; this._capacity = t; var n = this._front, i = this._length, o = n + i & e - 1; r(this, 0, this, e, o) }, e.exports = i }, {}], 27: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i) { function o(t, o) { var c = r(t); if (c instanceof e) return a(c); if (t = s.asArray(t), null === t) return i("expecting an array or an iterable object but got " + s.classString(t)); var l = new e(n); void 0 !== o && l._propagateFrom(o, 3); for (var u = l._fulfill, p = l._reject, h = 0, f = t.length; f > h; ++h) { var _ = t[h]; (void 0 !== _ || h in t) && e.cast(_)._then(u, p, void 0, l, null) } return l } var s = t("./util"), a = function (t) { return t.then(function (e) { return o(e, t) }) }; e.race = function (t) { return o(t, void 0) }, e.prototype.race = function () { return o(this, void 0) } } }, { "./util": 36 }], 28: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i, o, s) { function a(t, n, r, i) { this.constructor$(t); var s = h(); this._fn = null === s ? n : s.bind(n), void 0 !== r && (r = e.resolve(r), r._attachCancellationCallback(this)), this._initialValue = r, this._currentCancellable = null, this._eachValues = i === o ? [] : void 0, this._promise._captureStackTrace(), this._init$(void 0, -5) } function c(t, e) { this.isFulfilled() ? e._resolve(t) : e._reject(t) } function l(t, e, n, i) { if ("function" != typeof e) return r("expecting a function but got " + f.classString(e)); var o = new a(t, e, n, i); return o.promise() } function u(t) { this.accum = t, this.array._gotAccum(t); var n = i(this.value, this.array._promise); return n instanceof e ? (this.array._currentCancellable = n, n._then(p, void 0, void 0, this, void 0)) : p.call(this, n) } function p(t) { var n = this.array, r = n._promise, i = _(n._fn); r._pushContext(); var o; o = void 0 !== n._eachValues ? i.call(r._boundValue(), t, this.index, this.length) : i.call(r._boundValue(), this.accum, t, this.index, this.length), o instanceof e && (n._currentCancellable = o); var a = r._popContext(); return s.checkForgottenReturns(o, a, void 0 !== n._eachValues ? "Promise.each" : "Promise.reduce", r), o } var h = e._getDomain, f = t("./util"), _ = f.tryCatch; f.inherits(a, n), a.prototype._gotAccum = function (t) { void 0 !== this._eachValues && t !== o && this._eachValues.push(t) }, a.prototype._eachComplete = function (t) { return this._eachValues.push(t), this._eachValues }, a.prototype._init = function () { }, a.prototype._resolveEmptyArray = function () { this._resolve(void 0 !== this._eachValues ? this._eachValues : this._initialValue) }, a.prototype.shouldCopyValues = function () { return !1 }, a.prototype._resolve = function (t) { this._promise._resolveCallback(t), this._values = null }, a.prototype._resultCancelled = function (t) { return t === this._initialValue ? this._cancel() : void (this._isResolved() || (this._resultCancelled$(), this._currentCancellable instanceof e && this._currentCancellable.cancel(), this._initialValue instanceof e && this._initialValue.cancel())) }, a.prototype._iterate = function (t) { this._values = t; var n, r, i = t.length; if (void 0 !== this._initialValue ? (n = this._initialValue, r = 0) : (n = e.resolve(t[0]), r = 1), this._currentCancellable = n, !n.isRejected()) for (; i > r; ++r) { var o = { accum: null, value: t[r], index: r, length: i, array: this }; n = n._then(u, void 0, void 0, o, void 0) } void 0 !== this._eachValues && (n = n._then(this._eachComplete, void 0, void 0, this, void 0)), n._then(c, c, void 0, n, this) }, e.prototype.reduce = function (t, e) { return l(this, t, e, null) }, e.reduce = function (t, e, n, r) { return l(t, e, n, r) } } }, { "./util": 36 }], 29: [function (t, e, n) { "use strict"; var r, i = t("./util"), o = function () { throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n") }; if (i.isNode && "undefined" == typeof MutationObserver) { var s = global.setImmediate, a = process.nextTick; r = i.isRecentNode ? function (t) { s.call(global, t) } : function (t) { a.call(process, t) } } else r = "undefined" == typeof MutationObserver || "undefined" != typeof window && window.navigator && window.navigator.standalone ? "undefined" != typeof setImmediate ? function (t) { setImmediate(t) } : "undefined" != typeof setTimeout ? function (t) { setTimeout(t, 0) } : o : function () { var t = document.createElement("div"), e = { attributes: !0 }, n = !1, r = document.createElement("div"), i = new MutationObserver(function () { t.classList.toggle("foo"), n = !1 }); i.observe(r, e); var o = function () { n || (n = !0, r.classList.toggle("foo")) }; return function (n) { var r = new MutationObserver(function () { r.disconnect(), n() }); r.observe(t, e), o() } }(); e.exports = r }, { "./util": 36 }], 30: [function (t, e, n) { "use strict"; e.exports = function (e, n, r) { function i(t) { this.constructor$(t) } var o = e.PromiseInspection, s = t("./util"); s.inherits(i, n), i.prototype._promiseResolved = function (t, e) { this._values[t] = e; var n = ++this._totalResolved; return n >= this._length ? (this._resolve(this._values), !0) : !1 }, i.prototype._promiseFulfilled = function (t, e) { var n = new o; return n._bitField = 33554432, n._settledValueField = t, this._promiseResolved(e, n) }, i.prototype._promiseRejected = function (t, e) { var n = new o; return n._bitField = 16777216, n._settledValueField = t, this._promiseResolved(e, n) }, e.settle = function (t) { return r.deprecated(".settle()", ".reflect()"), new i(t).promise() }, e.prototype.settle = function () { return e.settle(this) } } }, { "./util": 36 }], 31: [function (t, e, n) { "use strict"; e.exports = function (e, n, r) { function i(t) { this.constructor$(t), this._howMany = 0, this._unwrap = !1, this._initialized = !1 } function o(t, e) { if ((0 | e) !== e || 0 > e) return r("expecting a positive integer\n\n    See http://goo.gl/MqrFmX\n"); var n = new i(t), o = n.promise(); return n.setHowMany(e), n.init(), o } var s = t("./util"), a = t("./errors").RangeError, c = t("./errors").AggregateError, l = s.isArray, u = {}; s.inherits(i, n), i.prototype._init = function () { if (this._initialized) { if (0 === this._howMany) return void this._resolve([]); this._init$(void 0, -5); var t = l(this._values); !this._isResolved() && t && this._howMany > this._canPossiblyFulfill() && this._reject(this._getRangeError(this.length())) } }, i.prototype.init = function () { this._initialized = !0, this._init() }, i.prototype.setUnwrap = function () { this._unwrap = !0 }, i.prototype.howMany = function () { return this._howMany }, i.prototype.setHowMany = function (t) { this._howMany = t }, i.prototype._promiseFulfilled = function (t) { return this._addFulfilled(t), this._fulfilled() === this.howMany() ? (this._values.length = this.howMany(), 1 === this.howMany() && this._unwrap ? this._resolve(this._values[0]) : this._resolve(this._values), !0) : !1 }, i.prototype._promiseRejected = function (t) { return this._addRejected(t), this._checkOutcome() }, i.prototype._promiseCancelled = function () { return this._values instanceof e || null == this._values ? this._cancel() : (this._addRejected(u), this._checkOutcome()) }, i.prototype._checkOutcome = function () { if (this.howMany() > this._canPossiblyFulfill()) { for (var t = new c, e = this.length(); e < this._values.length; ++e)this._values[e] !== u && t.push(this._values[e]); return t.length > 0 ? this._reject(t) : this._cancel(), !0 } return !1 }, i.prototype._fulfilled = function () { return this._totalResolved }, i.prototype._rejected = function () { return this._values.length - this.length() }, i.prototype._addRejected = function (t) { this._values.push(t) }, i.prototype._addFulfilled = function (t) { this._values[this._totalResolved++] = t }, i.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected() }, i.prototype._getRangeError = function (t) { var e = "Input array must contain at least " + this._howMany + " items but contains only " + t + " items"; return new a(e) }, i.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)) }, e.some = function (t, e) { return o(t, e) }, e.prototype.some = function (t) { return o(this, t) }, e._SomePromiseArray = i } }, { "./errors": 12, "./util": 36 }], 32: [function (t, e, n) {
    "use strict"; e.exports = function (t) {
        function e(t) {
        void 0 !== t ? (t = t._target(),
            this._bitField = t._bitField, this._settledValueField = t._isFateSealed() ? t._settledValue() : void 0) : (this._bitField = 0, this._settledValueField = void 0)
        } e.prototype._settledValue = function () { return this._settledValueField }; var n = e.prototype.value = function () { if (!this.isFulfilled()) throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n    See http://goo.gl/MqrFmX\n"); return this._settledValue() }, r = e.prototype.error = e.prototype.reason = function () { if (!this.isRejected()) throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n    See http://goo.gl/MqrFmX\n"); return this._settledValue() }, i = e.prototype.isFulfilled = function () { return 0 !== (33554432 & this._bitField) }, o = e.prototype.isRejected = function () { return 0 !== (16777216 & this._bitField) }, s = e.prototype.isPending = function () { return 0 === (50397184 & this._bitField) }, a = e.prototype.isResolved = function () { return 0 !== (50331648 & this._bitField) }; e.prototype.isCancelled = t.prototype._isCancelled = function () { return 65536 === (65536 & this._bitField) }, t.prototype.isCancelled = function () { return this._target()._isCancelled() }, t.prototype.isPending = function () { return s.call(this._target()) }, t.prototype.isRejected = function () { return o.call(this._target()) }, t.prototype.isFulfilled = function () { return i.call(this._target()) }, t.prototype.isResolved = function () { return a.call(this._target()) }, t.prototype.value = function () { return n.call(this._target()) }, t.prototype.reason = function () { var t = this._target(); return t._unsetRejectionIsUnhandled(), r.call(t) }, t.prototype._value = function () { return this._settledValue() }, t.prototype._reason = function () { return this._unsetRejectionIsUnhandled(), this._settledValue() }, t.PromiseInspection = e
    }
}, {}], 33: [function (t, e, n) { "use strict"; e.exports = function (e, n) { function r(t, r) { if (u(t)) { if (t instanceof e) return t; var i = o(t); if (i === l) { r && r._pushContext(); var c = e.reject(i.e); return r && r._popContext(), c } if ("function" == typeof i) { if (s(t)) { var c = new e(n); return t._then(c._fulfill, c._reject, void 0, c, null), c } return a(t, i, r) } } return t } function i(t) { return t.then } function o(t) { try { return i(t) } catch (e) { return l.e = e, l } } function s(t) { return p.call(t, "_promise0") } function a(t, r, i) { function o(t) { a && (a._resolveCallback(t), a = null) } function s(t) { a && (a._rejectCallback(t, p, !0), a = null) } var a = new e(n), u = a; i && i._pushContext(), a._captureStackTrace(), i && i._popContext(); var p = !0, h = c.tryCatch(r).call(t, o, s); return p = !1, a && h === l && (a._rejectCallback(h.e, !0, !0), a = null), u } var c = t("./util"), l = c.errorObj, u = c.isObject, p = {}.hasOwnProperty; return r } }, { "./util": 36 }], 34: [function (t, e, n) { "use strict"; e.exports = function (e, n, r) { function i(t) { this.handle = t } function o(t) { return clearTimeout(this.handle), t } function s(t) { throw clearTimeout(this.handle), t } var a = t("./util"), c = e.TimeoutError; i.prototype._resultCancelled = function () { clearTimeout(this.handle) }; var l = function (t) { return u(+this).thenReturn(t) }, u = e.delay = function (t, o) { var s, a; return void 0 !== o ? (s = e.resolve(o)._then(l, null, null, t, void 0), r.cancellation() && o instanceof e && s._setOnCancel(o)) : (s = new e(n), a = setTimeout(function () { s._fulfill() }, +t), r.cancellation() && s._setOnCancel(new i(a))), s._setAsyncGuaranteed(), s }; e.prototype.delay = function (t) { return u(t, this) }; var p = function (t, e, n) { var r; r = "string" != typeof e ? e instanceof Error ? e : new c("operation timed out") : new c(e), a.markAsOriginatingFromRejection(r), t._attachExtraTrace(r), t._reject(r), null != n && n.cancel() }; e.prototype.timeout = function (t, e) { t = +t; var n, a, c = new i(setTimeout(function () { n.isPending() && p(n, e, a) }, t)); return r.cancellation() ? (a = this.then(), n = a._then(o, s, void 0, c, void 0), n._setOnCancel(c)) : n = this._then(o, s, void 0, c, void 0), n } } }, { "./util": 36 }], 35: [function (t, e, n) { "use strict"; e.exports = function (e, n, r, i, o, s) { function a(t) { setTimeout(function () { throw t }, 0) } function c(t) { var e = r(t); return e !== t && "function" == typeof t._isDisposable && "function" == typeof t._getDisposer && t._isDisposable() && e._setDisposable(t._getDisposer()), e } function l(t, n) { function i() { if (s >= l) return u._fulfill(); var o = c(t[s++]); if (o instanceof e && o._isDisposable()) { try { o = r(o._getDisposer().tryDispose(n), t.promise) } catch (p) { return a(p) } if (o instanceof e) return o._then(i, a, null, null, null) } i() } var s = 0, l = t.length, u = new e(o); return i(), u } function u(t, e, n) { this._data = t, this._promise = e, this._context = n } function p(t, e, n) { this.constructor$(t, e, n) } function h(t) { return u.isDisposer(t) ? (this.resources[this.index]._setDisposable(t), t.promise()) : t } function f(t) { this.length = t, this.promise = null, this[t - 1] = null } var _ = t("./util"), d = t("./errors").TypeError, v = t("./util").inherits, y = _.errorObj, g = _.tryCatch; u.prototype.data = function () { return this._data }, u.prototype.promise = function () { return this._promise }, u.prototype.resource = function () { return this.promise().isFulfilled() ? this.promise().value() : null }, u.prototype.tryDispose = function (t) { var e = this.resource(), n = this._context; void 0 !== n && n._pushContext(); var r = null !== e ? this.doDispose(e, t) : null; return void 0 !== n && n._popContext(), this._promise._unsetDisposable(), this._data = null, r }, u.isDisposer = function (t) { return null != t && "function" == typeof t.resource && "function" == typeof t.tryDispose }, v(p, u), p.prototype.doDispose = function (t, e) { var n = this.data(); return n.call(t, t, e) }, f.prototype._resultCancelled = function () { for (var t = this.length, n = 0; t > n; ++n) { var r = this[n]; r instanceof e && r.cancel() } }, e.using = function () { var t = arguments.length; if (2 > t) return n("you must pass at least 2 arguments to Promise.using"); var i = arguments[t - 1]; if ("function" != typeof i) return n("expecting a function but got " + _.classString(i)); var o, a = !0; 2 === t && Array.isArray(arguments[0]) ? (o = arguments[0], t = o.length, a = !1) : (o = arguments, t--); for (var c = new f(t), p = 0; t > p; ++p) { var d = o[p]; if (u.isDisposer(d)) { var v = d; d = d.promise(), d._setDisposable(v) } else { var m = r(d); m instanceof e && (d = m._then(h, null, null, { resources: c, index: p }, void 0)) } c[p] = d } for (var b = new Array(c.length), p = 0; p < b.length; ++p)b[p] = e.resolve(c[p]).reflect(); var w = e.all(b).then(function (t) { for (var e = 0; e < t.length; ++e) { var n = t[e]; if (n.isRejected()) return y.e = n.error(), y; if (!n.isFulfilled()) return void w.cancel(); t[e] = n.value() } C._pushContext(), i = g(i); var r = a ? i.apply(void 0, t) : i(t), o = C._popContext(); return s.checkForgottenReturns(r, o, "Promise.using", C), r }), C = w.lastly(function () { var t = new e.PromiseInspection(w); return l(c, t) }); return c.promise = C, C._setOnCancel(c), C }, e.prototype._setDisposable = function (t) { this._bitField = 131072 | this._bitField, this._disposer = t }, e.prototype._isDisposable = function () { return (131072 & this._bitField) > 0 }, e.prototype._getDisposer = function () { return this._disposer }, e.prototype._unsetDisposable = function () { this._bitField = -131073 & this._bitField, this._disposer = void 0 }, e.prototype.disposer = function (t) { if ("function" == typeof t) return new p(t, this, i()); throw new d } } }, { "./errors": 12, "./util": 36 }], 36: [function (t, e, n) { "use strict"; function r() { try { var t = x; return x = null, t.apply(this, arguments) } catch (e) { return F.e = e, F } } function i(t) { return x = t, r } function o(t) { return null == t || t === !0 || t === !1 || "string" == typeof t || "number" == typeof t } function s(t) { return "function" == typeof t || "object" == typeof t && null !== t } function a(t) { return o(t) ? new Error(v(t)) : t } function c(t, e) { var n, r = t.length, i = new Array(r + 1); for (n = 0; r > n; ++n)i[n] = t[n]; return i[n] = e, i } function l(t, e, n) { if (!k.isES5) return {}.hasOwnProperty.call(t, e) ? t[e] : void 0; var r = Object.getOwnPropertyDescriptor(t, e); return null != r ? null == r.get && null == r.set ? r.value : n : void 0 } function u(t, e, n) { if (o(t)) return t; var r = { value: n, configurable: !0, enumerable: !1, writable: !0 }; return k.defineProperty(t, e, r), t } function p(t) { throw t } function h(t) { try { if ("function" == typeof t) { var e = k.names(t.prototype), n = k.isES5 && e.length > 1, r = e.length > 0 && !(1 === e.length && "constructor" === e[0]), i = O.test(t + "") && k.names(t).length > 0; if (n || r || i) return !0 } return !1 } catch (o) { return !1 } } function f(t) { function e() { } e.prototype = t; for (var n = 8; n--;)new e; return t } function _(t) { return S.test(t) } function d(t, e, n) { for (var r = new Array(t), i = 0; t > i; ++i)r[i] = e + i + n; return r } function v(t) { try { return t + "" } catch (e) { return "[no string representation]" } } function y(t) { return null !== t && "object" == typeof t && "string" == typeof t.message && "string" == typeof t.name } function g(t) { try { u(t, "isOperational", !0) } catch (e) { } } function m(t) { return null == t ? !1 : t instanceof Error.__BluebirdErrorTypes__.OperationalError || t.isOperational === !0 } function b(t) { return y(t) && k.propertyIsWritable(t, "stack") } function w(t) { return {}.toString.call(t) } function C(t, e, n) { for (var r = k.names(t), i = 0; i < r.length; ++i) { var o = r[i]; if (n(o)) try { k.defineProperty(e, o, k.getDescriptor(t, o)) } catch (s) { } } } function j(t, e) { return I ? process.env[t] : e } var k = t("./es5"), E = "undefined" == typeof navigator, F = { e: {} }, x, T = "undefined" != typeof self ? self : "undefined" != typeof window ? window : "undefined" != typeof global ? global : void 0 !== this ? this : null, R = function (t, e) { function n() { this.constructor = t, this.constructor$ = e; for (var n in e.prototype) r.call(e.prototype, n) && "$" !== n.charAt(n.length - 1) && (this[n + "$"] = e.prototype[n]) } var r = {}.hasOwnProperty; return n.prototype = e.prototype, t.prototype = new n, t.prototype }, P = function () { var t = [Array.prototype, Object.prototype, Function.prototype], e = function (e) { for (var n = 0; n < t.length; ++n)if (t[n] === e) return !0; return !1 }; if (k.isES5) { var n = Object.getOwnPropertyNames; return function (t) { for (var r = [], i = Object.create(null); null != t && !e(t);) { var o; try { o = n(t) } catch (s) { return r } for (var a = 0; a < o.length; ++a) { var c = o[a]; if (!i[c]) { i[c] = !0; var l = Object.getOwnPropertyDescriptor(t, c); null != l && null == l.get && null == l.set && r.push(c) } } t = k.getPrototypeOf(t) } return r } } var r = {}.hasOwnProperty; return function (n) { if (e(n)) return []; var i = []; t: for (var o in n) if (r.call(n, o)) i.push(o); else { for (var s = 0; s < t.length; ++s)if (r.call(t[s], o)) continue t; i.push(o) } return i } }(), O = /this\s*\.\s*\S+\s*=/, S = /^[a-z$_][a-z$_0-9]*$/i, A = function () { return "stack" in new Error ? function (t) { return b(t) ? t : new Error(v(t)) } : function (t) { if (b(t)) return t; try { throw new Error(v(t)) } catch (e) { return e } } }(), D = function (t) { return k.isArray(t) ? t : null }; if ("undefined" != typeof Symbol && Symbol.iterator) { var V = "function" == typeof Array.from ? function (t) { return Array.from(t) } : function (t) { for (var e, n = [], r = t[Symbol.iterator](); !(e = r.next()).done;)n.push(e.value); return n }; D = function (t) { return k.isArray(t) ? t : null != t && "function" == typeof t[Symbol.iterator] ? V(t) : null } } var I = "undefined" != typeof process && "[object process]" === w(process).toLowerCase(), L = { isClass: h, isIdentifier: _, inheritedDataKeys: P, getDataPropertyOrDefault: l, thrower: p, isArray: k.isArray, asArray: D, notEnumerableProp: u, isPrimitive: o, isObject: s, isError: y, canEvaluate: E, errorObj: F, tryCatch: i, inherits: R, withAppended: c, maybeWrapAsError: a, toFastProperties: f, filledRange: d, toString: v, canAttachTrace: b, ensureErrorObject: A, originatesFromRejection: m, markAsOriginatingFromRejection: g, classString: w, copyDescriptors: C, hasDevTools: "undefined" != typeof chrome && chrome && "function" == typeof chrome.loadTimes, isNode: I, env: j, global: T }; L.isRecentNode = L.isNode && function () { var t = process.versions.node.split(".").map(Number); return 0 === t[0] && t[1] > 10 || t[0] > 0 }(), L.isNode && L.toFastProperties(process); try { throw new Error } catch (H) { L.lastLineError = H } e.exports = L }, { "./es5": 13 }]}, { }, [4]) (4)}), "undefined" != typeof window && null !== window ? window.P = window.Promise : "undefined" != typeof self && null !== self && (self.P = self.Promise);;
/*! @azure/msal-browser v2.8.0 2020-12-07 */
'use strict';
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
        typeof define === 'function' && define.amd ? define(['exports'], factory) :
            (global = global || self, factory(global.msal = {}));
}(this, (function (exports) {
    'use strict';

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */
    /* global Reflect, Promise */

    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };

    function __extends(d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    var __assign = function () {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __awaiter(thisArg, _arguments, P, generator) {
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m) return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
        }
        catch (error) { e = { error: error }; }
        finally {
            try {
                if (r && !r.done && (m = i["return"])) m.call(i);
            }
            finally { if (e) throw e.error; }
        }
        return ar;
    }

    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }

    /*! @azure/msal-common v2.0.0 2020-12-07 */
    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */
    /* global Reflect, Promise */

    var extendStatics$1 = function (d, b) {
        extendStatics$1 = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics$1(d, b);
    };

    function __extends$1(d, b) {
        extendStatics$1(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    var __assign$1 = function () {
        __assign$1 = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign$1.apply(this, arguments);
    };

    function __awaiter$1(thisArg, _arguments, P, generator) {
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator$1(thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var Constants = {
        LIBRARY_NAME: "MSAL.JS",
        SKU: "msal.js.common",
        // Prefix for all library cache entries
        CACHE_PREFIX: "msal",
        // default authority
        DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common/",
        DEFAULT_AUTHORITY_HOST: "login.microsoftonline.com",
        // ADFS String
        ADFS: "adfs",
        // Default AAD Instance Discovery Endpoint
        AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",
        // Resource delimiter - used for certain cache entries
        RESOURCE_DELIM: "|",
        // Placeholder for non-existent account ids/objects
        NO_ACCOUNT: "NO_ACCOUNT",
        // Claims
        CLAIMS: "claims",
        // Consumer UTID
        CONSUMER_UTID: "9188040d-6c67-4c5b-b112-36a304b66dad",
        // Default scopes
        OPENID_SCOPE: "openid",
        PROFILE_SCOPE: "profile",
        OFFLINE_ACCESS_SCOPE: "offline_access",
        // Default response type for authorization code flow
        CODE_RESPONSE_TYPE: "code",
        CODE_GRANT_TYPE: "authorization_code",
        RT_GRANT_TYPE: "refresh_token",
        FRAGMENT_RESPONSE_MODE: "fragment",
        S256_CODE_CHALLENGE_METHOD: "S256",
        URL_FORM_CONTENT_TYPE: "application/x-www-form-urlencoded;charset=utf-8",
        AUTHORIZATION_PENDING: "authorization_pending",
        NOT_DEFINED: "not_defined",
        EMPTY_STRING: "",
        FORWARD_SLASH: "/"
    };
    /**
     * Request header names
     */
    var HeaderNames;
    (function (HeaderNames) {
        HeaderNames["CONTENT_TYPE"] = "Content-Type";
        HeaderNames["X_CLIENT_CURR_TELEM"] = "x-client-current-telemetry";
        HeaderNames["X_CLIENT_LAST_TELEM"] = "x-client-last-telemetry";
        HeaderNames["RETRY_AFTER"] = "Retry-After";
        HeaderNames["X_MS_LIB_CAPABILITY"] = "x-ms-lib-capability";
        HeaderNames["X_MS_LIB_CAPABILITY_VALUE"] = "retry-after, h429";
    })(HeaderNames || (HeaderNames = {}));
    /**
     * Persistent cache keys MSAL which stay while user is logged in.
     */
    var PersistentCacheKeys;
    (function (PersistentCacheKeys) {
        PersistentCacheKeys["ID_TOKEN"] = "idtoken";
        PersistentCacheKeys["CLIENT_INFO"] = "client.info";
        PersistentCacheKeys["ADAL_ID_TOKEN"] = "adal.idtoken";
        PersistentCacheKeys["ERROR"] = "error";
        PersistentCacheKeys["ERROR_DESC"] = "error.description";
    })(PersistentCacheKeys || (PersistentCacheKeys = {}));
    /**
     * String constants related to AAD Authority
     */
    var AADAuthorityConstants;
    (function (AADAuthorityConstants) {
        AADAuthorityConstants["COMMON"] = "common";
        AADAuthorityConstants["ORGANIZATIONS"] = "organizations";
        AADAuthorityConstants["CONSUMERS"] = "consumers";
    })(AADAuthorityConstants || (AADAuthorityConstants = {}));
    /**
     * Keys in the hashParams sent by AAD Server
     */
    var AADServerParamKeys;
    (function (AADServerParamKeys) {
        AADServerParamKeys["CLIENT_ID"] = "client_id";
        AADServerParamKeys["REDIRECT_URI"] = "redirect_uri";
        AADServerParamKeys["RESPONSE_TYPE"] = "response_type";
        AADServerParamKeys["RESPONSE_MODE"] = "response_mode";
        AADServerParamKeys["GRANT_TYPE"] = "grant_type";
        AADServerParamKeys["CLAIMS"] = "claims";
        AADServerParamKeys["SCOPE"] = "scope";
        AADServerParamKeys["ERROR"] = "error";
        AADServerParamKeys["ERROR_DESCRIPTION"] = "error_description";
        AADServerParamKeys["ACCESS_TOKEN"] = "access_token";
        AADServerParamKeys["ID_TOKEN"] = "id_token";
        AADServerParamKeys["REFRESH_TOKEN"] = "refresh_token";
        AADServerParamKeys["EXPIRES_IN"] = "expires_in";
        AADServerParamKeys["STATE"] = "state";
        AADServerParamKeys["NONCE"] = "nonce";
        AADServerParamKeys["PROMPT"] = "prompt";
        AADServerParamKeys["SESSION_STATE"] = "session_state";
        AADServerParamKeys["CLIENT_INFO"] = "client_info";
        AADServerParamKeys["CODE"] = "code";
        AADServerParamKeys["CODE_CHALLENGE"] = "code_challenge";
        AADServerParamKeys["CODE_CHALLENGE_METHOD"] = "code_challenge_method";
        AADServerParamKeys["CODE_VERIFIER"] = "code_verifier";
        AADServerParamKeys["CLIENT_REQUEST_ID"] = "client-request-id";
        AADServerParamKeys["X_CLIENT_SKU"] = "x-client-SKU";
        AADServerParamKeys["X_CLIENT_VER"] = "x-client-VER";
        AADServerParamKeys["X_CLIENT_OS"] = "x-client-OS";
        AADServerParamKeys["X_CLIENT_CPU"] = "x-client-CPU";
        AADServerParamKeys["POST_LOGOUT_URI"] = "post_logout_redirect_uri";
        AADServerParamKeys["ID_TOKEN_HINT"] = "id_token_hint";
        AADServerParamKeys["DEVICE_CODE"] = "device_code";
        AADServerParamKeys["CLIENT_SECRET"] = "client_secret";
        AADServerParamKeys["CLIENT_ASSERTION"] = "client_assertion";
        AADServerParamKeys["CLIENT_ASSERTION_TYPE"] = "client_assertion_type";
        AADServerParamKeys["TOKEN_TYPE"] = "token_type";
        AADServerParamKeys["REQ_CNF"] = "req_cnf";
        AADServerParamKeys["OBO_ASSERTION"] = "assertion";
        AADServerParamKeys["REQUESTED_TOKEN_USE"] = "requested_token_use";
        AADServerParamKeys["ON_BEHALF_OF"] = "on_behalf_of";
        AADServerParamKeys["FOCI"] = "foci";
    })(AADServerParamKeys || (AADServerParamKeys = {}));
    /**
     * Claims request keys
     */
    var ClaimsRequestKeys;
    (function (ClaimsRequestKeys) {
        ClaimsRequestKeys["ACCESS_TOKEN"] = "access_token";
        ClaimsRequestKeys["XMS_CC"] = "xms_cc";
    })(ClaimsRequestKeys || (ClaimsRequestKeys = {}));
    /**
     * we considered making this "enum" in the request instead of string, however it looks like the allowed list of
     * prompt values kept changing over past couple of years. There are some undocumented prompt values for some
     * internal partners too, hence the choice of generic "string" type instead of the "enum"
     */
    var PromptValue = {
        LOGIN: "login",
        SELECT_ACCOUNT: "select_account",
        CONSENT: "consent",
        NONE: "none",
    };
    /**
     * SSO Types - generated to populate hints
     */
    var SSOTypes;
    (function (SSOTypes) {
        SSOTypes["ACCOUNT"] = "account";
        SSOTypes["SID"] = "sid";
        SSOTypes["LOGIN_HINT"] = "login_hint";
        SSOTypes["ID_TOKEN"] = "id_token";
        SSOTypes["DOMAIN_HINT"] = "domain_hint";
        SSOTypes["ORGANIZATIONS"] = "organizations";
        SSOTypes["CONSUMERS"] = "consumers";
        SSOTypes["ACCOUNT_ID"] = "accountIdentifier";
        SSOTypes["HOMEACCOUNT_ID"] = "homeAccountIdentifier";
    })(SSOTypes || (SSOTypes = {}));
    /**
     * Disallowed extra query parameters.
     */
    var BlacklistedEQParams = [
        SSOTypes.SID,
        SSOTypes.LOGIN_HINT
    ];
    /**
     * allowed values for codeVerifier
     */
    var CodeChallengeMethodValues = {
        PLAIN: "plain",
        S256: "S256"
    };
    /**
     * allowed values for response_mode
     */
    var ResponseMode;
    (function (ResponseMode) {
        ResponseMode["QUERY"] = "query";
        ResponseMode["FRAGMENT"] = "fragment";
        ResponseMode["FORM_POST"] = "form_post";
    })(ResponseMode || (ResponseMode = {}));
    /**
     * allowed grant_type
     */
    var GrantType;
    (function (GrantType) {
        GrantType["IMPLICIT_GRANT"] = "implicit";
        GrantType["AUTHORIZATION_CODE_GRANT"] = "authorization_code";
        GrantType["CLIENT_CREDENTIALS_GRANT"] = "client_credentials";
        GrantType["RESOURCE_OWNER_PASSWORD_GRANT"] = "password";
        GrantType["REFRESH_TOKEN_GRANT"] = "refresh_token";
        GrantType["DEVICE_CODE_GRANT"] = "device_code";
        GrantType["JWT_BEARER"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
    })(GrantType || (GrantType = {}));
    /**
     * Account types in Cache
     */
    var CacheAccountType;
    (function (CacheAccountType) {
        CacheAccountType["MSSTS_ACCOUNT_TYPE"] = "MSSTS";
        CacheAccountType["ADFS_ACCOUNT_TYPE"] = "ADFS";
        CacheAccountType["MSAV1_ACCOUNT_TYPE"] = "MSA";
        CacheAccountType["GENERIC_ACCOUNT_TYPE"] = "Generic"; // NTLM, Kerberos, FBA, Basic etc
    })(CacheAccountType || (CacheAccountType = {}));
    /**
     * Separators used in cache
     */
    var Separators;
    (function (Separators) {
        Separators["CACHE_KEY_SEPARATOR"] = "-";
        Separators["CLIENT_INFO_SEPARATOR"] = ".";
    })(Separators || (Separators = {}));
    /**
     * Credential Type stored in the cache
     */
    var CredentialType;
    (function (CredentialType) {
        CredentialType["ID_TOKEN"] = "IdToken";
        CredentialType["ACCESS_TOKEN"] = "AccessToken";
        CredentialType["REFRESH_TOKEN"] = "RefreshToken";
    })(CredentialType || (CredentialType = {}));
    /**
     * Credential Type stored in the cache
     */
    var CacheSchemaType;
    (function (CacheSchemaType) {
        CacheSchemaType["ACCOUNT"] = "Account";
        CacheSchemaType["CREDENTIAL"] = "Credential";
        CacheSchemaType["ID_TOKEN"] = "IdToken";
        CacheSchemaType["ACCESS_TOKEN"] = "AccessToken";
        CacheSchemaType["REFRESH_TOKEN"] = "RefreshToken";
        CacheSchemaType["APP_METADATA"] = "AppMetadata";
        CacheSchemaType["TEMPORARY"] = "TempCache";
        CacheSchemaType["TELEMETRY"] = "Telemetry";
        CacheSchemaType["UNDEFINED"] = "Undefined";
        CacheSchemaType["THROTTLING"] = "Throttling";
    })(CacheSchemaType || (CacheSchemaType = {}));
    /**
     * Combine all cache types
     */
    var CacheType;
    (function (CacheType) {
        CacheType[CacheType["ADFS"] = 1001] = "ADFS";
        CacheType[CacheType["MSA"] = 1002] = "MSA";
        CacheType[CacheType["MSSTS"] = 1003] = "MSSTS";
        CacheType[CacheType["GENERIC"] = 1004] = "GENERIC";
        CacheType[CacheType["ACCESS_TOKEN"] = 2001] = "ACCESS_TOKEN";
        CacheType[CacheType["REFRESH_TOKEN"] = 2002] = "REFRESH_TOKEN";
        CacheType[CacheType["ID_TOKEN"] = 2003] = "ID_TOKEN";
        CacheType[CacheType["APP_METADATA"] = 3001] = "APP_METADATA";
        CacheType[CacheType["UNDEFINED"] = 9999] = "UNDEFINED";
    })(CacheType || (CacheType = {}));
    /**
     * More Cache related constants
     */
    var APP_METADATA = "appmetadata";
    var ClientInfo = "client_info";
    var THE_FAMILY_ID = "1";
    var SERVER_TELEM_CONSTANTS = {
        SCHEMA_VERSION: 2,
        MAX_HEADER_BYTES: 4000,
        CACHE_KEY: "server-telemetry",
        CATEGORY_SEPARATOR: "|",
        VALUE_SEPARATOR: ",",
        OVERFLOW_TRUE: "1",
        OVERFLOW_FALSE: "0",
        UNKNOWN_ERROR: "unknown_error"
    };
    /**
     * Type of the authentication request
     */

    (function (AuthenticationScheme) {
        AuthenticationScheme["POP"] = "pop";
        AuthenticationScheme["BEARER"] = "Bearer";
    })(exports.AuthenticationScheme || (exports.AuthenticationScheme = {}));
    /**
     * Constants related to throttling
     */
    var ThrottlingConstants = {
        // Default time to throttle RequestThumbprint in seconds
        DEFAULT_THROTTLE_TIME_SECONDS: 60,
        // Default maximum time to throttle in seconds, overrides what the server sends back
        DEFAULT_MAX_THROTTLE_TIME_SECONDS: 3600,
        // Prefix for storing throttling entries
        THROTTLING_PREFIX: "throttling"
    };
    var Errors = {
        INVALID_GRANT_ERROR: "invalid_grant",
        CLIENT_MISMATCH_ERROR: "client_mismatch",
    };
    /**
     * Password grant parameters
     */
    var PasswordGrantConstants;
    (function (PasswordGrantConstants) {
        PasswordGrantConstants["username"] = "username";
        PasswordGrantConstants["password"] = "password";
    })(PasswordGrantConstants || (PasswordGrantConstants = {}));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * AuthErrorMessage class containing string constants used by error codes and messages.
     */
    var AuthErrorMessage = {
        unexpectedError: {
            code: "unexpected_error",
            desc: "Unexpected error in authentication."
        }
    };
    /**
     * General error class thrown by the MSAL.js library.
     */
    var AuthError = /** @class */ (function (_super) {
        __extends$1(AuthError, _super);
        function AuthError(errorCode, errorMessage, suberror) {
            var _this = this;
            var errorString = errorMessage ? errorCode + ": " + errorMessage : errorCode;
            _this = _super.call(this, errorString) || this;
            Object.setPrototypeOf(_this, AuthError.prototype);
            _this.errorCode = errorCode || Constants.EMPTY_STRING;
            _this.errorMessage = errorMessage || "";
            _this.subError = suberror || "";
            _this.name = "AuthError";
            return _this;
        }
        /**
         * Creates an error that is thrown when something unexpected happens in the library.
         * @param errDesc
         */
        AuthError.createUnexpectedError = function (errDesc) {
            return new AuthError(AuthErrorMessage.unexpectedError.code, AuthErrorMessage.unexpectedError.desc + ": " + errDesc);
        };
        return AuthError;
    }(Error));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * ClientAuthErrorMessage class containing string constants used by error codes and messages.
     */
    var ClientAuthErrorMessage = {
        clientInfoDecodingError: {
            code: "client_info_decoding_error",
            desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause."
        },
        clientInfoEmptyError: {
            code: "client_info_empty_error",
            desc: "The client info was empty. Please review the trace to determine the root cause."
        },
        tokenParsingError: {
            code: "token_parsing_error",
            desc: "Token cannot be parsed. Please review stack trace to determine root cause."
        },
        nullOrEmptyToken: {
            code: "null_or_empty_token",
            desc: "The token is null or empty. Please review the trace to determine the root cause."
        },
        endpointResolutionError: {
            code: "endpoints_resolution_error",
            desc: "Error: could not resolve endpoints. Please check network and try again."
        },
        hashNotDeserialized: {
            code: "hash_not_deserialized",
            desc: "The hash parameters could not be deserialized. Please review the trace to determine the root cause."
        },
        blankGuidGenerated: {
            code: "blank_guid_generated",
            desc: "The guid generated was blank. Please review the trace to determine the root cause."
        },
        invalidStateError: {
            code: "invalid_state",
            desc: "State was not the expected format. Please check the logs to determine whether the request was sent using ProtocolUtils.setRequestState()."
        },
        stateMismatchError: {
            code: "state_mismatch",
            desc: "State mismatch error. Please check your network. Continued requests may cause cache overflow."
        },
        stateNotFoundError: {
            code: "state_not_found",
            desc: "State not found"
        },
        nonceMismatchError: {
            code: "nonce_mismatch",
            desc: "Nonce mismatch error. This may be caused by a race condition in concurrent requests."
        },
        nonceNotFoundError: {
            code: "nonce_not_found",
            desc: "nonce not found"
        },
        noTokensFoundError: {
            code: "no_tokens_found",
            desc: "No tokens were found for the given scopes, and no authorization code was passed to acquireToken. You must retrieve an authorization code before making a call to acquireToken()."
        },
        multipleMatchingTokens: {
            code: "multiple_matching_tokens",
            desc: "The cache contains multiple tokens satisfying the requirements. " +
                "Call AcquireToken again providing more requirements such as authority or account."
        },
        multipleMatchingAccounts: {
            code: "multiple_matching_accounts",
            desc: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account"
        },
        multipleMatchingAppMetadata: {
            code: "multiple_matching_appMetadata",
            desc: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata"
        },
        tokenRequestCannotBeMade: {
            code: "request_cannot_be_made",
            desc: "Token request cannot be made without authorization code or refresh token."
        },
        appendEmptyScopeError: {
            code: "cannot_append_empty_scope",
            desc: "Cannot append null or empty scope to ScopeSet. Please check the stack trace for more info."
        },
        removeEmptyScopeError: {
            code: "cannot_remove_empty_scope",
            desc: "Cannot remove null or empty scope from ScopeSet. Please check the stack trace for more info."
        },
        appendScopeSetError: {
            code: "cannot_append_scopeset",
            desc: "Cannot append ScopeSet due to error."
        },
        emptyInputScopeSetError: {
            code: "empty_input_scopeset",
            desc: "Empty input ScopeSet cannot be processed."
        },
        DeviceCodePollingCancelled: {
            code: "device_code_polling_cancelled",
            desc: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true."
        },
        DeviceCodeExpired: {
            code: "device_code_expired",
            desc: "Device code is expired."
        },
        NoAccountInSilentRequest: {
            code: "no_account_in_silent_request",
            desc: "Please pass an account object, silent flow is not supported without account information"
        },
        invalidCacheRecord: {
            code: "invalid_cache_record",
            desc: "Cache record object was null or undefined."
        },
        invalidCacheEnvironment: {
            code: "invalid_cache_environment",
            desc: "Invalid environment when attempting to create cache entry"
        },
        noAccountFound: {
            code: "no_account_found",
            desc: "No account found in cache for given key."
        },
        CachePluginError: {
            code: "no cache plugin set on CacheManager",
            desc: "ICachePlugin needs to be set before using readFromStorage or writeFromStorage"
        },
        noCryptoObj: {
            code: "no_crypto_object",
            desc: "No crypto object detected. This is required for the following operation: "
        },
        invalidCacheType: {
            code: "invalid_cache_type",
            desc: "Invalid cache type"
        },
        unexpectedAccountType: {
            code: "unexpected_account_type",
            desc: "Unexpected account type."
        },
        unexpectedCredentialType: {
            code: "unexpected_credential_type",
            desc: "Unexpected credential type."
        },
        invalidAssertion: {
            code: "invalid_assertion",
            desc: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515"
        },
        invalidClientCredential: {
            code: "invalid_client_credential",
            desc: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential"
        },
        tokenRefreshRequired: {
            code: "token_refresh_required",
            desc: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired."
        },
        tokenClaimsRequired: {
            code: "token_claims_cnf_required_for_signedjwt",
            desc: "Cannot generate a POP jwt if the token_claims are not populated"
        },
        noAuthorizationCodeFromServer: {
            code: "authorization_code_missing_from_server_response",
            desc: "Srver response does not contain an authorization code to proceed"
        }
    };
    /**
     * Error thrown when there is an error in the client code running on the browser.
     */
    var ClientAuthError = /** @class */ (function (_super) {
        __extends$1(ClientAuthError, _super);
        function ClientAuthError(errorCode, errorMessage) {
            var _this = _super.call(this, errorCode, errorMessage) || this;
            _this.name = "ClientAuthError";
            Object.setPrototypeOf(_this, ClientAuthError.prototype);
            return _this;
        }
        /**
         * Creates an error thrown when client info object doesn't decode correctly.
         * @param caughtError
         */
        ClientAuthError.createClientInfoDecodingError = function (caughtError) {
            return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code, ClientAuthErrorMessage.clientInfoDecodingError.desc + " Failed with error: " + caughtError);
        };
        /**
         * Creates an error thrown if the client info is empty.
         * @param rawClientInfo
         */
        ClientAuthError.createClientInfoEmptyError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.clientInfoEmptyError.code, "" + ClientAuthErrorMessage.clientInfoEmptyError.desc);
        };
        /**
         * Creates an error thrown when the id token extraction errors out.
         * @param err
         */
        ClientAuthError.createTokenParsingError = function (caughtExtractionError) {
            return new ClientAuthError(ClientAuthErrorMessage.tokenParsingError.code, ClientAuthErrorMessage.tokenParsingError.desc + " Failed with error: " + caughtExtractionError);
        };
        /**
         * Creates an error thrown when the id token string is null or empty.
         * @param invalidRawTokenString
         */
        ClientAuthError.createTokenNullOrEmptyError = function (invalidRawTokenString) {
            return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyToken.code, ClientAuthErrorMessage.nullOrEmptyToken.desc + " Raw Token Value: " + invalidRawTokenString);
        };
        /**
         * Creates an error thrown when the endpoint discovery doesn't complete correctly.
         */
        ClientAuthError.createEndpointDiscoveryIncompleteError = function (errDetail) {
            return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, ClientAuthErrorMessage.endpointResolutionError.desc + " Detail: " + errDetail);
        };
        /**
         * Creates an error thrown when the hash cannot be deserialized.
         * @param hashParamObj
         */
        ClientAuthError.createHashNotDeserializedError = function (hashParamObj) {
            return new ClientAuthError(ClientAuthErrorMessage.hashNotDeserialized.code, ClientAuthErrorMessage.hashNotDeserialized.desc + " Given Object: " + hashParamObj);
        };
        /**
         * Creates an error thrown when the state cannot be parsed.
         * @param invalidState
         */
        ClientAuthError.createInvalidStateError = function (invalidState, errorString) {
            return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code, ClientAuthErrorMessage.invalidStateError.desc + " Invalid State: " + invalidState + ", Root Err: " + errorString);
        };
        /**
         * Creates an error thrown when two states do not match.
         */
        ClientAuthError.createStateMismatchError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.stateMismatchError.code, ClientAuthErrorMessage.stateMismatchError.desc);
        };
        /**
         * Creates an error thrown when the state is not present
         * @param missingState
         */
        ClientAuthError.createStateNotFoundError = function (missingState) {
            return new ClientAuthError(ClientAuthErrorMessage.stateNotFoundError.code, ClientAuthErrorMessage.stateNotFoundError.desc + ":  " + missingState);
        };
        /**
         * Creates an error thrown when the nonce does not match.
         */
        ClientAuthError.createNonceMismatchError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.nonceMismatchError.code, ClientAuthErrorMessage.nonceMismatchError.desc);
        };
        /**
         * Creates an error thrown when the mnonce is not present
         * @param missingNonce
         */
        ClientAuthError.createNonceNotFoundError = function (missingNonce) {
            return new ClientAuthError(ClientAuthErrorMessage.nonceNotFoundError.code, ClientAuthErrorMessage.nonceNotFoundError.desc + ":  " + missingNonce);
        };
        /**
         * Creates an error thrown when the authorization code required for a token request is null or empty.
         */
        ClientAuthError.createNoTokensFoundError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.noTokensFoundError.code, ClientAuthErrorMessage.noTokensFoundError.desc);
        };
        /**
         * Throws error when multiple tokens are in cache.
         */
        ClientAuthError.createMultipleMatchingTokensInCacheError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, ClientAuthErrorMessage.multipleMatchingTokens.desc + ".");
        };
        /**
         * Throws error when multiple accounts are in cache for the given params
         */
        ClientAuthError.createMultipleMatchingAccountsInCacheError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAccounts.code, ClientAuthErrorMessage.multipleMatchingAccounts.desc);
        };
        /**
         * Throws error when multiple appMetada are in cache for the given clientId.
         */
        ClientAuthError.createMultipleMatchingAppMetadataInCacheError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAppMetadata.code, ClientAuthErrorMessage.multipleMatchingAppMetadata.desc);
        };
        /**
         * Throws error when no auth code or refresh token is given to ServerTokenRequestParameters.
         */
        ClientAuthError.createTokenRequestCannotBeMadeError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.tokenRequestCannotBeMade.code, ClientAuthErrorMessage.tokenRequestCannotBeMade.desc);
        };
        /**
         * Throws error when attempting to append a null, undefined or empty scope to a set
         * @param givenScope
         */
        ClientAuthError.createAppendEmptyScopeToSetError = function (givenScope) {
            return new ClientAuthError(ClientAuthErrorMessage.appendEmptyScopeError.code, ClientAuthErrorMessage.appendEmptyScopeError.desc + " Given Scope: " + givenScope);
        };
        /**
         * Throws error when attempting to append a null, undefined or empty scope to a set
         * @param givenScope
         */
        ClientAuthError.createRemoveEmptyScopeFromSetError = function (givenScope) {
            return new ClientAuthError(ClientAuthErrorMessage.removeEmptyScopeError.code, ClientAuthErrorMessage.removeEmptyScopeError.desc + " Given Scope: " + givenScope);
        };
        /**
         * Throws error when attempting to append null or empty ScopeSet.
         * @param appendError
         */
        ClientAuthError.createAppendScopeSetError = function (appendError) {
            return new ClientAuthError(ClientAuthErrorMessage.appendScopeSetError.code, ClientAuthErrorMessage.appendScopeSetError.desc + " Detail Error: " + appendError);
        };
        /**
         * Throws error if ScopeSet is null or undefined.
         * @param givenScopeSet
         */
        ClientAuthError.createEmptyInputScopeSetError = function (givenScopeSet) {
            return new ClientAuthError(ClientAuthErrorMessage.emptyInputScopeSetError.code, ClientAuthErrorMessage.emptyInputScopeSetError.desc + " Given ScopeSet: " + givenScopeSet);
        };
        /**
         * Throws error if user sets CancellationToken.cancel = true during polling of token endpoint during device code flow
         */
        ClientAuthError.createDeviceCodeCancelledError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.DeviceCodePollingCancelled.code, "" + ClientAuthErrorMessage.DeviceCodePollingCancelled.desc);
        };
        /**
         * Throws error if device code is expired
         */
        ClientAuthError.createDeviceCodeExpiredError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeExpired.code, "" + ClientAuthErrorMessage.DeviceCodeExpired.desc);
        };
        /**
         * Throws error when silent requests are made without an account object
         */
        ClientAuthError.createNoAccountInSilentRequestError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.NoAccountInSilentRequest.code, "" + ClientAuthErrorMessage.NoAccountInSilentRequest.desc);
        };
        /**
         * Throws error when cache record is null or undefined.
         */
        ClientAuthError.createNullOrUndefinedCacheRecord = function () {
            return new ClientAuthError(ClientAuthErrorMessage.invalidCacheRecord.code, ClientAuthErrorMessage.invalidCacheRecord.desc);
        };
        /**
         * Throws error when provided environment is not part of the CloudDiscoveryMetadata object
         */
        ClientAuthError.createInvalidCacheEnvironmentError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.invalidCacheEnvironment.code, ClientAuthErrorMessage.invalidCacheEnvironment.desc);
        };
        /**
         * Throws error when account is not found in cache.
         */
        ClientAuthError.createNoAccountFoundError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.noAccountFound.code, ClientAuthErrorMessage.noAccountFound.desc);
        };
        /**
         * Throws error if ICachePlugin not set on CacheManager.
         */
        ClientAuthError.createCachePluginError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.CachePluginError.code, "" + ClientAuthErrorMessage.CachePluginError.desc);
        };
        /**
         * Throws error if crypto object not found.
         * @param operationName
         */
        ClientAuthError.createNoCryptoObjectError = function (operationName) {
            return new ClientAuthError(ClientAuthErrorMessage.noCryptoObj.code, "" + ClientAuthErrorMessage.noCryptoObj.desc + operationName);
        };
        /**
         * Throws error if cache type is invalid.
         */
        ClientAuthError.createInvalidCacheTypeError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.invalidCacheType.code, "" + ClientAuthErrorMessage.invalidCacheType.desc);
        };
        /**
         * Throws error if unexpected account type.
         */
        ClientAuthError.createUnexpectedAccountTypeError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.unexpectedAccountType.code, "" + ClientAuthErrorMessage.unexpectedAccountType.desc);
        };
        /**
         * Throws error if unexpected credential type.
         */
        ClientAuthError.createUnexpectedCredentialTypeError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.unexpectedCredentialType.code, "" + ClientAuthErrorMessage.unexpectedCredentialType.desc);
        };
        /**
         * Throws error if client assertion is not valid.
         */
        ClientAuthError.createInvalidAssertionError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.invalidAssertion.code, "" + ClientAuthErrorMessage.invalidAssertion.desc);
        };
        /**
         * Throws error if client assertion is not valid.
         */
        ClientAuthError.createInvalidCredentialError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.invalidClientCredential.code, "" + ClientAuthErrorMessage.invalidClientCredential.desc);
        };
        /**
         * Throws error if token cannot be retrieved from cache due to refresh being required.
         */
        ClientAuthError.createRefreshRequiredError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.tokenRefreshRequired.code, ClientAuthErrorMessage.tokenRefreshRequired.desc);
        };
        /**
         * Throws error if token claims are not populated for a signed jwt generation
         */
        ClientAuthError.createTokenClaimsRequiredError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.tokenClaimsRequired.code, ClientAuthErrorMessage.tokenClaimsRequired.desc);
        };
        /**
         * Throws error when the authorization code is missing from the server response
         */
        ClientAuthError.createNoAuthCodeInServerResponseError = function () {
            return new ClientAuthError(ClientAuthErrorMessage.noAuthorizationCodeFromServer.code, ClientAuthErrorMessage.noAuthorizationCodeFromServer.desc);
        };
        return ClientAuthError;
    }(AuthError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * @hidden
     */
    var StringUtils = /** @class */ (function () {
        function StringUtils() {
        }
        /**
         * decode a JWT
         *
         * @param authToken
         */
        StringUtils.decodeAuthToken = function (authToken) {
            if (StringUtils.isEmpty(authToken)) {
                throw ClientAuthError.createTokenNullOrEmptyError(authToken);
            }
            var tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
            var matches = tokenPartsRegex.exec(authToken);
            if (!matches || matches.length < 4) {
                throw ClientAuthError.createTokenParsingError("Given token is malformed: " + JSON.stringify(authToken));
            }
            var crackedToken = {
                header: matches[1],
                JWSPayload: matches[2],
                JWSSig: matches[3]
            };
            return crackedToken;
        };
        /**
         * Check if a string is empty.
         *
         * @param str
         */
        StringUtils.isEmpty = function (str) {
            return (typeof str === "undefined" || !str || 0 === str.length);
        };
        StringUtils.startsWith = function (str, search) {
            return str.indexOf(search) === 0;
        };
        StringUtils.endsWith = function (str, search) {
            return (str.length >= search.length) && (str.lastIndexOf(search) === (str.length - search.length));
        };
        /**
         * Parses string into an object.
         *
         * @param query
         */
        StringUtils.queryStringToObject = function (query) {
            var match; // Regex for replacing addition symbol with a space
            var pl = /\+/g;
            var search = /([^&=]+)=([^&]*)/g;
            var decode = function (s) { return decodeURIComponent(decodeURIComponent(s.replace(pl, " "))); };
            var obj = {};
            match = search.exec(query);
            while (match) {
                obj[decode(match[1])] = decode(match[2]);
                match = search.exec(query);
            }
            return obj;
        };
        /**
         * Trims entries in an array.
         *
         * @param arr
         */
        StringUtils.trimArrayEntries = function (arr) {
            return arr.map(function (entry) { return entry.trim(); });
        };
        /**
         * Removes empty strings from array
         * @param arr
         */
        StringUtils.removeEmptyStringsFromArray = function (arr) {
            return arr.filter(function (entry) {
                return !StringUtils.isEmpty(entry);
            });
        };
        /**
         * Attempts to parse a string into JSON
         * @param str
         */
        StringUtils.jsonParseHelper = function (str) {
            try {
                return JSON.parse(str);
            }
            catch (e) {
                return null;
            }
        };
        /**
         * Tests if a given string matches a given pattern, with support for wildcards.
         * @param pattern Wildcard pattern to string match. Supports "*" for wildcards
         * @param input String to match against
         */
        StringUtils.matchPattern = function (pattern, input) {
            // https://stackoverflow.com/a/3117248/4888559
            var regex = new RegExp(pattern.replace(/\*/g, "[^ ]*"));
            return regex.test(input);
        };
        return StringUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Log message level.
     */

    (function (LogLevel) {
        LogLevel[LogLevel["Error"] = 0] = "Error";
        LogLevel[LogLevel["Warning"] = 1] = "Warning";
        LogLevel[LogLevel["Info"] = 2] = "Info";
        LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
    })(exports.LogLevel || (exports.LogLevel = {}));
    /**
     * Class which facilitates logging of messages to a specific place.
     */
    var Logger = /** @class */ (function () {
        function Logger(loggerOptions, packageName, packageVersion) {
            // Current log level, defaults to info.
            this.level = exports.LogLevel.Info;
            var defaultLoggerCallback = function () { };
            this.localCallback = loggerOptions.loggerCallback || defaultLoggerCallback;
            this.piiLoggingEnabled = loggerOptions.piiLoggingEnabled || false;
            this.level = loggerOptions.logLevel || exports.LogLevel.Info;
            this.packageName = packageName || Constants.EMPTY_STRING;
            this.packageVersion = packageVersion || Constants.EMPTY_STRING;
        }
        /**
         * Create new Logger with existing configurations.
         */
        Logger.prototype.clone = function (packageName, packageVersion) {
            return new Logger({ loggerCallback: this.localCallback, piiLoggingEnabled: this.piiLoggingEnabled, logLevel: this.level }, packageName, packageVersion);
        };
        /**
         * Log message with required options.
         */
        Logger.prototype.logMessage = function (logMessage, options) {
            if ((options.logLevel > this.level) || (!this.piiLoggingEnabled && options.containsPii)) {
                return;
            }
            var timestamp = new Date().toUTCString();
            var logHeader = StringUtils.isEmpty(this.correlationId) ? "[" + timestamp + "] : " : "[" + timestamp + "] : [" + this.correlationId + "]";
            var log = logHeader + " : " + this.packageName + "@" + this.packageVersion + " : " + exports.LogLevel[options.logLevel] + " - " + logMessage;
            // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": ""}${options.context ? `:${options.context}` : ""}`)(logMessage);
            this.executeCallback(options.logLevel, log, options.containsPii || false);
        };
        /**
         * Execute callback with message.
         */
        Logger.prototype.executeCallback = function (level, message, containsPii) {
            if (this.localCallback) {
                this.localCallback(level, message, containsPii);
            }
        };
        /**
         * Logs error messages.
         */
        Logger.prototype.error = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Error,
                containsPii: false,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs error messages with PII.
         */
        Logger.prototype.errorPii = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Error,
                containsPii: true,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs warning messages.
         */
        Logger.prototype.warning = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Warning,
                containsPii: false,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs warning messages with PII.
         */
        Logger.prototype.warningPii = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Warning,
                containsPii: true,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs info messages.
         */
        Logger.prototype.info = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Info,
                containsPii: false,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs info messages with PII.
         */
        Logger.prototype.infoPii = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Info,
                containsPii: true,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs verbose messages.
         */
        Logger.prototype.verbose = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Verbose,
                containsPii: false,
                correlationId: correlationId || ""
            });
        };
        /**
         * Logs verbose messages with PII.
         */
        Logger.prototype.verbosePii = function (message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Verbose,
                containsPii: true,
                correlationId: correlationId || ""
            });
        };
        /**
         * Returns whether PII Logging is enabled or not.
         */
        Logger.prototype.isPiiLoggingEnabled = function () {
            return this.piiLoggingEnabled || false;
        };
        return Logger;
    }());

    var name = "@azure/msal-common";
    var version = "2.0.0";

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Base type for credentials to be stored in the cache: eg: ACCESS_TOKEN, ID_TOKEN etc
     *
     * Key:Value Schema:
     *
     * Key: <home_account_id*>-<environment>-<credential_type>-<client_id>-<realm*>-<target*>
     *
     * Value Schema:
     * {
     *      homeAccountId: home account identifier for the auth scheme,
     *      environment: entity that issued the token, represented as a full host
     *      credentialType: Type of credential as a string, can be one of the following: RefreshToken, AccessToken, IdToken, Password, Cookie, Certificate, Other
     *      clientId: client ID of the application
     *      secret: Actual credential as a string
     *      familyId: Family ID identifier, usually only used for refresh tokens
     *      realm: Full tenant or organizational identifier that the account belongs to
     *      target: Permissions that are included in the token, or for refresh tokens, the resource identifier.
     *      oboAssertion: access token passed in as part of OBO request
     * }
     */
    var CredentialEntity = /** @class */ (function () {
        function CredentialEntity() {
        }
        /**
         * Generate Account Id key component as per the schema: <home_account_id>-<environment>
         */
        CredentialEntity.prototype.generateAccountId = function () {
            return CredentialEntity.generateAccountIdForCacheKey(this.homeAccountId, this.environment);
        };
        /**
         * Generate Credential Id key component as per the schema: <credential_type>-<client_id>-<realm>
         */
        CredentialEntity.prototype.generateCredentialId = function () {
            return CredentialEntity.generateCredentialIdForCacheKey(this.credentialType, this.clientId, this.realm, this.familyId);
        };
        /**
         * Generate target key component as per schema: <target>
         */
        CredentialEntity.prototype.generateTarget = function () {
            return CredentialEntity.generateTargetForCacheKey(this.target);
        };
        /**
         * generates credential key
         */
        CredentialEntity.prototype.generateCredentialKey = function () {
            return CredentialEntity.generateCredentialCacheKey(this.homeAccountId, this.environment, this.credentialType, this.clientId, this.realm, this.target, this.familyId);
        };
        /**
         * returns the type of the cache (in this case credential)
         */
        CredentialEntity.prototype.generateType = function () {
            switch (this.credentialType) {
                case CredentialType.ID_TOKEN:
                    return CacheType.ID_TOKEN;
                case CredentialType.ACCESS_TOKEN:
                    return CacheType.ACCESS_TOKEN;
                case CredentialType.REFRESH_TOKEN:
                    return CacheType.REFRESH_TOKEN;
                default: {
                    throw ClientAuthError.createUnexpectedCredentialTypeError();
                }
            }
        };
        /**
         * helper function to return `CredentialType`
         * @param key
         */
        CredentialEntity.getCredentialType = function (key) {
            if (key.indexOf(CredentialType.ACCESS_TOKEN.toLowerCase()) !== -1) {
                return CredentialType.ACCESS_TOKEN;
            }
            else if (key.indexOf(CredentialType.ID_TOKEN.toLowerCase()) !== -1) {
                return CredentialType.ID_TOKEN;
            }
            else if (key.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) !== -1) {
                return CredentialType.REFRESH_TOKEN;
            }
            return Constants.NOT_DEFINED;
        };
        /**
         * generates credential key
         */
        CredentialEntity.generateCredentialCacheKey = function (homeAccountId, environment, credentialType, clientId, realm, target, familyId) {
            var credentialKey = [
                this.generateAccountIdForCacheKey(homeAccountId, environment),
                this.generateCredentialIdForCacheKey(credentialType, clientId, realm, familyId),
                this.generateTargetForCacheKey(target),
            ];
            return credentialKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * generates Account Id for keys
         * @param homeAccountId
         * @param environment
         */
        CredentialEntity.generateAccountIdForCacheKey = function (homeAccountId, environment) {
            var accountId = [homeAccountId, environment];
            return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * Generates Credential Id for keys
         * @param credentialType
         * @param realm
         * @param clientId
         * @param familyId
         */
        CredentialEntity.generateCredentialIdForCacheKey = function (credentialType, clientId, realm, familyId) {
            var clientOrFamilyId = credentialType === CredentialType.REFRESH_TOKEN
                ? familyId || clientId
                : clientId;
            var credentialId = [
                credentialType,
                clientOrFamilyId,
                realm || "",
            ];
            return credentialId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * Generate target key component as per schema: <target>
         */
        CredentialEntity.generateTargetForCacheKey = function (scopes) {
            return (scopes || "").toLowerCase();
        };
        return CredentialEntity;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * ClientConfigurationErrorMessage class containing string constants used by error codes and messages.
     */
    var ClientConfigurationErrorMessage = {
        redirectUriNotSet: {
            code: "redirect_uri_empty",
            desc: "A redirect URI is required for all calls, and none has been set."
        },
        postLogoutUriNotSet: {
            code: "post_logout_uri_empty",
            desc: "A post logout redirect has not been set."
        },
        claimsRequestParsingError: {
            code: "claims_request_parsing_error",
            desc: "Could not parse the given claims request object."
        },
        authorityUriInsecure: {
            code: "authority_uri_insecure",
            desc: "Authority URIs must use https.  Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options"
        },
        urlParseError: {
            code: "url_parse_error",
            desc: "URL could not be parsed into appropriate segments."
        },
        urlEmptyError: {
            code: "empty_url_error",
            desc: "URL was empty or null."
        },
        emptyScopesError: {
            code: "empty_input_scopes_error",
            desc: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token."
        },
        nonArrayScopesError: {
            code: "nonarray_input_scopes_error",
            desc: "Scopes cannot be passed as non-array."
        },
        clientIdSingleScopeError: {
            code: "clientid_input_scopes_error",
            desc: "Client ID can only be provided as a single scope."
        },
        invalidPrompt: {
            code: "invalid_prompt_value",
            desc: "Supported prompt values are 'login', 'select_account', 'consent' and 'none'.  Please see here for valid configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",
        },
        invalidClaimsRequest: {
            code: "invalid_claims",
            desc: "Given claims parameter must be a stringified JSON object."
        },
        tokenRequestEmptyError: {
            code: "token_request_empty",
            desc: "Token request was empty and not found in cache."
        },
        logoutRequestEmptyError: {
            code: "logout_request_empty",
            desc: "The logout request was null or undefined."
        },
        invalidCodeChallengeMethod: {
            code: "invalid_code_challenge_method",
            desc: "code_challenge_method passed is invalid. Valid values are \"plain\" and \"S256\"."
        },
        invalidCodeChallengeParams: {
            code: "pkce_params_missing",
            desc: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request"
        },
        knownAuthoritiesAndCloudDiscoveryMetadata: {
            code: "invalid_known_authorities",
            desc: "knownAuthorities and cloudDiscoveryMetadata cannot both be provided. Please provide cloudDiscoveryMetadata object for AAD, knownAuthorities otherwise."
        },
        invalidCloudDiscoveryMetadata: {
            code: "invalid_cloud_discovery_metadata",
            desc: "Invalid cloudDiscoveryMetadata provided. Must be a JSON object containing tenant_discovery_endpoint and metadata fields"
        },
        untrustedAuthority: {
            code: "untrusted_authority",
            desc: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter."
        },
        resourceRequestParametersRequired: {
            code: "resourceRequest_parameters_required",
            desc: "resourceRequestMethod and resourceRequestUri are required"
        }
    };
    /**
     * Error thrown when there is an error in configuration of the MSAL.js library.
     */
    var ClientConfigurationError = /** @class */ (function (_super) {
        __extends$1(ClientConfigurationError, _super);
        function ClientConfigurationError(errorCode, errorMessage) {
            var _this = _super.call(this, errorCode, errorMessage) || this;
            _this.name = "ClientConfigurationError";
            Object.setPrototypeOf(_this, ClientConfigurationError.prototype);
            return _this;
        }
        /**
         * Creates an error thrown when the redirect uri is empty (not set by caller)
         */
        ClientConfigurationError.createRedirectUriEmptyError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.redirectUriNotSet.code, ClientConfigurationErrorMessage.redirectUriNotSet.desc);
        };
        /**
         * Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
         */
        ClientConfigurationError.createPostLogoutRedirectUriEmptyError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.postLogoutUriNotSet.code, ClientConfigurationErrorMessage.postLogoutUriNotSet.desc);
        };
        /**
         * Creates an error thrown when the claims request could not be successfully parsed
         */
        ClientConfigurationError.createClaimsRequestParsingError = function (claimsRequestParseError) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.claimsRequestParsingError.code, ClientConfigurationErrorMessage.claimsRequestParsingError.desc + " Given value: " + claimsRequestParseError);
        };
        /**
         * Creates an error thrown if authority uri is given an insecure protocol.
         * @param urlString
         */
        ClientConfigurationError.createInsecureAuthorityUriError = function (urlString) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.authorityUriInsecure.code, ClientConfigurationErrorMessage.authorityUriInsecure.desc + " Given URI: " + urlString);
        };
        /**
         * Creates an error thrown if URL string does not parse into separate segments.
         * @param urlString
         */
        ClientConfigurationError.createUrlParseError = function (urlParseError) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.urlParseError.code, ClientConfigurationErrorMessage.urlParseError.desc + " Given Error: " + urlParseError);
        };
        /**
         * Creates an error thrown if URL string is empty or null.
         * @param urlString
         */
        ClientConfigurationError.createUrlEmptyError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.urlEmptyError.code, ClientConfigurationErrorMessage.urlEmptyError.desc);
        };
        /**
         * Error thrown when scopes are not an array
         * @param inputScopes
         */
        ClientConfigurationError.createScopesNonArrayError = function (inputScopes) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.nonArrayScopesError.code, ClientConfigurationErrorMessage.nonArrayScopesError.desc + " Given Scopes: " + inputScopes);
        };
        /**
         * Error thrown when scopes are empty.
         * @param scopesValue
         */
        ClientConfigurationError.createEmptyScopesArrayError = function (inputScopes) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.emptyScopesError.code, ClientConfigurationErrorMessage.emptyScopesError.desc + " Given Scopes: " + inputScopes);
        };
        /**
         * Error thrown when client id scope is not provided as single scope.
         * @param inputScopes
         */
        ClientConfigurationError.createClientIdSingleScopeError = function (inputScopes) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.clientIdSingleScopeError.code, ClientConfigurationErrorMessage.clientIdSingleScopeError.desc + " Given Scopes: " + inputScopes);
        };
        /**
         * Error thrown when prompt is not an allowed type.
         * @param promptValue
         */
        ClientConfigurationError.createInvalidPromptError = function (promptValue) {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidPrompt.code, ClientConfigurationErrorMessage.invalidPrompt.desc + " Given value: " + promptValue);
        };
        /**
         * Creates error thrown when claims parameter is not a stringified JSON object
         */
        ClientConfigurationError.createInvalidClaimsRequestError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidClaimsRequest.code, ClientConfigurationErrorMessage.invalidClaimsRequest.desc);
        };
        /**
         * Throws error when token request is empty and nothing cached in storage.
         */
        ClientConfigurationError.createEmptyLogoutRequestError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.logoutRequestEmptyError.code, ClientConfigurationErrorMessage.logoutRequestEmptyError.desc);
        };
        /**
         * Throws error when token request is empty and nothing cached in storage.
         */
        ClientConfigurationError.createEmptyTokenRequestError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.tokenRequestEmptyError.code, ClientConfigurationErrorMessage.tokenRequestEmptyError.desc);
        };
        /**
         * Throws error when an invalid code_challenge_method is passed by the user
         */
        ClientConfigurationError.createInvalidCodeChallengeMethodError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeMethod.code, ClientConfigurationErrorMessage.invalidCodeChallengeMethod.desc);
        };
        /**
         * Throws error when both params: code_challenge and code_challenge_method are not passed together
         */
        ClientConfigurationError.createInvalidCodeChallengeParamsError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeParams.code, ClientConfigurationErrorMessage.invalidCodeChallengeParams.desc);
        };
        /**
         * Throws an error when the user passes both knownAuthorities and cloudDiscoveryMetadata
         */
        ClientConfigurationError.createKnownAuthoritiesCloudDiscoveryMetadataError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.knownAuthoritiesAndCloudDiscoveryMetadata.code, ClientConfigurationErrorMessage.knownAuthoritiesAndCloudDiscoveryMetadata.desc);
        };
        /**
         * Throws an error when the user passes invalid cloudDiscoveryMetadata
         */
        ClientConfigurationError.createInvalidCloudDiscoveryMetadataError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.code, ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.desc);
        };
        /**
         * Throws error when provided authority is not a member of the trusted host list
         */
        ClientConfigurationError.createUntrustedAuthorityError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.untrustedAuthority.code, ClientConfigurationErrorMessage.untrustedAuthority.desc);
        };
        /**
         * Throws error when resourceRequestMethod or resourceRequestUri is missing
         */
        ClientConfigurationError.createResourceRequestParametersRequiredError = function () {
            return new ClientConfigurationError(ClientConfigurationErrorMessage.resourceRequestParametersRequired.code, ClientConfigurationErrorMessage.resourceRequestParametersRequired.desc);
        };
        return ClientConfigurationError;
    }(ClientAuthError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes
     * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions
     * to ensure uniqueness of strings.
     */
    var ScopeSet = /** @class */ (function () {
        function ScopeSet(inputScopes) {
            var _this = this;
            // Filter empty string and null/undefined array items
            var scopeArr = inputScopes ? StringUtils.trimArrayEntries(__spreadArrays(inputScopes)) : [];
            var filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : [];
            // Validate and filter scopes (validate function throws if validation fails)
            this.validateInputScopes(filteredInput);
            this.scopes = new Set(); // Iterator in constructor not supported by IE11
            filteredInput.forEach(function (scope) { return _this.scopes.add(scope); });
        }
        /**
         * Factory method to create ScopeSet from space-delimited string
         * @param inputScopeString
         * @param appClientId
         * @param scopesRequired
         */
        ScopeSet.fromString = function (inputScopeString) {
            inputScopeString = inputScopeString || "";
            var inputScopes = inputScopeString.split(" ");
            return new ScopeSet(inputScopes);
        };
        /**
         * Used to validate the scopes input parameter requested  by the developer.
         * @param {Array<string>} inputScopes - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.
         * @param {boolean} scopesRequired - Boolean indicating whether the scopes array is required or not
         */
        ScopeSet.prototype.validateInputScopes = function (inputScopes) {
            // Check if scopes are required but not given or is an empty array
            if (!inputScopes || inputScopes.length < 1) {
                throw ClientConfigurationError.createEmptyScopesArrayError(inputScopes);
            }
        };
        /**
         * Check if a given scope is present in this set of scopes.
         * @param scope
         */
        ScopeSet.prototype.containsScope = function (scope) {
            var lowerCaseScopes = this.printScopesLowerCase().split(" ");
            var lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);
            // compare lowercase scopes
            return !StringUtils.isEmpty(scope) ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false;
        };
        /**
         * Check if a set of scopes is present in this set of scopes.
         * @param scopeSet
         */
        ScopeSet.prototype.containsScopeSet = function (scopeSet) {
            var _this = this;
            if (!scopeSet || scopeSet.scopes.size <= 0) {
                return false;
            }
            return (this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every(function (scope) { return _this.containsScope(scope); }));
        };
        /**
         * Check if set of scopes contains only the defaults
         */
        ScopeSet.prototype.containsOnlyDefaultScopes = function () {
            var defaultScopeCount = 0;
            if (this.containsScope(Constants.OPENID_SCOPE)) {
                defaultScopeCount += 1;
            }
            if (this.containsScope(Constants.PROFILE_SCOPE)) {
                defaultScopeCount += 1;
            }
            if (this.containsScope(Constants.OFFLINE_ACCESS_SCOPE)) {
                defaultScopeCount += 1;
            }
            return this.scopes.size === defaultScopeCount;
        };
        /**
         * Appends single scope if passed
         * @param newScope
         */
        ScopeSet.prototype.appendScope = function (newScope) {
            if (!StringUtils.isEmpty(newScope)) {
                this.scopes.add(newScope.trim());
            }
        };
        /**
         * Appends multiple scopes if passed
         * @param newScopes
         */
        ScopeSet.prototype.appendScopes = function (newScopes) {
            var _this = this;
            try {
                newScopes.forEach(function (newScope) { return _this.appendScope(newScope); });
            }
            catch (e) {
                throw ClientAuthError.createAppendScopeSetError(e);
            }
        };
        /**
         * Removes element from set of scopes.
         * @param scope
         */
        ScopeSet.prototype.removeScope = function (scope) {
            if (StringUtils.isEmpty(scope)) {
                throw ClientAuthError.createRemoveEmptyScopeFromSetError(scope);
            }
            this.scopes.delete(scope.trim());
        };
        /**
         * Removes default scopes from set of scopes
         * Primarily used to prevent cache misses if the default scopes are not returned from the server
         */
        ScopeSet.prototype.removeDefaultScopes = function () {
            this.scopes.delete(Constants.OFFLINE_ACCESS_SCOPE);
            this.scopes.delete(Constants.OPENID_SCOPE);
            this.scopes.delete(Constants.PROFILE_SCOPE);
        };
        /**
         * Combines an array of scopes with the current set of scopes.
         * @param otherScopes
         */
        ScopeSet.prototype.unionScopeSets = function (otherScopes) {
            if (!otherScopes) {
                throw ClientAuthError.createEmptyInputScopeSetError(otherScopes);
            }
            var unionScopes = new Set(); // Iterator in constructor not supported in IE11
            otherScopes.scopes.forEach(function (scope) { return unionScopes.add(scope.toLowerCase()); });
            this.scopes.forEach(function (scope) { return unionScopes.add(scope.toLowerCase()); });
            return unionScopes;
        };
        /**
         * Check if scopes intersect between this set and another.
         * @param otherScopes
         */
        ScopeSet.prototype.intersectingScopeSets = function (otherScopes) {
            if (!otherScopes) {
                throw ClientAuthError.createEmptyInputScopeSetError(otherScopes);
            }
            var unionScopes = this.unionScopeSets(otherScopes);
            // Do not allow default scopes to be the only intersecting scopes
            if (!otherScopes.containsOnlyDefaultScopes()) {
                otherScopes.removeDefaultScopes();
            }
            var sizeOtherScopes = otherScopes.getScopeCount();
            var sizeThisScopes = this.getScopeCount();
            var sizeUnionScopes = unionScopes.size;
            return sizeUnionScopes < (sizeThisScopes + sizeOtherScopes);
        };
        /**
         * Returns size of set of scopes.
         */
        ScopeSet.prototype.getScopeCount = function () {
            return this.scopes.size;
        };
        /**
         * Returns the scopes as an array of string values
         */
        ScopeSet.prototype.asArray = function () {
            var array = [];
            this.scopes.forEach(function (val) { return array.push(val); });
            return array;
        };
        /**
         * Prints scopes into a space-delimited string
         */
        ScopeSet.prototype.printScopes = function () {
            if (this.scopes) {
                var scopeArr = this.asArray();
                return scopeArr.join(" ");
            }
            return "";
        };
        /**
         * Prints scopes into a space-delimited lower-case string (used for caching)
         */
        ScopeSet.prototype.printScopesLowerCase = function () {
            return this.printScopes().toLowerCase();
        };
        return ScopeSet;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Authority types supported by MSAL.
     */
    var AuthorityType;
    (function (AuthorityType) {
        AuthorityType[AuthorityType["Default"] = 0] = "Default";
        AuthorityType[AuthorityType["Adfs"] = 1] = "Adfs";
    })(AuthorityType || (AuthorityType = {}));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Url object class which can perform various transformations on url strings.
     */
    var UrlString = /** @class */ (function () {
        function UrlString(url) {
            this._urlString = url;
            if (StringUtils.isEmpty(this._urlString)) {
                // Throws error if url is empty
                throw ClientConfigurationError.createUrlEmptyError();
            }
            if (StringUtils.isEmpty(this.getHash())) {
                this._urlString = UrlString.canonicalizeUri(url);
            }
        }
        Object.defineProperty(UrlString.prototype, "urlString", {
            get: function () {
                return this._urlString;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Ensure urls are lower case and end with a / character.
         * @param url
         */
        UrlString.canonicalizeUri = function (url) {
            if (url) {
                url = url.toLowerCase();
                if (StringUtils.endsWith(url, "?")) {
                    url = url.slice(0, -1);
                }
                else if (StringUtils.endsWith(url, "?/")) {
                    url = url.slice(0, -2);
                }
                if (!StringUtils.endsWith(url, "/")) {
                    url += "/";
                }
            }
            return url;
        };
        /**
         * Throws if urlString passed is not a valid authority URI string.
         */
        UrlString.prototype.validateAsUri = function () {
            // Attempts to parse url for uri components
            var components;
            try {
                components = this.getUrlComponents();
            }
            catch (e) {
                throw ClientConfigurationError.createUrlParseError(e);
            }
            // Throw error if URI or path segments are not parseable.
            if (!components.HostNameAndPort || !components.PathSegments) {
                throw ClientConfigurationError.createUrlParseError("Given url string: " + this.urlString);
            }
            // Throw error if uri is insecure.
            if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") {
                throw ClientConfigurationError.createInsecureAuthorityUriError(this.urlString);
            }
        };
        /**
         * Function to remove query string params from url. Returns the new url.
         * @param url
         * @param name
         */
        UrlString.prototype.urlRemoveQueryStringParameter = function (name) {
            var regex = new RegExp("(\\&" + name + "=)[^\&]+");
            this._urlString = this.urlString.replace(regex, "");
            // name=value&
            regex = new RegExp("(" + name + "=)[^\&]+&");
            this._urlString = this.urlString.replace(regex, "");
            // name=value
            regex = new RegExp("(" + name + "=)[^\&]+");
            this._urlString = this.urlString.replace(regex, "");
            return this.urlString;
        };
        UrlString.removeHashFromUrl = function (url) {
            return UrlString.canonicalizeUri(url.split("#")[0]);
        };
        /**
         * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
         * @param href The url
         * @param tenantId The tenant id to replace
         */
        UrlString.prototype.replaceTenantPath = function (tenantId) {
            var urlObject = this.getUrlComponents();
            var pathArray = urlObject.PathSegments;
            if (tenantId && (pathArray.length !== 0 && (pathArray[0] === AADAuthorityConstants.COMMON || pathArray[0] === AADAuthorityConstants.ORGANIZATIONS))) {
                pathArray[0] = tenantId;
            }
            return UrlString.constructAuthorityUriFromObject(urlObject);
        };
        /**
         * Returns the anchor part(#) of the URL
         */
        UrlString.prototype.getHash = function () {
            return UrlString.parseHash(this.urlString);
        };
        /**
         * Parses out the components from a url string.
         * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
         */
        UrlString.prototype.getUrlComponents = function () {
            // https://gist.github.com/curtisz/11139b2cfcaef4a261e0
            var regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
            // If url string does not match regEx, we throw an error
            var match = this.urlString.match(regEx);
            if (!match) {
                throw ClientConfigurationError.createUrlParseError("Given url string: " + this.urlString);
            }
            // Url component object
            var urlComponents = {
                Protocol: match[1],
                HostNameAndPort: match[4],
                AbsolutePath: match[5],
                QueryString: match[7]
            };
            var pathSegments = urlComponents.AbsolutePath.split("/");
            pathSegments = pathSegments.filter(function (val) { return val && val.length > 0; }); // remove empty elements
            urlComponents.PathSegments = pathSegments;
            if (!StringUtils.isEmpty(urlComponents.QueryString) && urlComponents.QueryString.endsWith("/")) {
                urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
            }
            return urlComponents;
        };
        UrlString.getDomainFromUrl = function (url) {
            var regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
            var match = url.match(regEx);
            if (!match) {
                throw ClientConfigurationError.createUrlParseError("Given url string: " + url);
            }
            return match[2];
        };
        UrlString.getAbsoluteUrl = function (relativeUrl, baseUrl) {
            if (relativeUrl[0] === Constants.FORWARD_SLASH) {
                var url = new UrlString(baseUrl);
                var baseComponents = url.getUrlComponents();
                return baseComponents.Protocol + "//" + baseComponents.HostNameAndPort + relativeUrl;
            }
            return relativeUrl;
        };
        /**
         * Parses hash string from given string. Returns empty string if no hash symbol is found.
         * @param hashString
         */
        UrlString.parseHash = function (hashString) {
            var hashIndex1 = hashString.indexOf("#");
            var hashIndex2 = hashString.indexOf("#/");
            if (hashIndex2 > -1) {
                return hashString.substring(hashIndex2 + 2);
            }
            else if (hashIndex1 > -1) {
                return hashString.substring(hashIndex1 + 1);
            }
            return "";
        };
        UrlString.constructAuthorityUriFromObject = function (urlObject) {
            return new UrlString(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + urlObject.PathSegments.join("/"));
        };
        /**
         * Returns URL hash as server auth code response object.
         */
        UrlString.getDeserializedHash = function (hash) {
            // Check if given hash is empty
            if (StringUtils.isEmpty(hash)) {
                return {};
            }
            // Strip the # symbol if present
            var parsedHash = UrlString.parseHash(hash);
            // If # symbol was not present, above will return empty string, so give original hash value
            var deserializedHash = StringUtils.queryStringToObject(StringUtils.isEmpty(parsedHash) ? hash : parsedHash);
            // Check if deserialization didn't work
            if (!deserializedHash) {
                throw ClientAuthError.createHashNotDeserializedError(JSON.stringify(deserializedHash));
            }
            return deserializedHash;
        };
        /**
         * Check if the hash of the URL string contains known properties
         */
        UrlString.hashContainsKnownProperties = function (hash) {
            if (StringUtils.isEmpty(hash)) {
                return false;
            }
            var parameters = UrlString.getDeserializedHash(hash);
            return !!(parameters.code ||
                parameters.error_description ||
                parameters.error ||
                parameters.state);
        };
        return UrlString;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var TrustedAuthority = /** @class */ (function () {
        function TrustedAuthority() {
        }
        /**
         * Set the CloudDiscoveryMetadata object from knownAuthorities or cloudDiscoveryMetadata passed into the app config
         * @param knownAuthorities
         * @param cloudDiscoveryMetadata
         */
        TrustedAuthority.setTrustedAuthoritiesFromConfig = function (knownAuthorities, cloudDiscoveryMetadata) {
            if (!this.getTrustedHostList().length) {
                if (knownAuthorities.length > 0 && !StringUtils.isEmpty(cloudDiscoveryMetadata)) {
                    throw ClientConfigurationError.createKnownAuthoritiesCloudDiscoveryMetadataError();
                }
                this.createCloudDiscoveryMetadataFromKnownAuthorities(knownAuthorities);
                try {
                    if (cloudDiscoveryMetadata) {
                        var parsedMetadata = JSON.parse(cloudDiscoveryMetadata);
                        this.saveCloudDiscoveryMetadata(parsedMetadata.metadata);
                    }
                }
                catch (e) {
                    throw ClientConfigurationError.createInvalidCloudDiscoveryMetadataError();
                }
            }
        };
        /**
         * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
         * @param networkInterface
         */
        TrustedAuthority.setTrustedAuthoritiesFromNetwork = function (authorityToVerify, networkInterface) {
            return __awaiter$1(this, void 0, void 0, function () {
                var instanceDiscoveryEndpoint, response, metadata, e_1, host;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            instanceDiscoveryEndpoint = "" + Constants.AAD_INSTANCE_DISCOVERY_ENDPT + authorityToVerify.urlString + "oauth2/v2.0/authorize";
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint)];
                        case 2:
                            response = _a.sent();
                            metadata = response.body.metadata;
                            this.saveCloudDiscoveryMetadata(metadata);
                            return [3 /*break*/, 4];
                        case 3:
                            e_1 = _a.sent();
                            return [2 /*return*/];
                        case 4:
                            host = authorityToVerify.getUrlComponents().HostNameAndPort;
                            if (this.getTrustedHostList().length > 0 && !this.IsInTrustedHostList(host)) {
                                // Custom Domain scenario, host is trusted because Instance Discovery call succeeded 
                                this.createCloudDiscoveryMetadataFromKnownAuthorities([host]);
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        /**
         *
         * @param metadata
         */
        TrustedAuthority.saveCloudDiscoveryMetadata = function (metadata) {
            metadata.forEach(function (entry) {
                var authorities = entry.aliases;
                authorities.forEach(function (authority) {
                    TrustedAuthority.TrustedHostList[authority.toLowerCase()] = entry;
                });
            });
        };
        /**
         * Create a generic metadata object for each host passed to knownAuthorities.
         * This is mostly useful for B2C or ADFS scenarios
         * @param knownAuthorities
         */
        TrustedAuthority.createCloudDiscoveryMetadataFromKnownAuthorities = function (knownAuthorities) {
            var _this = this;
            knownAuthorities.forEach(function (authority) {
                var authorityDomain = UrlString.getDomainFromUrl(authority).toLowerCase();
                _this.TrustedHostList[authorityDomain] = {
                    preferred_cache: authorityDomain,
                    preferred_network: authorityDomain,
                    aliases: [authorityDomain]
                };
            });
        };
        TrustedAuthority.getTrustedHostList = function () {
            return Object.keys(this.TrustedHostList);
        };
        /**
         * Get metadata for the provided host
         * @param host
         */
        TrustedAuthority.getCloudDiscoveryMetadata = function (host) {
            return this.TrustedHostList[host.toLowerCase()] || null;
        };
        /**
         * Checks to see if the host is in a list of trusted hosts
         * @param host
         */
        TrustedAuthority.IsInTrustedHostList = function (host) {
            return Object.keys(this.TrustedHostList).indexOf(host.toLowerCase()) > -1;
        };
        TrustedAuthority.TrustedHostList = {};
        return TrustedAuthority;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Protocol modes supported by MSAL.
     */

    (function (ProtocolMode) {
        ProtocolMode["AAD"] = "AAD";
        ProtocolMode["OIDC"] = "OIDC";
    })(exports.ProtocolMode || (exports.ProtocolMode = {}));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
     * endpoint. It will store the pertinent config data in this object for use during token calls.
     */
    var Authority = /** @class */ (function () {
        function Authority(authority, networkInterface, protocolMode) {
            this.canonicalAuthority = authority;
            this._canonicalAuthority.validateAsUri();
            this.networkInterface = networkInterface;
            this.authorityProtocolMode = protocolMode;
        }
        Object.defineProperty(Authority.prototype, "authorityType", {
            // See above for AuthorityType
            get: function () {
                var pathSegments = this.canonicalAuthorityUrlComponents.PathSegments;
                if (pathSegments.length && pathSegments[0].toLowerCase() === Constants.ADFS) {
                    return AuthorityType.Adfs;
                }
                return AuthorityType.Default;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "protocolMode", {
            /**
             * ProtocolMode enum representing the way endpoints are constructed.
             */
            get: function () {
                return this.authorityProtocolMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "canonicalAuthority", {
            /**
             * A URL that is the authority set by the developer
             */
            get: function () {
                return this._canonicalAuthority.urlString;
            },
            /**
             * Sets canonical authority.
             */
            set: function (url) {
                this._canonicalAuthority = new UrlString(url);
                this._canonicalAuthority.validateAsUri();
                this._canonicalAuthorityUrlComponents = null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "canonicalAuthorityUrlComponents", {
            /**
             * Get authority components.
             */
            get: function () {
                if (!this._canonicalAuthorityUrlComponents) {
                    this._canonicalAuthorityUrlComponents = this._canonicalAuthority.getUrlComponents();
                }
                return this._canonicalAuthorityUrlComponents;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "tenant", {
            /**
             * Get tenant for authority.
             */
            get: function () {
                return this.canonicalAuthorityUrlComponents.PathSegments[0];
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "authorizationEndpoint", {
            /**
             * OAuth /authorize endpoint for requests
             */
            get: function () {
                if (this.discoveryComplete()) {
                    return this.replaceTenant(this.tenantDiscoveryResponse.authorization_endpoint);
                }
                else {
                    throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "tokenEndpoint", {
            /**
             * OAuth /token endpoint for requests
             */
            get: function () {
                if (this.discoveryComplete()) {
                    return this.replaceTenant(this.tenantDiscoveryResponse.token_endpoint);
                }
                else {
                    throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "deviceCodeEndpoint", {
            get: function () {
                if (this.discoveryComplete()) {
                    return this.tenantDiscoveryResponse.token_endpoint.replace("/token", "/devicecode");
                }
                else {
                    throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "endSessionEndpoint", {
            /**
             * OAuth logout endpoint for requests
             */
            get: function () {
                if (this.discoveryComplete()) {
                    return this.replaceTenant(this.tenantDiscoveryResponse.end_session_endpoint);
                }
                else {
                    throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Authority.prototype, "selfSignedJwtAudience", {
            /**
             * OAuth issuer for requests
             */
            get: function () {
                if (this.discoveryComplete()) {
                    return this.replaceTenant(this.tenantDiscoveryResponse.issuer);
                }
                else {
                    throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Replaces tenant in url path with current tenant. Defaults to common.
         * @param urlString
         */
        Authority.prototype.replaceTenant = function (urlString) {
            return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
        };
        Object.defineProperty(Authority.prototype, "defaultOpenIdConfigurationEndpoint", {
            /**
             * The default open id configuration endpoint for any canonical authority.
             */
            get: function () {
                if (this.authorityType === AuthorityType.Adfs || this.protocolMode === exports.ProtocolMode.OIDC) {
                    return this.canonicalAuthority + ".well-known/openid-configuration";
                }
                return this.canonicalAuthority + "v2.0/.well-known/openid-configuration";
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Boolean that returns whethr or not tenant discovery has been completed.
         */
        Authority.prototype.discoveryComplete = function () {
            return !!this.tenantDiscoveryResponse;
        };
        /**
         * Gets OAuth endpoints from the given OpenID configuration endpoint.
         * @param openIdConfigurationEndpoint
         */
        Authority.prototype.discoverEndpoints = function (openIdConfigurationEndpoint) {
            return __awaiter$1(this, void 0, void 0, function () {
                return __generator$1(this, function (_a) {
                    return [2 /*return*/, this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint)];
                });
            });
        };
        /**
         * Set the trusted hosts and validate subsequent calls
         */
        Authority.prototype.validateAndSetPreferredNetwork = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var host, preferredNetwork;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            host = this.canonicalAuthorityUrlComponents.HostNameAndPort;
                            if (!(TrustedAuthority.getTrustedHostList().length === 0)) return [3 /*break*/, 2];
                            return [4 /*yield*/, TrustedAuthority.setTrustedAuthoritiesFromNetwork(this._canonicalAuthority, this.networkInterface)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            if (!TrustedAuthority.IsInTrustedHostList(host)) {
                                throw ClientConfigurationError.createUntrustedAuthorityError();
                            }
                            preferredNetwork = TrustedAuthority.getCloudDiscoveryMetadata(host).preferred_network;
                            if (host !== preferredNetwork) {
                                this.canonicalAuthority = this.canonicalAuthority.replace(host, preferredNetwork);
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Perform endpoint discovery to discover the /authorize, /token and logout endpoints.
         */
        Authority.prototype.resolveEndpointsAsync = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var openIdConfigEndpoint, response;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.validateAndSetPreferredNetwork()];
                        case 1:
                            _a.sent();
                            openIdConfigEndpoint = this.defaultOpenIdConfigurationEndpoint;
                            return [4 /*yield*/, this.discoverEndpoints(openIdConfigEndpoint)];
                        case 2:
                            response = _a.sent();
                            this.tenantDiscoveryResponse = response.body;
                            return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Determine if given hostname is alias of this authority
         * @param host
         */
        Authority.prototype.isAuthorityAlias = function (host) {
            if (host === this.canonicalAuthorityUrlComponents.HostNameAndPort) {
                return true;
            }
            var aliases = TrustedAuthority.getCloudDiscoveryMetadata(this.canonicalAuthorityUrlComponents.HostNameAndPort).aliases;
            return aliases.indexOf(host) !== -1;
        };
        /**
         * helper function to generate environment from authority object
         * @param authority
         */
        Authority.generateEnvironmentFromAuthority = function (authority) {
            var reqEnvironment = authority.canonicalAuthorityUrlComponents.HostNameAndPort;
            return TrustedAuthority.getCloudDiscoveryMetadata(reqEnvironment) ? TrustedAuthority.getCloudDiscoveryMetadata(reqEnvironment).preferred_cache : "";
        };
        return Authority;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Function to build a client info object
     * @param rawClientInfo
     * @param crypto
     */
    function buildClientInfo(rawClientInfo, crypto) {
        if (StringUtils.isEmpty(rawClientInfo)) {
            throw ClientAuthError.createClientInfoEmptyError();
        }
        try {
            var decodedClientInfo = crypto.base64Decode(rawClientInfo);
            return JSON.parse(decodedClientInfo);
        }
        catch (e) {
            throw ClientAuthError.createClientInfoDecodingError(e);
        }
    }

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Type that defines required and optional parameters for an Account field (based on universal cache schema implemented by all MSALs).
     *
     * Key : Value Schema
     *
     * Key: <home_account_id>-<environment>-<realm*>
     *
     * Value Schema:
     * {
     *      homeAccountId: home account identifier for the auth scheme,
     *      environment: entity that issued the token, represented as a full host
     *      realm: Full tenant or organizational identifier that the account belongs to
     *      localAccountId: Original tenant-specific accountID, usually used for legacy cases
     *      username: primary username that represents the user, usually corresponds to preferred_username in the v2 endpt
     *      authorityType: Accounts authority type as a string
     *      name: Full name for the account, including given name and family name,
     *      clientInfo: Full base64 encoded client info received from ESTS
     *      lastModificationTime: last time this entity was modified in the cache
     *      lastModificationApp:
     *      oboAssertion: access token passed in as part of OBO request
     *      idTokenClaims: Object containing claims parsed from ID token
     * }
     */
    var AccountEntity = /** @class */ (function () {
        function AccountEntity() {
        }
        /**
         * Generate Account Id key component as per the schema: <home_account_id>-<environment>
         */
        AccountEntity.prototype.generateAccountId = function () {
            var accountId = [this.homeAccountId, this.environment];
            return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * Generate Account Cache Key as per the schema: <home_account_id>-<environment>-<realm*>
         */
        AccountEntity.prototype.generateAccountKey = function () {
            return AccountEntity.generateAccountCacheKey({
                homeAccountId: this.homeAccountId,
                environment: this.environment,
                tenantId: this.realm,
                username: this.username,
                localAccountId: this.localAccountId
            });
        };
        /**
         * returns the type of the cache (in this case account)
         */
        AccountEntity.prototype.generateType = function () {
            switch (this.authorityType) {
                case CacheAccountType.ADFS_ACCOUNT_TYPE:
                    return CacheType.ADFS;
                case CacheAccountType.MSAV1_ACCOUNT_TYPE:
                    return CacheType.MSA;
                case CacheAccountType.MSSTS_ACCOUNT_TYPE:
                    return CacheType.MSSTS;
                case CacheAccountType.GENERIC_ACCOUNT_TYPE:
                    return CacheType.GENERIC;
                default: {
                    throw ClientAuthError.createUnexpectedAccountTypeError();
                }
            }
        };
        /**
         * Returns the AccountInfo interface for this account.
         */
        AccountEntity.prototype.getAccountInfo = function () {
            return {
                homeAccountId: this.homeAccountId,
                environment: this.environment,
                tenantId: this.realm,
                username: this.username,
                localAccountId: this.localAccountId,
                name: this.name,
                idTokenClaims: this.idTokenClaims
            };
        };
        /**
         * Generates account key from interface
         * @param accountInterface
         */
        AccountEntity.generateAccountCacheKey = function (accountInterface) {
            var accountKey = [
                accountInterface.homeAccountId,
                accountInterface.environment || "",
                accountInterface.tenantId || "",
            ];
            return accountKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
         * @param clientInfo
         * @param authority
         * @param idToken
         * @param policy
         */
        AccountEntity.createAccount = function (clientInfo, homeAccountId, authority, idToken, oboAssertion, cloudGraphHostName, msGraphHost) {
            var _a, _b, _c, _d, _e, _f;
            var account = new AccountEntity();
            account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE;
            account.clientInfo = clientInfo;
            account.homeAccountId = homeAccountId;
            var env = Authority.generateEnvironmentFromAuthority(authority);
            if (StringUtils.isEmpty(env)) {
                throw ClientAuthError.createInvalidCacheEnvironmentError();
            }
            account.environment = env;
            // non AAD scenarios can have empty realm
            account.realm = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.tid) || "";
            account.oboAssertion = oboAssertion;
            if (idToken) {
                account.idTokenClaims = idToken.claims;
                // How do you account for MSA CID here?
                account.localAccountId = ((_b = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _b === void 0 ? void 0 : _b.oid) || ((_c = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _c === void 0 ? void 0 : _c.sub) || "";
                /*
                 * In B2C scenarios the emails claim is used instead of preferred_username and it is an array. In most cases it will contain a single email.
                 * This field should not be relied upon if a custom policy is configured to return more than 1 email.
                 */
                account.username = ((_d = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _d === void 0 ? void 0 : _d.preferred_username) || (((_e = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _e === void 0 ? void 0 : _e.emails) ? idToken.claims.emails[0] : "");
                account.name = (_f = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _f === void 0 ? void 0 : _f.name;
            }
            account.cloudGraphHostName = cloudGraphHostName;
            account.msGraphHost = msGraphHost;
            return account;
        };
        /**
         * Builds non-AAD/ADFS account.
         * @param authority
         * @param idToken
         */
        AccountEntity.createGenericAccount = function (authority, homeAccountId, idToken, oboAssertion, cloudGraphHostName, msGraphHost) {
            var _a, _b, _c, _d;
            var account = new AccountEntity();
            account.authorityType = (authority.authorityType === AuthorityType.Adfs) ? CacheAccountType.ADFS_ACCOUNT_TYPE : CacheAccountType.GENERIC_ACCOUNT_TYPE;
            account.homeAccountId = homeAccountId;
            // non AAD scenarios can have empty realm
            account.realm = "";
            account.oboAssertion = oboAssertion;
            var env = Authority.generateEnvironmentFromAuthority(authority);
            if (StringUtils.isEmpty(env)) {
                throw ClientAuthError.createInvalidCacheEnvironmentError();
            }
            if (idToken) {
                // How do you account for MSA CID here?
                account.localAccountId = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.oid) || ((_b = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _b === void 0 ? void 0 : _b.sub) || "";
                // upn claim for most ADFS scenarios
                account.username = ((_c = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _c === void 0 ? void 0 : _c.upn) || "";
                account.name = ((_d = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _d === void 0 ? void 0 : _d.name) || "";
                account.idTokenClaims = idToken === null || idToken === void 0 ? void 0 : idToken.claims;
            }
            account.environment = env;
            account.cloudGraphHostName = cloudGraphHostName;
            account.msGraphHost = msGraphHost;
            /*
             * add uniqueName to claims
             * account.name = idToken.claims.uniqueName;
             */
            return account;
        };
        /**
         * Generate HomeAccountId from server response
         * @param serverClientInfo
         * @param authType
         */
        AccountEntity.generateHomeAccountId = function (serverClientInfo, authType, logger, cryptoObj, idToken) {
            var _a;
            var accountId = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.sub) ? idToken.claims.sub : Constants.EMPTY_STRING;
            // since ADFS does not have tid and does not set client_info
            if (authType === AuthorityType.Adfs) {
                return accountId;
            }
            // for cases where there is clientInfo
            if (serverClientInfo) {
                var clientInfo = buildClientInfo(serverClientInfo, cryptoObj);
                if (!StringUtils.isEmpty(clientInfo.uid) && !StringUtils.isEmpty(clientInfo.utid)) {
                    return "" + clientInfo.uid + Separators.CLIENT_INFO_SEPARATOR + clientInfo.utid;
                }
            }
            // default to "sub" claim
            logger.verbose("No client info in response");
            return accountId;
        };
        /**
         * Validates an entity: checks for all expected params
         * @param entity
         */
        AccountEntity.isAccountEntity = function (entity) {
            if (!entity) {
                return false;
            }
            return (entity.hasOwnProperty("homeAccountId") &&
                entity.hasOwnProperty("environment") &&
                entity.hasOwnProperty("realm") &&
                entity.hasOwnProperty("localAccountId") &&
                entity.hasOwnProperty("username") &&
                entity.hasOwnProperty("authorityType"));
        };
        return AccountEntity;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * JWT Token representation class. Parses token string and generates claims object.
     */
    var AuthToken = /** @class */ (function () {
        function AuthToken(rawToken, crypto) {
            if (StringUtils.isEmpty(rawToken)) {
                throw ClientAuthError.createTokenNullOrEmptyError(rawToken);
            }
            this.rawToken = rawToken;
            this.claims = AuthToken.extractTokenClaims(rawToken, crypto);
        }
        /**
         * Extract token by decoding the rawToken
         *
         * @param encodedToken
         */
        AuthToken.extractTokenClaims = function (encodedToken, crypto) {
            var decodedToken = StringUtils.decodeAuthToken(encodedToken);
            // token will be decoded to get the username
            try {
                var base64TokenPayload = decodedToken.JWSPayload;
                // base64Decode() should throw an error if there is an issue
                var base64Decoded = crypto.base64Decode(base64TokenPayload);
                return JSON.parse(base64Decoded);
            }
            catch (err) {
                throw ClientAuthError.createTokenParsingError(err);
            }
        };
        return AuthToken;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens.
     */
    var CacheManager = /** @class */ (function () {
        function CacheManager(clientId, cryptoImpl) {
            this.clientId = clientId;
            this.cryptoImpl = cryptoImpl;
        }
        /**
         * Returns all accounts in cache
         */
        CacheManager.prototype.getAllAccounts = function () {
            var _this = this;
            var currentAccounts = this.getAccountsFilteredBy();
            var accountValues = Object.keys(currentAccounts).map(function (accountKey) { return currentAccounts[accountKey]; });
            var numAccounts = accountValues.length;
            if (numAccounts < 1) {
                return [];
            }
            else {
                var allAccounts = accountValues.map(function (value) {
                    var accountEntity = CacheManager.toObject(new AccountEntity(), value);
                    var accountInfo = accountEntity.getAccountInfo();
                    var idToken = _this.readIdTokenFromCache(_this.clientId, accountInfo);
                    if (idToken && !accountInfo.idTokenClaims) {
                        accountInfo.idTokenClaims = new AuthToken(idToken.secret, _this.cryptoImpl).claims;
                    }
                    return accountInfo;
                });
                return allAccounts;
            }
        };
        /**
         * saves a cache record
         * @param cacheRecord
         */
        CacheManager.prototype.saveCacheRecord = function (cacheRecord) {
            if (!cacheRecord) {
                throw ClientAuthError.createNullOrUndefinedCacheRecord();
            }
            if (!!cacheRecord.account) {
                this.setAccount(cacheRecord.account);
            }
            if (!!cacheRecord.idToken) {
                this.setIdTokenCredential(cacheRecord.idToken);
            }
            if (!!cacheRecord.accessToken) {
                this.saveAccessToken(cacheRecord.accessToken);
            }
            if (!!cacheRecord.refreshToken) {
                this.setRefreshTokenCredential(cacheRecord.refreshToken);
            }
            if (!!cacheRecord.appMetadata) {
                this.setAppMetadata(cacheRecord.appMetadata);
            }
        };
        /**
         * saves access token credential
         * @param credential
         */
        CacheManager.prototype.saveAccessToken = function (credential) {
            var _this = this;
            var currentTokenCache = this.getCredentialsFilteredBy({
                clientId: credential.clientId,
                credentialType: CredentialType.ACCESS_TOKEN,
                environment: credential.environment,
                homeAccountId: credential.homeAccountId,
                realm: credential.realm,
            });
            var currentScopes = ScopeSet.fromString(credential.target);
            var currentAccessTokens = Object.keys(currentTokenCache.accessTokens).map(function (key) { return currentTokenCache.accessTokens[key]; });
            if (currentAccessTokens) {
                currentAccessTokens.forEach(function (tokenEntity) {
                    var tokenScopeSet = ScopeSet.fromString(tokenEntity.target);
                    if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
                        _this.removeCredential(tokenEntity);
                    }
                });
            }
            this.setAccessTokenCredential(credential);
        };
        /**
         * retrieve accounts matching all provided filters; if no filter is set, get all accounts
         * not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
         * @param homeAccountId
         * @param environment
         * @param realm
         */
        CacheManager.prototype.getAccountsFilteredBy = function (accountFilter) {
            return this.getAccountsFilteredByInternal(accountFilter ? accountFilter.homeAccountId : "", accountFilter ? accountFilter.environment : "", accountFilter ? accountFilter.realm : "");
        };
        /**
         * retrieve accounts matching all provided filters; if no filter is set, get all accounts
         * not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
         * @param homeAccountId
         * @param environment
         * @param realm
         */
        CacheManager.prototype.getAccountsFilteredByInternal = function (homeAccountId, environment, realm) {
            var _this = this;
            var allCacheKeys = this.getKeys();
            var matchingAccounts = {};
            allCacheKeys.forEach(function (cacheKey) {
                var entity = _this.getAccount(cacheKey);
                if (!entity) {
                    return;
                }
                if (!!homeAccountId && !_this.matchHomeAccountId(entity, homeAccountId)) {
                    return;
                }
                if (!!environment && !_this.matchEnvironment(entity, environment)) {
                    return;
                }
                if (!!realm && !_this.matchRealm(entity, realm)) {
                    return;
                }
                matchingAccounts[cacheKey] = entity;
            });
            return matchingAccounts;
        };
        /**
         * retrieve credentails matching all provided filters; if no filter is set, get all credentials
         * @param homeAccountId
         * @param environment
         * @param credentialType
         * @param clientId
         * @param realm
         * @param target
         */
        CacheManager.prototype.getCredentialsFilteredBy = function (filter) {
            return this.getCredentialsFilteredByInternal(filter.homeAccountId, filter.environment, filter.credentialType, filter.clientId, filter.familyId, filter.realm, filter.target, filter.oboAssertion);
        };
        /**
         * Support function to help match credentials
         * @param homeAccountId
         * @param environment
         * @param credentialType
         * @param clientId
         * @param realm
         * @param target
         */
        CacheManager.prototype.getCredentialsFilteredByInternal = function (homeAccountId, environment, credentialType, clientId, familyId, realm, target, oboAssertion) {
            var _this = this;
            var allCacheKeys = this.getKeys();
            var matchingCredentials = {
                idTokens: {},
                accessTokens: {},
                refreshTokens: {},
            };
            allCacheKeys.forEach(function (cacheKey) {
                // don't parse any non-credential type cache entities
                var credType = CredentialEntity.getCredentialType(cacheKey);
                if (credType === Constants.NOT_DEFINED) {
                    return;
                }
                // Attempt retrieval
                var entity = _this.getSpecificCredential(cacheKey, credType);
                if (!entity) {
                    return;
                }
                if (!!oboAssertion && !_this.matchOboAssertion(entity, oboAssertion)) {
                    return;
                }
                if (!!homeAccountId && !_this.matchHomeAccountId(entity, homeAccountId)) {
                    return;
                }
                if (!!environment && !_this.matchEnvironment(entity, environment)) {
                    return;
                }
                if (!!realm && !_this.matchRealm(entity, realm)) {
                    return;
                }
                if (!!credentialType && !_this.matchCredentialType(entity, credentialType)) {
                    return;
                }
                if (!!clientId && !_this.matchClientId(entity, clientId)) {
                    return;
                }
                if (!!familyId && !_this.matchFamilyId(entity, familyId)) {
                    return;
                }
                /*
                 * idTokens do not have "target", target specific refreshTokens do exist for some types of authentication
                 * Resource specific refresh tokens case will be added when the support is deemed necessary
                 */
                if (!!target && !_this.matchTarget(entity, target)) {
                    return;
                }
                switch (credType) {
                    case CredentialType.ID_TOKEN:
                        matchingCredentials.idTokens[cacheKey] = entity;
                        break;
                    case CredentialType.ACCESS_TOKEN:
                        matchingCredentials.accessTokens[cacheKey] = entity;
                        break;
                    case CredentialType.REFRESH_TOKEN:
                        matchingCredentials.refreshTokens[cacheKey] = entity;
                        break;
                }
            });
            return matchingCredentials;
        };
        /**
         * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata
         * @param filter
         */
        CacheManager.prototype.getAppMetadataFilteredBy = function (filter) {
            return this.getAppMetadataFilteredByInternal(filter.environment, filter.clientId);
        };
        /**
         * Support function to help match appMetadata
         * @param environment
         * @param clientId
         */
        CacheManager.prototype.getAppMetadataFilteredByInternal = function (environment, clientId) {
            var _this = this;
            var allCacheKeys = this.getKeys();
            var matchingAppMetadata = {};
            allCacheKeys.forEach(function (cacheKey) {
                // don't parse any non-appMetadata type cache entities
                if (!_this.isAppMetadata(cacheKey)) {
                    return;
                }
                // Attempt retrieval
                var entity = _this.getAppMetadata(cacheKey);
                if (!entity) {
                    return;
                }
                if (!!environment && !_this.matchEnvironment(entity, environment)) {
                    return;
                }
                if (!!clientId && !_this.matchClientId(entity, clientId)) {
                    return;
                }
                matchingAppMetadata[cacheKey] = entity;
            });
            return matchingAppMetadata;
        };
        /**
         * Removes all accounts and related tokens from cache.
         */
        CacheManager.prototype.removeAllAccounts = function () {
            var _this = this;
            var allCacheKeys = this.getKeys();
            allCacheKeys.forEach(function (cacheKey) {
                var entity = _this.getAccount(cacheKey);
                if (!entity) {
                    return;
                }
                _this.removeAccount(cacheKey);
            });
            return true;
        };
        /**
         * returns a boolean if the given account is removed
         * @param account
         */
        CacheManager.prototype.removeAccount = function (accountKey) {
            var account = this.getAccount(accountKey);
            if (!account) {
                throw ClientAuthError.createNoAccountFoundError();
            }
            return (this.removeAccountContext(account) && this.removeItem(accountKey, CacheSchemaType.ACCOUNT));
        };
        /**
         * returns a boolean if the given account is removed
         * @param account
         */
        CacheManager.prototype.removeAccountContext = function (account) {
            var _this = this;
            var allCacheKeys = this.getKeys();
            var accountId = account.generateAccountId();
            allCacheKeys.forEach(function (cacheKey) {
                // don't parse any non-credential type cache entities
                var credType = CredentialEntity.getCredentialType(cacheKey);
                if (credType === Constants.NOT_DEFINED) {
                    return;
                }
                var cacheEntity = _this.getSpecificCredential(cacheKey, credType);
                if (!!cacheEntity && accountId === cacheEntity.generateAccountId()) {
                    _this.removeCredential(cacheEntity);
                }
            });
            return true;
        };
        /**
         * returns a boolean if the given credential is removed
         * @param credential
         */
        CacheManager.prototype.removeCredential = function (credential) {
            var key = credential.generateCredentialKey();
            return this.removeItem(key, CacheSchemaType.CREDENTIAL);
        };
        /**
         * Removes all app metadata objects from cache.
         */
        CacheManager.prototype.removeAppMetadata = function () {
            var _this = this;
            var allCacheKeys = this.getKeys();
            allCacheKeys.forEach(function (cacheKey) {
                if (_this.isAppMetadata(cacheKey)) {
                    _this.removeItem(cacheKey, CacheSchemaType.APP_METADATA);
                }
            });
            return true;
        };
        /**
         * Retrieve the cached credentials into a cacherecord
         * @param account
         * @param clientId
         * @param scopes
         * @param environment
         */
        CacheManager.prototype.readCacheRecord = function (account, clientId, scopes, environment) {
            var cachedAccount = this.readAccountFromCache(account);
            var cachedIdToken = this.readIdTokenFromCache(clientId, account);
            var cachedAccessToken = this.readAccessTokenFromCache(clientId, account, scopes);
            var cachedRefreshToken = this.readRefreshTokenFromCache(clientId, account, false);
            var cachedAppMetadata = this.readAppMetadataFromCache(environment, clientId);
            if (cachedAccount && cachedIdToken) {
                cachedAccount.idTokenClaims = new AuthToken(cachedIdToken.secret, this.cryptoImpl).claims;
            }
            return {
                account: cachedAccount,
                idToken: cachedIdToken,
                accessToken: cachedAccessToken,
                refreshToken: cachedRefreshToken,
                appMetadata: cachedAppMetadata,
            };
        };
        /**
         * Retrieve AccountEntity from cache
         * @param account
         */
        CacheManager.prototype.readAccountFromCache = function (account) {
            var accountKey = AccountEntity.generateAccountCacheKey(account);
            return this.getAccount(accountKey);
        };
        /**
         * Retrieve IdTokenEntity from cache
         * @param clientId
         * @param account
         * @param inputRealm
         */
        CacheManager.prototype.readIdTokenFromCache = function (clientId, account) {
            var idTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: CredentialType.ID_TOKEN,
                clientId: clientId,
                realm: account.tenantId,
            };
            var credentialCache = this.getCredentialsFilteredBy(idTokenFilter);
            var idTokens = Object.keys(credentialCache.idTokens).map(function (key) { return credentialCache.idTokens[key]; });
            var numIdTokens = idTokens.length;
            if (numIdTokens < 1) {
                return null;
            }
            else if (numIdTokens > 1) {
                throw ClientAuthError.createMultipleMatchingTokensInCacheError();
            }
            return idTokens[0];
        };
        /**
         * Retrieve AccessTokenEntity from cache
         * @param clientId
         * @param account
         * @param scopes
         * @param inputRealm
         */
        CacheManager.prototype.readAccessTokenFromCache = function (clientId, account, scopes) {
            var accessTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: CredentialType.ACCESS_TOKEN,
                clientId: clientId,
                realm: account.tenantId,
                target: scopes.printScopesLowerCase(),
            };
            var credentialCache = this.getCredentialsFilteredBy(accessTokenFilter);
            var accessTokens = Object.keys(credentialCache.accessTokens).map(function (key) { return credentialCache.accessTokens[key]; });
            var numAccessTokens = accessTokens.length;
            if (numAccessTokens < 1) {
                return null;
            }
            else if (numAccessTokens > 1) {
                throw ClientAuthError.createMultipleMatchingTokensInCacheError();
            }
            return accessTokens[0];
        };
        /**
         * Helper to retrieve the appropriate refresh token from cache
         * @param clientId
         * @param account
         * @param familyRT
         */
        CacheManager.prototype.readRefreshTokenFromCache = function (clientId, account, familyRT) {
            var id = familyRT ? THE_FAMILY_ID : undefined;
            var refreshTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: CredentialType.REFRESH_TOKEN,
                clientId: clientId,
                familyId: id
            };
            var credentialCache = this.getCredentialsFilteredBy(refreshTokenFilter);
            var refreshTokens = Object.keys(credentialCache.refreshTokens).map(function (key) { return credentialCache.refreshTokens[key]; });
            var numRefreshTokens = refreshTokens.length;
            if (numRefreshTokens < 1) {
                return null;
            }
            // address the else case after remove functions address environment aliases
            return refreshTokens[0];
        };
        /**
         * Retrieve AppMetadataEntity from cache
         */
        CacheManager.prototype.readAppMetadataFromCache = function (environment, clientId) {
            var appMetadataFilter = {
                environment: environment,
                clientId: clientId,
            };
            var appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter);
            var appMetadataEntries = Object.keys(appMetadata).map(function (key) { return appMetadata[key]; });
            var numAppMetadata = appMetadataEntries.length;
            if (numAppMetadata < 1) {
                return null;
            }
            else if (numAppMetadata > 1) {
                throw ClientAuthError.createMultipleMatchingAppMetadataInCacheError();
            }
            return appMetadataEntries[0];
        };
        /**
         * Return the family_id value associated  with FOCI
         * @param environment
         * @param clientId
         */
        CacheManager.prototype.isAppMetadataFOCI = function (environment, clientId) {
            var appMetadata = this.readAppMetadataFromCache(environment, clientId);
            return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
        };
        /**
         * helper to match account ids
         * @param value
         * @param homeAccountId
         */
        CacheManager.prototype.matchHomeAccountId = function (entity, homeAccountId) {
            return !!(entity.homeAccountId && homeAccountId === entity.homeAccountId);
        };
        /**
         * helper to match assertion
         * @param value
         * @param oboAssertion
         */
        CacheManager.prototype.matchOboAssertion = function (entity, oboAssertion) {
            return !!(entity.oboAssertion && oboAssertion === entity.oboAssertion);
        };
        /**
         * helper to match environment
         * @param value
         * @param environment
         */
        CacheManager.prototype.matchEnvironment = function (entity, environment) {
            var cloudMetadata = TrustedAuthority.getCloudDiscoveryMetadata(environment);
            if (cloudMetadata && cloudMetadata.aliases.indexOf(entity.environment) > -1) {
                return true;
            }
            return false;
        };
        /**
         * helper to match credential type
         * @param entity
         * @param credentialType
         */
        CacheManager.prototype.matchCredentialType = function (entity, credentialType) {
            return (entity.credentialType && credentialType.toLowerCase() === entity.credentialType.toLowerCase());
        };
        /**
         * helper to match client ids
         * @param entity
         * @param clientId
         */
        CacheManager.prototype.matchClientId = function (entity, clientId) {
            return !!(entity.clientId && clientId === entity.clientId);
        };
        /**
         * helper to match family ids
         * @param entity
         * @param familyId
         */
        CacheManager.prototype.matchFamilyId = function (entity, familyId) {
            return !!(entity.familyId && familyId === entity.familyId);
        };
        /**
         * helper to match realm
         * @param entity
         * @param realm
         */
        CacheManager.prototype.matchRealm = function (entity, realm) {
            return !!(entity.realm && realm === entity.realm);
        };
        /**
         * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.
         * @param entity
         * @param target
         */
        CacheManager.prototype.matchTarget = function (entity, target) {
            if (entity.credentialType !== CredentialType.ACCESS_TOKEN || !entity.target) {
                return false;
            }
            var entityScopeSet = ScopeSet.fromString(entity.target);
            var requestTargetScopeSet = ScopeSet.fromString(target);
            if (!requestTargetScopeSet.containsOnlyDefaultScopes()) {
                requestTargetScopeSet.removeDefaultScopes(); // ignore default scopes
            }
            return entityScopeSet.containsScopeSet(requestTargetScopeSet);
        };
        /**
         * returns if a given cache entity is of the type appmetadata
         * @param key
         */
        CacheManager.prototype.isAppMetadata = function (key) {
            return key.indexOf(APP_METADATA) !== -1;
        };
        /**
         * Returns the specific credential (IdToken/AccessToken/RefreshToken) from the cache
         * @param key
         * @param credType
         */
        CacheManager.prototype.getSpecificCredential = function (key, credType) {
            switch (credType) {
                case CredentialType.ID_TOKEN: {
                    return this.getIdTokenCredential(key);
                }
                case CredentialType.ACCESS_TOKEN: {
                    return this.getAccessTokenCredential(key);
                }
                case CredentialType.REFRESH_TOKEN: {
                    return this.getRefreshTokenCredential(key);
                }
                default:
                    return null;
            }
        };
        /**
         * Helper to convert serialized data to object
         * @param obj
         * @param json
         */
        CacheManager.toObject = function (obj, json) {
            for (var propertyName in json) {
                obj[propertyName] = json[propertyName];
            }
            return obj;
        };
        return CacheManager;
    }());
    var DefaultStorageClass = /** @class */ (function (_super) {
        __extends$1(DefaultStorageClass, _super);
        function DefaultStorageClass() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        DefaultStorageClass.prototype.setAccount = function () {
            var notImplErr = "Storage interface - setAccount() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getAccount = function () {
            var notImplErr = "Storage interface - getAccount() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setIdTokenCredential = function () {
            var notImplErr = "Storage interface - setIdTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getIdTokenCredential = function () {
            var notImplErr = "Storage interface - getIdTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setAccessTokenCredential = function () {
            var notImplErr = "Storage interface - setAccessTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getAccessTokenCredential = function () {
            var notImplErr = "Storage interface - getAccessTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setRefreshTokenCredential = function () {
            var notImplErr = "Storage interface - setRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getRefreshTokenCredential = function () {
            var notImplErr = "Storage interface - getRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setAppMetadata = function () {
            var notImplErr = "Storage interface - setAppMetadata() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getAppMetadata = function () {
            var notImplErr = "Storage interface - getAppMetadata() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setServerTelemetry = function () {
            var notImplErr = "Storage interface - setServerTelemetry() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getServerTelemetry = function () {
            var notImplErr = "Storage interface - getServerTelemetry() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.setThrottlingCache = function () {
            var notImplErr = "Storage interface - setThrottlingCache() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getThrottlingCache = function () {
            var notImplErr = "Storage interface - getThrottlingCache() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.removeItem = function () {
            var notImplErr = "Storage interface - removeItem() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.containsKey = function () {
            var notImplErr = "Storage interface - containsKey() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.getKeys = function () {
            var notImplErr = "Storage interface - getKeys() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        DefaultStorageClass.prototype.clear = function () {
            var notImplErr = "Storage interface - clear() has not been implemented for the cacheStorage interface.";
            throw AuthError.createUnexpectedError(notImplErr);
        };
        return DefaultStorageClass;
    }(CacheManager));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Token renewal offset default in seconds
    var DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
    var DEFAULT_SYSTEM_OPTIONS = {
        tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC
    };
    var DEFAULT_LOGGER_IMPLEMENTATION = {
        loggerCallback: function () {
            // allow users to not set loggerCallback
        },
        piiLoggingEnabled: false,
        logLevel: exports.LogLevel.Info
    };
    var DEFAULT_NETWORK_IMPLEMENTATION = {
        sendGetRequestAsync: function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var notImplErr;
                return __generator$1(this, function (_a) {
                    notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
                    throw AuthError.createUnexpectedError(notImplErr);
                });
            });
        },
        sendPostRequestAsync: function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var notImplErr;
                return __generator$1(this, function (_a) {
                    notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
                    throw AuthError.createUnexpectedError(notImplErr);
                });
            });
        }
    };
    var DEFAULT_CRYPTO_IMPLEMENTATION = {
        createNewGuid: function () {
            var notImplErr = "Crypto interface - createNewGuid() has not been implemented";
            throw AuthError.createUnexpectedError(notImplErr);
        },
        base64Decode: function () {
            var notImplErr = "Crypto interface - base64Decode() has not been implemented";
            throw AuthError.createUnexpectedError(notImplErr);
        },
        base64Encode: function () {
            var notImplErr = "Crypto interface - base64Encode() has not been implemented";
            throw AuthError.createUnexpectedError(notImplErr);
        },
        generatePkceCodes: function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var notImplErr;
                return __generator$1(this, function (_a) {
                    notImplErr = "Crypto interface - generatePkceCodes() has not been implemented";
                    throw AuthError.createUnexpectedError(notImplErr);
                });
            });
        },
        getPublicKeyThumbprint: function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var notImplErr;
                return __generator$1(this, function (_a) {
                    notImplErr = "Crypto interface - getPublicKeyThumbprint() has not been implemented";
                    throw AuthError.createUnexpectedError(notImplErr);
                });
            });
        },
        signJwt: function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var notImplErr;
                return __generator$1(this, function (_a) {
                    notImplErr = "Crypto interface - signJwt() has not been implemented";
                    throw AuthError.createUnexpectedError(notImplErr);
                });
            });
        }
    };
    var DEFAULT_LIBRARY_INFO = {
        sku: Constants.SKU,
        version: version,
        cpu: "",
        os: ""
    };
    var DEFAULT_CLIENT_CREDENTIALS = {
        clientSecret: "",
        clientAssertion: undefined
    };
    /**
     * Function that sets the default options when not explicitly configured from app developer
     *
     * @param Configuration
     *
     * @returns Configuration
     */
    function buildClientConfiguration(_a) {
        var userAuthOptions = _a.authOptions, userSystemOptions = _a.systemOptions, userLoggerOption = _a.loggerOptions, storageImplementation = _a.storageInterface, networkImplementation = _a.networkInterface, cryptoImplementation = _a.cryptoInterface, clientCredentials = _a.clientCredentials, libraryInfo = _a.libraryInfo, serverTelemetryManager = _a.serverTelemetryManager, persistencePlugin = _a.persistencePlugin, serializableCache = _a.serializableCache;
        return {
            authOptions: buildAuthOptions(userAuthOptions),
            systemOptions: __assign$1(__assign$1({}, DEFAULT_SYSTEM_OPTIONS), userSystemOptions),
            loggerOptions: __assign$1(__assign$1({}, DEFAULT_LOGGER_IMPLEMENTATION), userLoggerOption),
            storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION),
            networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
            cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
            clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
            libraryInfo: __assign$1(__assign$1({}, DEFAULT_LIBRARY_INFO), libraryInfo),
            serverTelemetryManager: serverTelemetryManager || null,
            persistencePlugin: persistencePlugin || null,
            serializableCache: serializableCache || null
        };
    }
    /**
     * Construct authoptions from the client and platform passed values
     * @param authOptions
     */
    function buildAuthOptions(authOptions) {
        return __assign$1({ knownAuthorities: [], cloudDiscoveryMetadata: "", clientCapabilities: [], protocolMode: exports.ProtocolMode.AAD }, authOptions);
    }

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Error thrown when there is an error with the server code, for example, unavailability.
     */
    var ServerError = /** @class */ (function (_super) {
        __extends$1(ServerError, _super);
        function ServerError(errorCode, errorMessage, subError) {
            var _this = _super.call(this, errorCode, errorMessage, subError) || this;
            _this.name = "ServerError";
            Object.setPrototypeOf(_this, ServerError.prototype);
            return _this;
        }
        return ServerError;
    }(AuthError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var ThrottlingUtils = /** @class */ (function () {
        function ThrottlingUtils() {
        }
        /**
         * Prepares a RequestThumbprint to be stored as a key.
         * @param thumbprint
         */
        ThrottlingUtils.generateThrottlingStorageKey = function (thumbprint) {
            return ThrottlingConstants.THROTTLING_PREFIX + "." + JSON.stringify(thumbprint);
        };
        /**
         * Performs necessary throttling checks before a network request.
         * @param cacheManager
         * @param thumbprint
         */
        ThrottlingUtils.preProcess = function (cacheManager, thumbprint) {
            var _a;
            var key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
            var value = cacheManager.getThrottlingCache(key);
            if (value) {
                if (value.throttleTime < Date.now()) {
                    cacheManager.removeItem(key, CacheSchemaType.THROTTLING);
                    return;
                }
                throw new ServerError(((_a = value.errorCodes) === null || _a === void 0 ? void 0 : _a.join(" ")) || Constants.EMPTY_STRING, value.errorMessage, value.subError);
            }
        };
        /**
         * Performs necessary throttling checks after a network request.
         * @param cacheManager
         * @param thumbprint
         * @param response
         */
        ThrottlingUtils.postProcess = function (cacheManager, thumbprint, response) {
            if (ThrottlingUtils.checkResponseStatus(response) || ThrottlingUtils.checkResponseForRetryAfter(response)) {
                var thumbprintValue = {
                    throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),
                    error: response.body.error,
                    errorCodes: response.body.error_codes,
                    errorMessage: response.body.error_description,
                    subError: response.body.suberror
                };
                cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue);
            }
        };
        /**
         * Checks a NetworkResponse object's status codes against 429 or 5xx
         * @param response
         */
        ThrottlingUtils.checkResponseStatus = function (response) {
            return response.status === 429 || response.status >= 500 && response.status < 600;
        };
        /**
         * Checks a NetworkResponse object's RetryAfter header
         * @param response
         */
        ThrottlingUtils.checkResponseForRetryAfter = function (response) {
            if (response.headers) {
                return response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && (response.status < 200 || response.status >= 300);
            }
            return false;
        };
        /**
         * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.
         * @param throttleTime
         */
        ThrottlingUtils.calculateThrottleTime = function (throttleTime) {
            if (throttleTime <= 0) {
                throttleTime = 0;
            }
            var currentSeconds = Date.now() / 1000;
            return Math.floor(Math.min(currentSeconds + (throttleTime || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
        };
        ThrottlingUtils.removeThrottle = function (cacheManager, clientId, authority, scopes, homeAccountIdentifier) {
            var thumbprint = {
                clientId: clientId,
                authority: authority,
                scopes: scopes,
                homeAccountIdentifier: homeAccountIdentifier
            };
            var key = this.generateThrottlingStorageKey(thumbprint);
            return cacheManager.removeItem(key, CacheSchemaType.THROTTLING);
        };
        return ThrottlingUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var NetworkManager = /** @class */ (function () {
        function NetworkManager(networkClient, cacheManager) {
            this.networkClient = networkClient;
            this.cacheManager = cacheManager;
        }
        /**
         * Wraps sendPostRequestAsync with necessary preflight and postflight logic
         * @param thumbprint
         * @param tokenEndpoint
         * @param options
         */
        NetworkManager.prototype.sendPostRequest = function (thumbprint, tokenEndpoint, options) {
            return __awaiter$1(this, void 0, void 0, function () {
                var response;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            ThrottlingUtils.preProcess(this.cacheManager, thumbprint);
                            return [4 /*yield*/, this.networkClient.sendPostRequestAsync(tokenEndpoint, options)];
                        case 1:
                            response = _a.sent();
                            ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);
                            // Placeholder for Telemetry hook
                            return [2 /*return*/, response];
                    }
                });
            });
        };
        return NetworkManager;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow.
     */
    var BaseClient = /** @class */ (function () {
        function BaseClient(configuration) {
            // Set the configuration
            this.config = buildClientConfiguration(configuration);
            // Initialize the logger
            this.logger = new Logger(this.config.loggerOptions, name, version);
            // Initialize crypto
            this.cryptoUtils = this.config.cryptoInterface;
            // Initialize storage interface
            this.cacheManager = this.config.storageInterface;
            // Set the network interface
            this.networkClient = this.config.networkInterface;
            // Set the NetworkManager
            this.networkManager = new NetworkManager(this.networkClient, this.cacheManager);
            // Set TelemetryManager
            this.serverTelemetryManager = this.config.serverTelemetryManager;
            // Set TrustedAuthorities from config
            TrustedAuthority.setTrustedAuthoritiesFromConfig(this.config.authOptions.knownAuthorities, this.config.authOptions.cloudDiscoveryMetadata);
            // set Authority
            this.authority = this.config.authOptions.authority;
        }
        /**
         * Creates default headers for requests to token endpoint
         */
        BaseClient.prototype.createDefaultTokenRequestHeaders = function () {
            var headers = this.createDefaultLibraryHeaders();
            headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;
            headers[HeaderNames.X_MS_LIB_CAPABILITY] = HeaderNames.X_MS_LIB_CAPABILITY_VALUE;
            if (this.serverTelemetryManager) {
                headers[HeaderNames.X_CLIENT_CURR_TELEM] = this.serverTelemetryManager.generateCurrentRequestHeaderValue();
                headers[HeaderNames.X_CLIENT_LAST_TELEM] = this.serverTelemetryManager.generateLastRequestHeaderValue();
            }
            return headers;
        };
        /**
         * addLibraryData
         */
        BaseClient.prototype.createDefaultLibraryHeaders = function () {
            var headers = {};
            // client info headers
            headers[AADServerParamKeys.X_CLIENT_SKU] = this.config.libraryInfo.sku;
            headers[AADServerParamKeys.X_CLIENT_VER] = this.config.libraryInfo.version;
            headers[AADServerParamKeys.X_CLIENT_OS] = this.config.libraryInfo.os;
            headers[AADServerParamKeys.X_CLIENT_CPU] = this.config.libraryInfo.cpu;
            return headers;
        };
        /**
         * Http post to token endpoint
         * @param tokenEndpoint
         * @param queryString
         * @param headers
         * @param thumbprint
         */
        BaseClient.prototype.executePostToTokenEndpoint = function (tokenEndpoint, queryString, headers, thumbprint) {
            return __awaiter$1(this, void 0, void 0, function () {
                var response;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.networkManager.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers })];
                        case 1:
                            response = _a.sent();
                            if (this.config.serverTelemetryManager && response.status < 500 && response.status !== 429) {
                                // Telemetry data successfully logged by server, clear Telemetry cache
                                this.config.serverTelemetryManager.clearTelemetryCache();
                            }
                            return [2 /*return*/, response];
                    }
                });
            });
        };
        /**
         * Updates the authority object of the client. Endpoint discovery must be completed.
         * @param updatedAuthority
         */
        BaseClient.prototype.updateAuthority = function (updatedAuthority) {
            if (!updatedAuthority.discoveryComplete()) {
                throw ClientAuthError.createEndpointDiscoveryIncompleteError("Updated authority has not completed endpoint discovery.");
            }
            this.authority = updatedAuthority;
        };
        return BaseClient;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Validates server consumable params from the "request" objects
     */
    var RequestValidator = /** @class */ (function () {
        function RequestValidator() {
        }
        /**
         * Utility to check if the `redirectUri` in the request is a non-null value
         * @param redirectUri
         */
        RequestValidator.validateRedirectUri = function (redirectUri) {
            if (StringUtils.isEmpty(redirectUri)) {
                throw ClientConfigurationError.createRedirectUriEmptyError();
            }
        };
        /**
         * Utility to validate prompt sent by the user in the request
         * @param prompt
         */
        RequestValidator.validatePrompt = function (prompt) {
            if ([
                PromptValue.LOGIN,
                PromptValue.SELECT_ACCOUNT,
                PromptValue.CONSENT,
                PromptValue.NONE
            ].indexOf(prompt) < 0) {
                throw ClientConfigurationError.createInvalidPromptError(prompt);
            }
        };
        RequestValidator.validateClaims = function (claims) {
            try {
                JSON.parse(claims);
            }
            catch (e) {
                throw ClientConfigurationError.createInvalidClaimsRequestError();
            }
        };
        /**
         * Utility to validate code_challenge and code_challenge_method
         * @param codeChallenge
         * @param codeChallengeMethod
         */
        RequestValidator.validateCodeChallengeParams = function (codeChallenge, codeChallengeMethod) {
            if (StringUtils.isEmpty(codeChallenge) || StringUtils.isEmpty(codeChallengeMethod)) {
                throw ClientConfigurationError.createInvalidCodeChallengeParamsError();
            }
            else {
                this.validateCodeChallengeMethod(codeChallengeMethod);
            }
        };
        /**
         * Utility to validate code_challenge_method
         * @param codeChallengeMethod
         */
        RequestValidator.validateCodeChallengeMethod = function (codeChallengeMethod) {
            if ([
                CodeChallengeMethodValues.PLAIN,
                CodeChallengeMethodValues.S256
            ].indexOf(codeChallengeMethod) < 0) {
                throw ClientConfigurationError.createInvalidCodeChallengeMethodError();
            }
        };
        /**
         * Removes unnecessary or duplicate query parameters from extraQueryParameters
         * @param request
         */
        RequestValidator.sanitizeEQParams = function (eQParams, queryParams) {
            if (!eQParams) {
                return {};
            }
            // Remove any query parameters already included in SSO params
            queryParams.forEach(function (value, key) {
                if (eQParams[key]) {
                    delete eQParams[key];
                }
            });
            return eQParams;
        };
        return RequestValidator;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var RequestParameterBuilder = /** @class */ (function () {
        function RequestParameterBuilder() {
            this.parameters = new Map();
        }
        /**
         * add response_type = code
         */
        RequestParameterBuilder.prototype.addResponseTypeCode = function () {
            this.parameters.set(AADServerParamKeys.RESPONSE_TYPE, encodeURIComponent(Constants.CODE_RESPONSE_TYPE));
        };
        /**
         * add response_mode. defaults to query.
         * @param responseMode
         */
        RequestParameterBuilder.prototype.addResponseMode = function (responseMode) {
            this.parameters.set(AADServerParamKeys.RESPONSE_MODE, encodeURIComponent((responseMode) ? responseMode : ResponseMode.QUERY));
        };
        /**
         * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios
         * @param scopeSet
         * @param addOidcScopes
         */
        RequestParameterBuilder.prototype.addScopes = function (scopes, addOidcScopes) {
            if (addOidcScopes === void 0) { addOidcScopes = true; }
            var requestScopes = addOidcScopes ? __spreadArrays(scopes || [], [Constants.OPENID_SCOPE, Constants.PROFILE_SCOPE]) : scopes || [];
            var scopeSet = new ScopeSet(requestScopes);
            this.parameters.set(AADServerParamKeys.SCOPE, encodeURIComponent(scopeSet.printScopes()));
        };
        /**
         * add clientId
         * @param clientId
         */
        RequestParameterBuilder.prototype.addClientId = function (clientId) {
            this.parameters.set(AADServerParamKeys.CLIENT_ID, encodeURIComponent(clientId));
        };
        /**
         * add redirect_uri
         * @param redirectUri
         */
        RequestParameterBuilder.prototype.addRedirectUri = function (redirectUri) {
            RequestValidator.validateRedirectUri(redirectUri);
            this.parameters.set(AADServerParamKeys.REDIRECT_URI, encodeURIComponent(redirectUri));
        };
        /**
         * add post logout redirectUri
         * @param redirectUri
         */
        RequestParameterBuilder.prototype.addPostLogoutRedirectUri = function (redirectUri) {
            RequestValidator.validateRedirectUri(redirectUri);
            this.parameters.set(AADServerParamKeys.POST_LOGOUT_URI, encodeURIComponent(redirectUri));
        };
        /**
         * add id_token_hint to logout request
         * @param idTokenHint
         */
        RequestParameterBuilder.prototype.addIdTokenHint = function (idTokenHint) {
            this.parameters.set(AADServerParamKeys.ID_TOKEN_HINT, encodeURIComponent(idTokenHint));
        };
        /**
         * add domain_hint
         * @param domainHint
         */
        RequestParameterBuilder.prototype.addDomainHint = function (domainHint) {
            this.parameters.set(SSOTypes.DOMAIN_HINT, encodeURIComponent(domainHint));
        };
        /**
         * add login_hint
         * @param loginHint
         */
        RequestParameterBuilder.prototype.addLoginHint = function (loginHint) {
            this.parameters.set(SSOTypes.LOGIN_HINT, encodeURIComponent(loginHint));
        };
        /**
         * add sid
         * @param sid
         */
        RequestParameterBuilder.prototype.addSid = function (sid) {
            this.parameters.set(SSOTypes.SID, encodeURIComponent(sid));
        };
        /**
         * add claims
         * @param claims
         */
        RequestParameterBuilder.prototype.addClaims = function (claims, clientCapabilities) {
            var mergedClaims = this.addClientCapabilitiesToClaims(claims, clientCapabilities);
            RequestValidator.validateClaims(mergedClaims);
            this.parameters.set(AADServerParamKeys.CLAIMS, encodeURIComponent(mergedClaims));
        };
        /**
         * add correlationId
         * @param correlationId
         */
        RequestParameterBuilder.prototype.addCorrelationId = function (correlationId) {
            this.parameters.set(AADServerParamKeys.CLIENT_REQUEST_ID, encodeURIComponent(correlationId));
        };
        /**
         * add library info query params
         * @param libraryInfo
         */
        RequestParameterBuilder.prototype.addLibraryInfo = function (libraryInfo) {
            // Telemetry Info
            this.parameters.set(AADServerParamKeys.X_CLIENT_SKU, libraryInfo.sku);
            this.parameters.set(AADServerParamKeys.X_CLIENT_VER, libraryInfo.version);
            this.parameters.set(AADServerParamKeys.X_CLIENT_OS, libraryInfo.os);
            this.parameters.set(AADServerParamKeys.X_CLIENT_CPU, libraryInfo.cpu);
        };
        /**
         * add prompt
         * @param prompt
         */
        RequestParameterBuilder.prototype.addPrompt = function (prompt) {
            RequestValidator.validatePrompt(prompt);
            this.parameters.set("" + AADServerParamKeys.PROMPT, encodeURIComponent(prompt));
        };
        /**
         * add state
         * @param state
         */
        RequestParameterBuilder.prototype.addState = function (state) {
            if (!StringUtils.isEmpty(state)) {
                this.parameters.set(AADServerParamKeys.STATE, encodeURIComponent(state));
            }
        };
        /**
         * add nonce
         * @param nonce
         */
        RequestParameterBuilder.prototype.addNonce = function (nonce) {
            this.parameters.set(AADServerParamKeys.NONCE, encodeURIComponent(nonce));
        };
        /**
         * add code_challenge and code_challenge_method
         * - throw if either of them are not passed
         * @param codeChallenge
         * @param codeChallengeMethod
         */
        RequestParameterBuilder.prototype.addCodeChallengeParams = function (codeChallenge, codeChallengeMethod) {
            RequestValidator.validateCodeChallengeParams(codeChallenge, codeChallengeMethod);
            if (codeChallenge && codeChallengeMethod) {
                this.parameters.set(AADServerParamKeys.CODE_CHALLENGE, encodeURIComponent(codeChallenge));
                this.parameters.set(AADServerParamKeys.CODE_CHALLENGE_METHOD, encodeURIComponent(codeChallengeMethod));
            }
            else {
                throw ClientConfigurationError.createInvalidCodeChallengeParamsError();
            }
        };
        /**
         * add the `authorization_code` passed by the user to exchange for a token
         * @param code
         */
        RequestParameterBuilder.prototype.addAuthorizationCode = function (code) {
            this.parameters.set(AADServerParamKeys.CODE, encodeURIComponent(code));
        };
        /**
         * add the `authorization_code` passed by the user to exchange for a token
         * @param code
         */
        RequestParameterBuilder.prototype.addDeviceCode = function (code) {
            this.parameters.set(AADServerParamKeys.DEVICE_CODE, encodeURIComponent(code));
        };
        /**
         * add the `refreshToken` passed by the user
         * @param refreshToken
         */
        RequestParameterBuilder.prototype.addRefreshToken = function (refreshToken) {
            this.parameters.set(AADServerParamKeys.REFRESH_TOKEN, encodeURIComponent(refreshToken));
        };
        /**
         * add the `code_verifier` passed by the user to exchange for a token
         * @param codeVerifier
         */
        RequestParameterBuilder.prototype.addCodeVerifier = function (codeVerifier) {
            this.parameters.set(AADServerParamKeys.CODE_VERIFIER, encodeURIComponent(codeVerifier));
        };
        /**
         * add client_secret
         * @param clientSecret
         */
        RequestParameterBuilder.prototype.addClientSecret = function (clientSecret) {
            this.parameters.set(AADServerParamKeys.CLIENT_SECRET, encodeURIComponent(clientSecret));
        };
        /**
         * add clientAssertion for confidential client flows
         * @param clientAssertion
         */
        RequestParameterBuilder.prototype.addClientAssertion = function (clientAssertion) {
            this.parameters.set(AADServerParamKeys.CLIENT_ASSERTION, encodeURIComponent(clientAssertion));
        };
        /**
         * add clientAssertionType for confidential client flows
         * @param clientAssertionType
         */
        RequestParameterBuilder.prototype.addClientAssertionType = function (clientAssertionType) {
            this.parameters.set(AADServerParamKeys.CLIENT_ASSERTION_TYPE, encodeURIComponent(clientAssertionType));
        };
        /**
         * add OBO assertion for confidential client flows
         * @param clientAssertion
         */
        RequestParameterBuilder.prototype.addOboAssertion = function (oboAssertion) {
            this.parameters.set(AADServerParamKeys.OBO_ASSERTION, encodeURIComponent(oboAssertion));
        };
        /**
         * add grant type
         * @param grantType
         */
        RequestParameterBuilder.prototype.addRequestTokenUse = function (tokenUse) {
            this.parameters.set(AADServerParamKeys.REQUESTED_TOKEN_USE, encodeURIComponent(tokenUse));
        };
        /**
         * add grant type
         * @param grantType
         */
        RequestParameterBuilder.prototype.addGrantType = function (grantType) {
            this.parameters.set(AADServerParamKeys.GRANT_TYPE, encodeURIComponent(grantType));
        };
        /**
         * add client info
         *
         */
        RequestParameterBuilder.prototype.addClientInfo = function () {
            this.parameters.set(ClientInfo, "1");
        };
        /**
         * add extraQueryParams
         * @param eQparams
         */
        RequestParameterBuilder.prototype.addExtraQueryParameters = function (eQparams) {
            var _this = this;
            RequestValidator.sanitizeEQParams(eQparams, this.parameters);
            Object.keys(eQparams).forEach(function (key) {
                _this.parameters.set(key, eQparams[key]);
            });
        };
        RequestParameterBuilder.prototype.addClientCapabilitiesToClaims = function (claims, clientCapabilities) {
            var mergedClaims;
            // Parse provided claims into JSON object or initialize empty object
            if (!claims) {
                mergedClaims = {};
            }
            else {
                try {
                    mergedClaims = JSON.parse(claims);
                }
                catch (e) {
                    throw ClientConfigurationError.createInvalidClaimsRequestError();
                }
            }
            if (clientCapabilities && clientCapabilities.length > 0) {
                if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) {
                    // Add access_token key to claims object
                    mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};
                }
                // Add xms_cc claim with provided clientCapabilities to access_token key
                mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = {
                    values: clientCapabilities
                };
            }
            return JSON.stringify(mergedClaims);
        };
        /**
         * adds `username` for Password Grant flow
         * @param username
         */
        RequestParameterBuilder.prototype.addUsername = function (username) {
            this.parameters.set(PasswordGrantConstants.username, username);
        };
        /**
         * adds `password` for Password Grant flow
         * @param password
         */
        RequestParameterBuilder.prototype.addPassword = function (password) {
            this.parameters.set(PasswordGrantConstants.password, password);
        };
        /**
         * add pop_jwk to query params
         * @param cnfString
         */
        RequestParameterBuilder.prototype.addPopToken = function (cnfString) {
            if (!StringUtils.isEmpty(cnfString)) {
                this.parameters.set(AADServerParamKeys.TOKEN_TYPE, exports.AuthenticationScheme.POP);
                this.parameters.set(AADServerParamKeys.REQ_CNF, encodeURIComponent(cnfString));
            }
        };
        /**
         * Utility to create a URL from the params map
         */
        RequestParameterBuilder.prototype.createQueryString = function () {
            var queryParameterArray = new Array();
            this.parameters.forEach(function (value, key) {
                queryParameterArray.push(key + "=" + value);
            });
            return queryParameterArray.join("&");
        };
        return RequestParameterBuilder;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility class which exposes functions for managing date and time operations.
     */
    var TimeUtils = /** @class */ (function () {
        function TimeUtils() {
        }
        /**
         * return the current time in Unix time (seconds).
         */
        TimeUtils.nowSeconds = function () {
            // Date.getTime() returns in milliseconds.
            return Math.round(new Date().getTime() / 1000.0);
        };
        /**
         * check if a token is expired based on given UTC time in seconds.
         * @param expiresOn
         */
        TimeUtils.isTokenExpired = function (expiresOn, offset) {
            // check for access token expiry
            var expirationSec = Number(expiresOn) || 0;
            var offsetCurrentTimeSec = TimeUtils.nowSeconds() + offset;
            // If current time + offset is greater than token expiration time, then token is expired.
            return (offsetCurrentTimeSec > expirationSec);
        };
        return TimeUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * ID_TOKEN Cache
     *
     * Key:Value Schema:
     *
     * Key Example: uid.utid-login.microsoftonline.com-idtoken-clientId-contoso.com-
     *
     * Value Schema:
     * {
     *      homeAccountId: home account identifier for the auth scheme,
     *      environment: entity that issued the token, represented as a full host
     *      credentialType: Type of credential as a string, can be one of the following: RefreshToken, AccessToken, IdToken, Password, Cookie, Certificate, Other
     *      clientId: client ID of the application
     *      secret: Actual credential as a string
     *      realm: Full tenant or organizational identifier that the account belongs to
     * }
     */
    var IdTokenEntity = /** @class */ (function (_super) {
        __extends$1(IdTokenEntity, _super);
        function IdTokenEntity() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Create IdTokenEntity
         * @param homeAccountId
         * @param authenticationResult
         * @param clientId
         * @param authority
         */
        IdTokenEntity.createIdTokenEntity = function (homeAccountId, environment, idToken, clientId, tenantId, oboAssertion) {
            var idTokenEntity = new IdTokenEntity();
            idTokenEntity.credentialType = CredentialType.ID_TOKEN;
            idTokenEntity.homeAccountId = homeAccountId;
            idTokenEntity.environment = environment;
            idTokenEntity.clientId = clientId;
            idTokenEntity.secret = idToken;
            idTokenEntity.realm = tenantId;
            idTokenEntity.oboAssertion = oboAssertion;
            return idTokenEntity;
        };
        /**
         * Validates an entity: checks for all expected params
         * @param entity
         */
        IdTokenEntity.isIdTokenEntity = function (entity) {
            if (!entity) {
                return false;
            }
            return (entity.hasOwnProperty("homeAccountId") &&
                entity.hasOwnProperty("environment") &&
                entity.hasOwnProperty("credentialType") &&
                entity.hasOwnProperty("realm") &&
                entity.hasOwnProperty("clientId") &&
                entity.hasOwnProperty("secret") &&
                entity["credentialType"] === CredentialType.ID_TOKEN);
        };
        return IdTokenEntity;
    }(CredentialEntity));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * ACCESS_TOKEN Credential Type
     *
     * Key:Value Schema:
     *
     * Key Example: uid.utid-login.microsoftonline.com-accesstoken-clientId-contoso.com-user.read
     *
     * Value Schema:
     * {
     *      homeAccountId: home account identifier for the auth scheme,
     *      environment: entity that issued the token, represented as a full host
     *      credentialType: Type of credential as a string, can be one of the following: RefreshToken, AccessToken, IdToken, Password, Cookie, Certificate, Other
     *      clientId: client ID of the application
     *      secret: Actual credential as a string
     *      familyId: Family ID identifier, usually only used for refresh tokens
     *      realm: Full tenant or organizational identifier that the account belongs to
     *      target: Permissions that are included in the token, or for refresh tokens, the resource identifier.
     *      cachedAt: Absolute device time when entry was created in the cache.
     *      expiresOn: Token expiry time, calculated based on current UTC time in seconds. Represented as a string.
     *      extendedExpiresOn: Additional extended expiry time until when token is valid in case of server-side outage. Represented as string in UTC seconds.
     *      keyId: used for POP and SSH tokenTypes
     *      tokenType: Type of the token issued. Usually "Bearer"
     * }
     */
    var AccessTokenEntity = /** @class */ (function (_super) {
        __extends$1(AccessTokenEntity, _super);
        function AccessTokenEntity() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Create AccessTokenEntity
         * @param homeAccountId
         * @param environment
         * @param accessToken
         * @param clientId
         * @param tenantId
         * @param scopes
         * @param expiresOn
         * @param extExpiresOn
         */
        AccessTokenEntity.createAccessTokenEntity = function (homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, tokenType, oboAssertion) {
            var atEntity = new AccessTokenEntity();
            atEntity.homeAccountId = homeAccountId;
            atEntity.credentialType = CredentialType.ACCESS_TOKEN;
            atEntity.secret = accessToken;
            var currentTime = TimeUtils.nowSeconds();
            atEntity.cachedAt = currentTime.toString();
            /*
             * Token expiry time.
             * This value should be â€¯calculated based on the current UTC time measured locally and the value â€¯expires_in Represented as a string in JSON.
             */
            atEntity.expiresOn = expiresOn.toString();
            atEntity.extendedExpiresOn = extExpiresOn.toString();
            atEntity.environment = environment;
            atEntity.clientId = clientId;
            atEntity.realm = tenantId;
            atEntity.target = scopes;
            atEntity.oboAssertion = oboAssertion;
            atEntity.tokenType = StringUtils.isEmpty(tokenType) ? exports.AuthenticationScheme.BEARER : tokenType;
            return atEntity;
        };
        /**
         * Validates an entity: checks for all expected params
         * @param entity
         */
        AccessTokenEntity.isAccessTokenEntity = function (entity) {
            if (!entity) {
                return false;
            }
            return (entity.hasOwnProperty("homeAccountId") &&
                entity.hasOwnProperty("environment") &&
                entity.hasOwnProperty("credentialType") &&
                entity.hasOwnProperty("realm") &&
                entity.hasOwnProperty("clientId") &&
                entity.hasOwnProperty("secret") &&
                entity.hasOwnProperty("target") &&
                entity["credentialType"] === CredentialType.ACCESS_TOKEN);
        };
        return AccessTokenEntity;
    }(CredentialEntity));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * REFRESH_TOKEN Cache
     *
     * Key:Value Schema:
     *
     * Key Example: uid.utid-login.microsoftonline.com-refreshtoken-clientId--
     *
     * Value:
     * {
     *      homeAccountId: home account identifier for the auth scheme,
     *      environment: entity that issued the token, represented as a full host
     *      credentialType: Type of credential as a string, can be one of the following: RefreshToken, AccessToken, IdToken, Password, Cookie, Certificate, Other
     *      clientId: client ID of the application
     *      secret: Actual credential as a string
     *      familyId: Family ID identifier, '1' represents Microsoft Family
     *      realm: Full tenant or organizational identifier that the account belongs to
     *      target: Permissions that are included in the token, or for refresh tokens, the resource identifier.
     * }
     */
    var RefreshTokenEntity = /** @class */ (function (_super) {
        __extends$1(RefreshTokenEntity, _super);
        function RefreshTokenEntity() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Create RefreshTokenEntity
         * @param homeAccountId
         * @param authenticationResult
         * @param clientId
         * @param authority
         */
        RefreshTokenEntity.createRefreshTokenEntity = function (homeAccountId, environment, refreshToken, clientId, familyId, oboAssertion) {
            var rtEntity = new RefreshTokenEntity();
            rtEntity.clientId = clientId;
            rtEntity.credentialType = CredentialType.REFRESH_TOKEN;
            rtEntity.environment = environment;
            rtEntity.homeAccountId = homeAccountId;
            rtEntity.secret = refreshToken;
            rtEntity.oboAssertion = oboAssertion;
            if (familyId)
                rtEntity.familyId = familyId;
            return rtEntity;
        };
        /**
         * Validates an entity: checks for all expected params
         * @param entity
         */
        RefreshTokenEntity.isRefreshTokenEntity = function (entity) {
            if (!entity) {
                return false;
            }
            return (entity.hasOwnProperty("homeAccountId") &&
                entity.hasOwnProperty("environment") &&
                entity.hasOwnProperty("credentialType") &&
                entity.hasOwnProperty("clientId") &&
                entity.hasOwnProperty("secret") &&
                entity["credentialType"] === CredentialType.REFRESH_TOKEN);
        };
        return RefreshTokenEntity;
    }(CredentialEntity));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * InteractionRequiredAuthErrorMessage class containing string constants used by error codes and messages.
     */
    var InteractionRequiredAuthErrorMessage = [
        "interaction_required",
        "consent_required",
        "login_required"
    ];
    var InteractionRequiredAuthSubErrorMessage = [
        "message_only",
        "additional_action",
        "basic_action",
        "user_password_expired",
        "consent_required"
    ];
    /**
     * Error thrown when user interaction is required at the auth server.
     */
    var InteractionRequiredAuthError = /** @class */ (function (_super) {
        __extends$1(InteractionRequiredAuthError, _super);
        function InteractionRequiredAuthError(errorCode, errorMessage, subError) {
            var _this = _super.call(this, errorCode, errorMessage, subError) || this;
            _this.name = "InteractionRequiredAuthError";
            Object.setPrototypeOf(_this, InteractionRequiredAuthError.prototype);
            return _this;
        }
        InteractionRequiredAuthError.isInteractionRequiredError = function (errorCode, errorString, subError) {
            var isInteractionRequiredErrorCode = !!errorCode && InteractionRequiredAuthErrorMessage.indexOf(errorCode) > -1;
            var isInteractionRequiredSubError = !!subError && InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
            var isInteractionRequiredErrorDesc = !!errorString && InteractionRequiredAuthErrorMessage.some(function (irErrorCode) {
                return errorString.indexOf(irErrorCode) > -1;
            });
            return isInteractionRequiredErrorCode || isInteractionRequiredErrorDesc || isInteractionRequiredSubError;
        };
        return InteractionRequiredAuthError;
    }(ServerError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var CacheRecord = /** @class */ (function () {
        function CacheRecord(accountEntity, idTokenEntity, accessTokenEntity, refreshTokenEntity, appMetadataEntity) {
            this.account = accountEntity || null;
            this.idToken = idTokenEntity || null;
            this.accessToken = accessTokenEntity || null;
            this.refreshToken = refreshTokenEntity || null;
            this.appMetadata = appMetadataEntity || null;
        }
        return CacheRecord;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class which provides helpers for OAuth 2.0 protocol specific values
     */
    var ProtocolUtils = /** @class */ (function () {
        function ProtocolUtils() {
        }
        /**
         * Appends user state with random guid, or returns random guid.
         * @param userState
         * @param randomGuid
         */
        ProtocolUtils.setRequestState = function (cryptoObj, userState, meta) {
            var libraryState = ProtocolUtils.generateLibraryState(cryptoObj, meta);
            return !StringUtils.isEmpty(userState) ? "" + libraryState + Constants.RESOURCE_DELIM + userState : libraryState;
        };
        /**
         * Generates the state value used by the common library.
         * @param randomGuid
         * @param cryptoObj
         */
        ProtocolUtils.generateLibraryState = function (cryptoObj, meta) {
            if (!cryptoObj) {
                throw ClientAuthError.createNoCryptoObjectError("generateLibraryState");
            }
            // Create a state object containing a unique id and the timestamp of the request creation
            var stateObj = {
                id: cryptoObj.createNewGuid(),
                ts: TimeUtils.nowSeconds()
            };
            if (meta) {
                stateObj.meta = meta;
            }
            var stateString = JSON.stringify(stateObj);
            return cryptoObj.base64Encode(stateString);
        };
        /**
         * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
         * @param state
         * @param cryptoObj
         */
        ProtocolUtils.parseRequestState = function (cryptoObj, state) {
            if (!cryptoObj) {
                throw ClientAuthError.createNoCryptoObjectError("parseRequestState");
            }
            if (StringUtils.isEmpty(state)) {
                throw ClientAuthError.createInvalidStateError(state, "Null, undefined or empty state");
            }
            try {
                // Split the state between library state and user passed state and decode them separately
                var splitState = decodeURIComponent(state).split(Constants.RESOURCE_DELIM);
                var libraryState = splitState[0];
                var userState = splitState.length > 1 ? splitState.slice(1).join(Constants.RESOURCE_DELIM) : "";
                var libraryStateString = cryptoObj.base64Decode(libraryState);
                var libraryStateObj = JSON.parse(libraryStateString);
                return {
                    userRequestState: !StringUtils.isEmpty(userState) ? userState : "",
                    libraryState: libraryStateObj
                };
            }
            catch (e) {
                throw ClientAuthError.createInvalidStateError(state, e);
            }
        };
        return ProtocolUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var KeyLocation;
    (function (KeyLocation) {
        KeyLocation["SW"] = "sw";
        KeyLocation["UHW"] = "uhw";
    })(KeyLocation || (KeyLocation = {}));
    var PopTokenGenerator = /** @class */ (function () {
        function PopTokenGenerator(cryptoUtils) {
            this.cryptoUtils = cryptoUtils;
        }
        PopTokenGenerator.prototype.generateCnf = function (resourceRequestMethod, resourceRequestUri) {
            return __awaiter$1(this, void 0, void 0, function () {
                var kidThumbprint, reqCnf;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.cryptoUtils.getPublicKeyThumbprint(resourceRequestMethod, resourceRequestUri)];
                        case 1:
                            kidThumbprint = _a.sent();
                            reqCnf = {
                                kid: kidThumbprint,
                                xms_ksl: KeyLocation.SW
                            };
                            return [2 /*return*/, this.cryptoUtils.base64Encode(JSON.stringify(reqCnf))];
                    }
                });
            });
        };
        PopTokenGenerator.prototype.signPopToken = function (accessToken, resourceRequestMethod, resourceRequestUri) {
            var _a;
            return __awaiter$1(this, void 0, void 0, function () {
                var tokenClaims, resourceUrlString, resourceUrlComponents;
                return __generator$1(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            tokenClaims = AuthToken.extractTokenClaims(accessToken, this.cryptoUtils);
                            resourceUrlString = new UrlString(resourceRequestUri);
                            resourceUrlComponents = resourceUrlString.getUrlComponents();
                            if (!((_a = tokenClaims === null || tokenClaims === void 0 ? void 0 : tokenClaims.cnf) === null || _a === void 0 ? void 0 : _a.kid)) {
                                throw ClientAuthError.createTokenClaimsRequiredError();
                            }
                            return [4 /*yield*/, this.cryptoUtils.signJwt({
                                at: accessToken,
                                ts: "" + TimeUtils.nowSeconds(),
                                m: resourceRequestMethod.toUpperCase(),
                                u: resourceUrlComponents.HostNameAndPort || "",
                                nonce: this.cryptoUtils.createNewGuid(),
                                p: resourceUrlComponents.AbsolutePath,
                                q: [[], resourceUrlComponents.QueryString],
                            }, tokenClaims.cnf.kid)];
                        case 1: return [2 /*return*/, _b.sent()];
                    }
                });
            });
        };
        return PopTokenGenerator;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * APP_METADATA Cache
     *
     * Key:Value Schema:
     *
     * Key: appmetadata-<environment>-<client_id>
     *
     * Value:
     * {
     *      clientId: client ID of the application
     *      environment: entity that issued the token, represented as a full host
     *      familyId: Family ID identifier, '1' represents Microsoft Family
     * }
     */
    var AppMetadataEntity = /** @class */ (function () {
        function AppMetadataEntity() {
        }
        /**
         * Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>
         */
        AppMetadataEntity.prototype.generateAppMetadataKey = function () {
            return AppMetadataEntity.generateAppMetadataCacheKey(this.environment, this.clientId);
        };
        /**
         * Generate AppMetadata Cache Key
         */
        AppMetadataEntity.generateAppMetadataCacheKey = function (environment, clientId) {
            var appMetaDataKeyArray = [
                APP_METADATA,
                environment,
                clientId,
            ];
            return appMetaDataKeyArray.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
        };
        /**
         * Creates AppMetadataEntity
         * @param clientId
         * @param environment
         * @param familyId
         */
        AppMetadataEntity.createAppMetadataEntity = function (clientId, environment, familyId) {
            var appMetadata = new AppMetadataEntity();
            appMetadata.clientId = clientId;
            appMetadata.environment = environment;
            if (familyId) {
                appMetadata.familyId = familyId;
            }
            return appMetadata;
        };
        /**
         * Validates an entity: checks for all expected params
         * @param entity
         */
        AppMetadataEntity.isAppMetadataEntity = function (key, entity) {
            if (!entity) {
                return false;
            }
            return (key.indexOf(APP_METADATA) === 0 &&
                entity.hasOwnProperty("clientId") &&
                entity.hasOwnProperty("environment"));
        };
        return AppMetadataEntity;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var TokenCacheContext = /** @class */ (function () {
        function TokenCacheContext(tokenCache, hasChanged) {
            this.cache = tokenCache;
            this.hasChanged = hasChanged;
        }
        Object.defineProperty(TokenCacheContext.prototype, "cacheHasChanged", {
            get: function () {
                return this.hasChanged;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TokenCacheContext.prototype, "tokenCache", {
            get: function () {
                return this.cache;
            },
            enumerable: true,
            configurable: true
        });
        return TokenCacheContext;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class that handles response parsing.
     */
    var ResponseHandler = /** @class */ (function () {
        function ResponseHandler(clientId, cacheStorage, cryptoObj, logger, serializableCache, persistencePlugin) {
            this.clientId = clientId;
            this.cacheStorage = cacheStorage;
            this.cryptoObj = cryptoObj;
            this.logger = logger;
            this.serializableCache = serializableCache;
            this.persistencePlugin = persistencePlugin;
        }
        /**
         * Function which validates server authorization code response.
         * @param serverResponseHash
         * @param cachedState
         * @param cryptoObj
         */
        ResponseHandler.prototype.validateServerAuthorizationCodeResponse = function (serverResponseHash, cachedState, cryptoObj) {
            if (!serverResponseHash.state || !cachedState) {
                throw !serverResponseHash.state ? ClientAuthError.createStateNotFoundError("Server State") : ClientAuthError.createStateNotFoundError("Cached State");
            }
            if (decodeURIComponent(serverResponseHash.state) !== decodeURIComponent(cachedState)) {
                throw ClientAuthError.createStateMismatchError();
            }
            // Check for error
            if (serverResponseHash.error || serverResponseHash.error_description || serverResponseHash.suberror) {
                if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponseHash.error, serverResponseHash.error_description, serverResponseHash.suberror)) {
                    throw new InteractionRequiredAuthError(serverResponseHash.error || Constants.EMPTY_STRING, serverResponseHash.error_description, serverResponseHash.suberror);
                }
                throw new ServerError(serverResponseHash.error || Constants.EMPTY_STRING, serverResponseHash.error_description, serverResponseHash.suberror);
            }
            if (serverResponseHash.client_info) {
                buildClientInfo(serverResponseHash.client_info, cryptoObj);
            }
        };
        /**
         * Function which validates server authorization token response.
         * @param serverResponse
         */
        ResponseHandler.prototype.validateTokenResponse = function (serverResponse) {
            // Check for error
            if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {
                if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
                    throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror);
                }
                var errString = serverResponse.error_codes + " - [" + serverResponse.timestamp + "]: " + serverResponse.error_description + " - Correlation ID: " + serverResponse.correlation_id + " - Trace ID: " + serverResponse.trace_id;
                throw new ServerError(serverResponse.error, errString);
            }
        };
        /**
         * Returns a constructed token response based on given string. Also manages the cache updates and cleanups.
         * @param serverTokenResponse
         * @param authority
         */
        ResponseHandler.prototype.handleServerTokenResponse = function (serverTokenResponse, authority, resourceRequestMethod, resourceRequestUri, authCodePayload, requestScopes, oboAssertion, handlingRefreshTokenResponse) {
            return __awaiter$1(this, void 0, void 0, function () {
                var idTokenObj, requestStateObj, cacheRecord, cacheContext, key, account;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (serverTokenResponse.id_token) {
                                idTokenObj = new AuthToken(serverTokenResponse.id_token || Constants.EMPTY_STRING, this.cryptoObj);
                                // token nonce check (TODO: Add a warning if no nonce is given?)
                                if (authCodePayload && !StringUtils.isEmpty(authCodePayload.nonce)) {
                                    if (idTokenObj.claims.nonce !== authCodePayload.nonce) {
                                        throw ClientAuthError.createNonceMismatchError();
                                    }
                                }
                            }
                            // generate homeAccountId
                            this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenObj);
                            if (!!authCodePayload && !!authCodePayload.state) {
                                requestStateObj = ProtocolUtils.parseRequestState(this.cryptoObj, authCodePayload.state);
                            }
                            cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, idTokenObj, requestStateObj && requestStateObj.libraryState, requestScopes, oboAssertion, authCodePayload);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, , 4, 7]);
                            if (!(this.persistencePlugin && this.serializableCache)) return [3 /*break*/, 3];
                            this.logger.verbose("Persistence enabled, calling beforeCacheAccess");
                            cacheContext = new TokenCacheContext(this.serializableCache, true);
                            return [4 /*yield*/, this.persistencePlugin.beforeCacheAccess(cacheContext)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            /*
                             * When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.
                             * If not present, we should return null, as it's the case that another application called removeAccount in between
                             * the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal.
                             */
                            if (handlingRefreshTokenResponse && cacheRecord.account) {
                                key = cacheRecord.account.generateAccountKey();
                                account = this.cacheStorage.getAccount(key);
                                if (!account) {
                                    this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache");
                                    return [2 /*return*/, null];
                                }
                            }
                            this.cacheStorage.saveCacheRecord(cacheRecord);
                            return [3 /*break*/, 7];
                        case 4:
                            if (!(this.persistencePlugin && this.serializableCache && cacheContext)) return [3 /*break*/, 6];
                            this.logger.verbose("Persistence enabled, calling afterCacheAccess");
                            return [4 /*yield*/, this.persistencePlugin.afterCacheAccess(cacheContext)];
                        case 5:
                            _a.sent();
                            _a.label = 6;
                        case 6: return [7 /*endfinally*/];
                        case 7: return [2 /*return*/, ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, idTokenObj, requestStateObj, resourceRequestMethod, resourceRequestUri)];
                    }
                });
            });
        };
        /**
         * Generates CacheRecord
         * @param serverTokenResponse
         * @param idTokenObj
         * @param authority
         */
        ResponseHandler.prototype.generateCacheRecord = function (serverTokenResponse, authority, idTokenObj, libraryState, requestScopes, oboAssertion, authCodePayload) {
            var env = Authority.generateEnvironmentFromAuthority(authority);
            if (StringUtils.isEmpty(env)) {
                throw ClientAuthError.createInvalidCacheEnvironmentError();
            }
            // IdToken: non AAD scenarios can have empty realm
            var cachedIdToken;
            var cachedAccount;
            if (!StringUtils.isEmpty(serverTokenResponse.id_token) && !!idTokenObj) {
                cachedIdToken = IdTokenEntity.createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token || Constants.EMPTY_STRING, this.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING, oboAssertion);
                cachedAccount = this.generateAccountEntity(serverTokenResponse, idTokenObj, authority, oboAssertion, authCodePayload);
            }
            // AccessToken
            var cachedAccessToken = null;
            if (!StringUtils.isEmpty(serverTokenResponse.access_token)) {
                // If scopes not returned in server response, use request scopes
                var responseScopes = serverTokenResponse.scope ? ScopeSet.fromString(serverTokenResponse.scope) : new ScopeSet(requestScopes || []);
                // Expiration calculation
                var currentTime = TimeUtils.nowSeconds();
                // If the request timestamp was sent in the library state, use that timestamp to calculate expiration. Otherwise, use current time.
                var timestamp = libraryState ? libraryState.ts : currentTime;
                var tokenExpirationSeconds = timestamp + (serverTokenResponse.expires_in || 0);
                var extendedTokenExpirationSeconds = tokenExpirationSeconds + (serverTokenResponse.ext_expires_in || 0);
                // non AAD scenarios can have empty realm
                cachedAccessToken = AccessTokenEntity.createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token || Constants.EMPTY_STRING, this.clientId, idTokenObj ? idTokenObj.claims.tid || Constants.EMPTY_STRING : authority.tenant, responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, serverTokenResponse.token_type, oboAssertion);
            }
            // refreshToken
            var cachedRefreshToken = null;
            if (!StringUtils.isEmpty(serverTokenResponse.refresh_token)) {
                cachedRefreshToken = RefreshTokenEntity.createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token || Constants.EMPTY_STRING, this.clientId, serverTokenResponse.foci, oboAssertion);
            }
            // appMetadata
            var cachedAppMetadata = null;
            if (!StringUtils.isEmpty(serverTokenResponse.foci)) {
                cachedAppMetadata = AppMetadataEntity.createAppMetadataEntity(this.clientId, env, serverTokenResponse.foci);
            }
            return new CacheRecord(cachedAccount, cachedIdToken, cachedAccessToken, cachedRefreshToken, cachedAppMetadata);
        };
        /**
         * Generate Account
         * @param serverTokenResponse
         * @param idToken
         * @param authority
         */
        ResponseHandler.prototype.generateAccountEntity = function (serverTokenResponse, idToken, authority, oboAssertion, authCodePayload) {
            var authorityType = authority.authorityType;
            var cloudGraphHostName = authCodePayload ? authCodePayload.cloud_graph_host_name : "";
            var msGraphhost = authCodePayload ? authCodePayload.msgraph_host : "";
            // ADFS does not require client_info in the response
            if (authorityType === AuthorityType.Adfs) {
                this.logger.verbose("Authority type is ADFS, creating ADFS account");
                return AccountEntity.createGenericAccount(authority, this.homeAccountIdentifier, idToken, oboAssertion, cloudGraphHostName, msGraphhost);
            }
            // This fallback applies to B2C as well as they fall under an AAD account type.
            if (StringUtils.isEmpty(serverTokenResponse.client_info) && authority.protocolMode === "AAD") {
                throw ClientAuthError.createClientInfoEmptyError();
            }
            return serverTokenResponse.client_info ?
                AccountEntity.createAccount(serverTokenResponse.client_info, this.homeAccountIdentifier, authority, idToken, oboAssertion, cloudGraphHostName, msGraphhost) :
                AccountEntity.createGenericAccount(authority, this.homeAccountIdentifier, idToken, oboAssertion, cloudGraphHostName, msGraphhost);
        };
        /**
         * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.
         *
         * Optionally takes a state string that is set as-is in the response.
         *
         * @param cacheRecord
         * @param idTokenObj
         * @param fromTokenCache
         * @param stateString
         */
        ResponseHandler.generateAuthenticationResult = function (cryptoObj, authority, cacheRecord, fromTokenCache, idTokenObj, requestState, resourceRequestMethod, resourceRequestUri) {
            var _a, _b, _c;
            return __awaiter$1(this, void 0, void 0, function () {
                var accessToken, responseScopes, expiresOn, extExpiresOn, familyId, popTokenGenerator, uid, tid;
                return __generator$1(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            accessToken = "";
                            responseScopes = [];
                            expiresOn = null;
                            familyId = Constants.EMPTY_STRING;
                            if (!cacheRecord.accessToken) return [3 /*break*/, 4];
                            if (!(cacheRecord.accessToken.tokenType === exports.AuthenticationScheme.POP)) return [3 /*break*/, 2];
                            popTokenGenerator = new PopTokenGenerator(cryptoObj);
                            if (!resourceRequestMethod || !resourceRequestUri) {
                                throw ClientConfigurationError.createResourceRequestParametersRequiredError();
                            }
                            return [4 /*yield*/, popTokenGenerator.signPopToken(cacheRecord.accessToken.secret, resourceRequestMethod, resourceRequestUri)];
                        case 1:
                            accessToken = _d.sent();
                            return [3 /*break*/, 3];
                        case 2:
                            accessToken = cacheRecord.accessToken.secret;
                            _d.label = 3;
                        case 3:
                            responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
                            expiresOn = new Date(Number(cacheRecord.accessToken.expiresOn) * 1000);
                            extExpiresOn = new Date(Number(cacheRecord.accessToken.extendedExpiresOn) * 1000);
                            _d.label = 4;
                        case 4:
                            if (cacheRecord.appMetadata) {
                                familyId = cacheRecord.appMetadata.familyId === THE_FAMILY_ID ? THE_FAMILY_ID : Constants.EMPTY_STRING;
                            }
                            uid = (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.oid) || (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.sub) || Constants.EMPTY_STRING;
                            tid = (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.tid) || Constants.EMPTY_STRING;
                            return [2 /*return*/, {
                                authority: authority.canonicalAuthority,
                                uniqueId: uid,
                                tenantId: tid,
                                scopes: responseScopes,
                                account: cacheRecord.account ? cacheRecord.account.getAccountInfo() : null,
                                idToken: idTokenObj ? idTokenObj.rawToken : Constants.EMPTY_STRING,
                                idTokenClaims: idTokenObj ? idTokenObj.claims : {},
                                accessToken: accessToken,
                                fromCache: fromTokenCache,
                                expiresOn: expiresOn,
                                extExpiresOn: extExpiresOn,
                                familyId: familyId,
                                tokenType: ((_a = cacheRecord.accessToken) === null || _a === void 0 ? void 0 : _a.tokenType) || Constants.EMPTY_STRING,
                                state: requestState ? requestState.userRequestState : Constants.EMPTY_STRING,
                                cloudGraphHostName: ((_b = cacheRecord.account) === null || _b === void 0 ? void 0 : _b.cloudGraphHostName) || Constants.EMPTY_STRING,
                                msGraphHost: ((_c = cacheRecord.account) === null || _c === void 0 ? void 0 : _c.msGraphHost) || Constants.EMPTY_STRING
                            }];
                    }
                });
            });
        };
        return ResponseHandler;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Oauth2.0 Authorization Code client
     */
    var AuthorizationCodeClient = /** @class */ (function (_super) {
        __extends$1(AuthorizationCodeClient, _super);
        function AuthorizationCodeClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Creates the URL of the authorization request letting the user input credentials and consent to the
         * application. The URL target the /authorize endpoint of the authority configured in the
         * application object.
         *
         * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
         * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
         * acquireToken(AuthorizationCodeRequest)
         * @param request
         */
        AuthorizationCodeClient.prototype.getAuthCodeUrl = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var queryString;
                return __generator$1(this, function (_a) {
                    queryString = this.createAuthCodeUrlQueryString(request);
                    return [2 /*return*/, this.authority.authorizationEndpoint + "?" + queryString];
                });
            });
        };
        /**
         * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
         * authorization_code_grant
         * @param request
         */
        AuthorizationCodeClient.prototype.acquireToken = function (request, authCodePayload) {
            return __awaiter$1(this, void 0, void 0, function () {
                var response, responseHandler;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.logger.info("in acquireToken call");
                            if (!request || StringUtils.isEmpty(request.code)) {
                                throw ClientAuthError.createTokenRequestCannotBeMadeError();
                            }
                            return [4 /*yield*/, this.executeTokenRequest(this.authority, request)];
                        case 1:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            // Validate response. This function throws a server error if an error is returned by the server.
                            responseHandler.validateTokenResponse(response.body);
                            return [4 /*yield*/, responseHandler.handleServerTokenResponse(response.body, this.authority, request.resourceRequestMethod, request.resourceRequestUri, authCodePayload)];
                        case 2: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * Handles the hash fragment response from public client code request. Returns a code response used by
         * the client to exchange for a token in acquireToken.
         * @param hashFragment
         */
        AuthorizationCodeClient.prototype.handleFragmentResponse = function (hashFragment, cachedState) {
            // Handle responses.
            var responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, null, null);
            // Deserialize hash fragment response parameters.
            var hashUrlString = new UrlString(hashFragment);
            // Deserialize hash fragment response parameters.
            var serverParams = UrlString.getDeserializedHash(hashUrlString.getHash());
            // Get code response
            responseHandler.validateServerAuthorizationCodeResponse(serverParams, cachedState, this.cryptoUtils);
            // throw when there is no auth code in the response
            if (!serverParams.code) {
                throw ClientAuthError.createNoAuthCodeInServerResponseError();
            }
            return __assign$1(__assign$1({}, serverParams), {
                // Code param is optional in ServerAuthorizationCodeResponse but required in AuthorizationCodePaylod
                code: serverParams.code
            });
        };
        /**
         * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param authorityUri
         */
        AuthorizationCodeClient.prototype.getLogoutUri = function (logoutRequest) {
            // Throw error if logoutRequest is null/undefined
            if (!logoutRequest) {
                throw ClientConfigurationError.createEmptyLogoutRequestError();
            }
            if (logoutRequest.account) {
                // Clear given account.
                this.cacheManager.removeAccount(AccountEntity.generateAccountCacheKey(logoutRequest.account));
            }
            else {
                // Clear all accounts and tokens
                this.cacheManager.clear();
            }
            var queryString = this.createLogoutUrlQueryString(logoutRequest);
            // Construct logout URI.
            return StringUtils.isEmpty(queryString) ? this.authority.endSessionEndpoint : this.authority.endSessionEndpoint + "?" + queryString;
        };
        /**
         * Executes POST request to token endpoint
         * @param authority
         * @param request
         */
        AuthorizationCodeClient.prototype.executeTokenRequest = function (authority, request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var thumbprint, requestBody, headers;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            thumbprint = {
                                clientId: this.config.authOptions.clientId,
                                authority: authority.canonicalAuthority,
                                scopes: request.scopes
                            };
                            return [4 /*yield*/, this.createTokenRequestBody(request)];
                        case 1:
                            requestBody = _a.sent();
                            headers = this.createDefaultTokenRequestHeaders();
                            return [2 /*return*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
                    }
                });
            });
        };
        /**
         * Generates a map for all the params to be sent to the service
         * @param request
         */
        AuthorizationCodeClient.prototype.createTokenRequestBody = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var parameterBuilder, clientAssertion, popTokenGenerator, cnfString, correlationId;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            parameterBuilder = new RequestParameterBuilder();
                            parameterBuilder.addClientId(this.config.authOptions.clientId);
                            // validate the redirectUri (to be a non null value)
                            parameterBuilder.addRedirectUri(request.redirectUri);
                            // Add scope array, parameter builder will add default scopes and dedupe
                            parameterBuilder.addScopes(request.scopes);
                            // add code: user set, not validated
                            parameterBuilder.addAuthorizationCode(request.code);
                            // add code_verifier if passed
                            if (request.codeVerifier) {
                                parameterBuilder.addCodeVerifier(request.codeVerifier);
                            }
                            if (this.config.clientCredentials.clientSecret) {
                                parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
                            }
                            if (this.config.clientCredentials.clientAssertion) {
                                clientAssertion = this.config.clientCredentials.clientAssertion;
                                parameterBuilder.addClientAssertion(clientAssertion.assertion);
                                parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
                            }
                            parameterBuilder.addGrantType(GrantType.AUTHORIZATION_CODE_GRANT);
                            parameterBuilder.addClientInfo();
                            if (!(request.authenticationScheme === exports.AuthenticationScheme.POP && !!request.resourceRequestMethod && !!request.resourceRequestUri)) return [3 /*break*/, 2];
                            popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
                            return [4 /*yield*/, popTokenGenerator.generateCnf(request.resourceRequestMethod, request.resourceRequestUri)];
                        case 1:
                            cnfString = _a.sent();
                            parameterBuilder.addPopToken(cnfString);
                            _a.label = 2;
                        case 2:
                            correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
                            parameterBuilder.addCorrelationId(correlationId);
                            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
                            }
                            return [2 /*return*/, parameterBuilder.createQueryString()];
                    }
                });
            });
        };
        /**
         * This API validates the `AuthorizationCodeUrlRequest` and creates a URL
         * @param request
         */
        AuthorizationCodeClient.prototype.createAuthCodeUrlQueryString = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            parameterBuilder.addClientId(this.config.authOptions.clientId);
            var requestScopes = __spreadArrays(request.scopes || [], request.extraScopesToConsent || []);
            parameterBuilder.addScopes(requestScopes);
            // validate the redirectUri (to be a non null value)
            parameterBuilder.addRedirectUri(request.redirectUri);
            // generate the correlationId if not set by the user and add
            var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
            parameterBuilder.addCorrelationId(correlationId);
            // add response_mode. If not passed in it defaults to query.
            parameterBuilder.addResponseMode(request.responseMode);
            // add response_type = code
            parameterBuilder.addResponseTypeCode();
            // add library info parameters
            parameterBuilder.addLibraryInfo(this.config.libraryInfo);
            // add client_info=1
            parameterBuilder.addClientInfo();
            if (request.codeChallenge && request.codeChallengeMethod) {
                parameterBuilder.addCodeChallengeParams(request.codeChallenge, request.codeChallengeMethod);
            }
            if (request.prompt) {
                parameterBuilder.addPrompt(request.prompt);
            }
            if (request.domainHint) {
                parameterBuilder.addDomainHint(request.domainHint);
            }
            // Add sid or loginHint with preference for sid -> loginHint -> username of AccountInfo object
            if (request.sid) {
                parameterBuilder.addSid(request.sid);
            }
            else if (request.loginHint) {
                parameterBuilder.addLoginHint(request.loginHint);
            }
            else if (request.account && request.account.username) {
                parameterBuilder.addLoginHint(request.account.username);
            }
            if (request.nonce) {
                parameterBuilder.addNonce(request.nonce);
            }
            if (request.state) {
                parameterBuilder.addState(request.state);
            }
            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
            }
            if (request.extraQueryParameters) {
                parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
            }
            return parameterBuilder.createQueryString();
        };
        /**
         * This API validates the `EndSessionRequest` and creates a URL
         * @param request
         */
        AuthorizationCodeClient.prototype.createLogoutUrlQueryString = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            if (request.postLogoutRedirectUri) {
                parameterBuilder.addPostLogoutRedirectUri(request.postLogoutRedirectUri);
            }
            if (request.correlationId) {
                parameterBuilder.addCorrelationId(request.correlationId);
            }
            if (request.idTokenHint) {
                parameterBuilder.addIdTokenHint(request.idTokenHint);
            }
            return parameterBuilder.createQueryString();
        };
        return AuthorizationCodeClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * OAuth2.0 Device code client
     */
    var DeviceCodeClient = /** @class */ (function (_super) {
        __extends$1(DeviceCodeClient, _super);
        function DeviceCodeClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Gets device code from device code endpoint, calls back to with device code response, and
         * polls token endpoint to exchange device code for tokens
         * @param request
         */
        DeviceCodeClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var deviceCodeResponse, response, responseHandler;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.getDeviceCode(request)];
                        case 1:
                            deviceCodeResponse = _a.sent();
                            request.deviceCodeCallback(deviceCodeResponse);
                            return [4 /*yield*/, this.acquireTokenWithDeviceCode(request, deviceCodeResponse)];
                        case 2:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            // Validate response. This function throws a server error if an error is returned by the server.
                            responseHandler.validateTokenResponse(response);
                            return [4 /*yield*/, responseHandler.handleServerTokenResponse(response, this.authority, request.resourceRequestMethod, request.resourceRequestUri)];
                        case 3: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * Creates device code request and executes http GET
         * @param request
         */
        DeviceCodeClient.prototype.getDeviceCode = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var queryString, headers, thumbprint;
                return __generator$1(this, function (_a) {
                    queryString = this.createQueryString(request);
                    headers = this.createDefaultTokenRequestHeaders();
                    thumbprint = {
                        clientId: this.config.authOptions.clientId,
                        authority: request.authority,
                        scopes: request.scopes
                    };
                    return [2 /*return*/, this.executePostRequestToDeviceCodeEndpoint(this.authority.deviceCodeEndpoint, queryString, headers, thumbprint)];
                });
            });
        };
        /**
         * Executes POST request to device code endpoint
         * @param deviceCodeEndpoint
         * @param queryString
         * @param headers
         */
        DeviceCodeClient.prototype.executePostRequestToDeviceCodeEndpoint = function (deviceCodeEndpoint, queryString, headers, thumbprint) {
            return __awaiter$1(this, void 0, void 0, function () {
                var _a, userCode, deviceCode, verificationUri, expiresIn, interval, message;
                return __generator$1(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, this.networkManager.sendPostRequest(thumbprint, deviceCodeEndpoint, {
                            body: queryString,
                            headers: headers
                        })];
                        case 1:
                            _a = (_b.sent()).body, userCode = _a.user_code, deviceCode = _a.device_code, verificationUri = _a.verification_uri, expiresIn = _a.expires_in, interval = _a.interval, message = _a.message;
                            return [2 /*return*/, {
                                userCode: userCode,
                                deviceCode: deviceCode,
                                verificationUri: verificationUri,
                                expiresIn: expiresIn,
                                interval: interval,
                                message: message
                            }];
                    }
                });
            });
        };
        /**
         * Create device code endpoint query parameters and returns string
         */
        DeviceCodeClient.prototype.createQueryString = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            parameterBuilder.addScopes(request.scopes);
            parameterBuilder.addClientId(this.config.authOptions.clientId);
            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
            }
            return parameterBuilder.createQueryString();
        };
        /**
         * Creates token request with device code response and polls token endpoint at interval set by the device code
         * response
         * @param request
         * @param deviceCodeResponse
         */
        DeviceCodeClient.prototype.acquireTokenWithDeviceCode = function (request, deviceCodeResponse) {
            return __awaiter$1(this, void 0, void 0, function () {
                var requestBody, headers, deviceCodeExpirationTime, pollingIntervalMilli;
                var _this = this;
                return __generator$1(this, function (_a) {
                    requestBody = this.createTokenRequestBody(request, deviceCodeResponse);
                    headers = this.createDefaultTokenRequestHeaders();
                    deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;
                    pollingIntervalMilli = deviceCodeResponse.interval * 1000;
                    /*
                     * Poll token endpoint while (device code is not expired AND operation has not been cancelled by
                     * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli
                     */
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var intervalId = setInterval(function () {
                            return __awaiter$1(_this, void 0, void 0, function () {
                                var thumbprint, response, error_1;
                                return __generator$1(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            _a.trys.push([0, 5, , 6]);
                                            if (!request.cancel) return [3 /*break*/, 1];
                                            this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true");
                                            clearInterval(intervalId);
                                            reject(ClientAuthError.createDeviceCodeCancelledError());
                                            return [3 /*break*/, 4];
                                        case 1:
                                            if (!(TimeUtils.nowSeconds() > deviceCodeExpirationTime)) return [3 /*break*/, 2];
                                            this.logger.error("Device code expired. Expiration time of device code was " + deviceCodeExpirationTime);
                                            clearInterval(intervalId);
                                            reject(ClientAuthError.createDeviceCodeExpiredError());
                                            return [3 /*break*/, 4];
                                        case 2:
                                            thumbprint = {
                                                clientId: this.config.authOptions.clientId,
                                                authority: request.authority,
                                                scopes: request.scopes
                                            };
                                            return [4 /*yield*/, this.executePostToTokenEndpoint(this.authority.tokenEndpoint, requestBody, headers, thumbprint)];
                                        case 3:
                                            response = _a.sent();
                                            if (response.body && response.body.error === Constants.AUTHORIZATION_PENDING) {
                                                // user authorization is pending. Sleep for polling interval and try again
                                                this.logger.info(response.body.error_description || "no_error_description");
                                            }
                                            else {
                                                clearInterval(intervalId);
                                                resolve(response.body);
                                            }
                                            _a.label = 4;
                                        case 4: return [3 /*break*/, 6];
                                        case 5:
                                            error_1 = _a.sent();
                                            clearInterval(intervalId);
                                            reject(error_1);
                                            return [3 /*break*/, 6];
                                        case 6: return [2 /*return*/];
                                    }
                                });
                            });
                        }, pollingIntervalMilli);
                    })];
                });
            });
        };
        /**
         * Creates query parameters and converts to string.
         * @param request
         * @param deviceCodeResponse
         */
        DeviceCodeClient.prototype.createTokenRequestBody = function (request, deviceCodeResponse) {
            var requestParameters = new RequestParameterBuilder();
            requestParameters.addScopes(request.scopes);
            requestParameters.addClientId(this.config.authOptions.clientId);
            requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);
            requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);
            var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
            requestParameters.addCorrelationId(correlationId);
            requestParameters.addClientInfo();
            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                requestParameters.addClaims(request.claims, this.config.authOptions.clientCapabilities);
            }
            return requestParameters.createQueryString();
        };
        return DeviceCodeClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * OAuth2.0 refresh token client
     */
    var RefreshTokenClient = /** @class */ (function (_super) {
        __extends$1(RefreshTokenClient, _super);
        function RefreshTokenClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        RefreshTokenClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var response, responseHandler;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
                        case 1:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            responseHandler.validateTokenResponse(response.body);
                            return [2 /*return*/, responseHandler.handleServerTokenResponse(response.body, this.authority, request.resourceRequestMethod, request.resourceRequestUri, undefined, [], undefined, true)];
                    }
                });
            });
        };
        /**
         * Gets cached refresh token and attaches to request, then calls acquireToken API
         * @param request
         */
        RefreshTokenClient.prototype.acquireTokenByRefreshToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var isFOCI, noFamilyRTInCache, clientMismatchErrorWithFamilyRT;
                return __generator$1(this, function (_a) {
                    // Cannot renew token if no request object is given.
                    if (!request) {
                        throw ClientConfigurationError.createEmptyTokenRequestError();
                    }
                    // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
                    if (!request.account) {
                        throw ClientAuthError.createNoAccountInSilentRequestError();
                    }
                    isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, this.config.authOptions.clientId);
                    // if the app is part of the family, retrieve a Family refresh token if present and make a refreshTokenRequest
                    if (isFOCI) {
                        try {
                            return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, true)];
                        }
                        catch (e) {
                            noFamilyRTInCache = e instanceof ClientAuthError && e.errorCode === ClientAuthErrorMessage.noTokensFoundError.code;
                            clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === Errors.INVALID_GRANT_ERROR && e.subError === Errors.CLIENT_MISMATCH_ERROR;
                            // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)
                            if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
                                return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
                                // throw in all other cases
                            }
                            else {
                                throw e;
                            }
                        }
                    }
                    // fall back to application refresh token acquisition
                    return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
                });
            });
        };
        /**
         * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
         * @param request
         */
        RefreshTokenClient.prototype.acquireTokenWithCachedRefreshToken = function (request, foci) {
            return __awaiter$1(this, void 0, void 0, function () {
                var refreshToken, refreshTokenRequest;
                return __generator$1(this, function (_a) {
                    refreshToken = this.cacheManager.readRefreshTokenFromCache(this.config.authOptions.clientId, request.account, foci);
                    // no refresh Token
                    if (!refreshToken) {
                        throw ClientAuthError.createNoTokensFoundError();
                    }
                    refreshTokenRequest = __assign$1(__assign$1({}, request), { refreshToken: refreshToken.secret, authenticationScheme: exports.AuthenticationScheme.BEARER });
                    return [2 /*return*/, this.acquireToken(refreshTokenRequest)];
                });
            });
        };
        /**
         * Constructs the network message and makes a NW call to the underlying secure token service
         * @param request
         * @param authority
         */
        RefreshTokenClient.prototype.executeTokenRequest = function (request, authority) {
            return __awaiter$1(this, void 0, void 0, function () {
                var requestBody, headers, thumbprint;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.createTokenRequestBody(request)];
                        case 1:
                            requestBody = _a.sent();
                            headers = this.createDefaultTokenRequestHeaders();
                            thumbprint = {
                                clientId: this.config.authOptions.clientId,
                                authority: authority.canonicalAuthority,
                                scopes: request.scopes
                            };
                            return [2 /*return*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
                    }
                });
            });
        };
        /**
         * Helper function to create the token request body
         * @param request
         */
        RefreshTokenClient.prototype.createTokenRequestBody = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var parameterBuilder, correlationId, clientAssertion, popTokenGenerator, _a, _b;
                return __generator$1(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            parameterBuilder = new RequestParameterBuilder();
                            parameterBuilder.addClientId(this.config.authOptions.clientId);
                            parameterBuilder.addScopes(request.scopes);
                            parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
                            parameterBuilder.addClientInfo();
                            correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
                            parameterBuilder.addCorrelationId(correlationId);
                            parameterBuilder.addRefreshToken(request.refreshToken);
                            if (this.config.clientCredentials.clientSecret) {
                                parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
                            }
                            if (this.config.clientCredentials.clientAssertion) {
                                clientAssertion = this.config.clientCredentials.clientAssertion;
                                parameterBuilder.addClientAssertion(clientAssertion.assertion);
                                parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
                            }
                            if (!(request.authenticationScheme === exports.AuthenticationScheme.POP)) return [3 /*break*/, 2];
                            popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
                            if (!request.resourceRequestMethod || !request.resourceRequestUri) {
                                throw ClientConfigurationError.createResourceRequestParametersRequiredError();
                            }
                            _b = (_a = parameterBuilder).addPopToken;
                            return [4 /*yield*/, popTokenGenerator.generateCnf(request.resourceRequestMethod, request.resourceRequestUri)];
                        case 1:
                            _b.apply(_a, [_c.sent()]);
                            _c.label = 2;
                        case 2:
                            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
                            }
                            return [2 /*return*/, parameterBuilder.createQueryString()];
                    }
                });
            });
        };
        return RefreshTokenClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * OAuth2.0 client credential grant
     */
    var ClientCredentialClient = /** @class */ (function (_super) {
        __extends$1(ClientCredentialClient, _super);
        function ClientCredentialClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Public API to acquire a token with ClientCredential Flow for Confidential clients
         * @param request
         */
        ClientCredentialClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var cachedAuthenticationResult;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.scopeSet = new ScopeSet(request.scopes || []);
                            if (!request.skipCache) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
                        case 1: return [2 /*return*/, _a.sent()];
                        case 2: return [4 /*yield*/, this.getCachedAuthenticationResult()];
                        case 3:
                            cachedAuthenticationResult = _a.sent();
                            if (!cachedAuthenticationResult) return [3 /*break*/, 4];
                            return [2 /*return*/, cachedAuthenticationResult];
                        case 4: return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
                        case 5: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * looks up cache if the tokens are cached already
         */
        ClientCredentialClient.prototype.getCachedAuthenticationResult = function () {
            return __awaiter$1(this, void 0, void 0, function () {
                var cachedAccessToken;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            cachedAccessToken = this.readAccessTokenFromCache();
                            if (!cachedAccessToken ||
                                TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
                                return [2 /*return*/, null];
                            }
                            return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
                                account: null,
                                idToken: null,
                                accessToken: cachedAccessToken,
                                refreshToken: null,
                                appMetadata: null
                            }, true)];
                        case 1: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * Reads access token from the cache
         * TODO: Move this call to cacheManager instead
         */
        ClientCredentialClient.prototype.readAccessTokenFromCache = function () {
            var accessTokenFilter = {
                homeAccountId: "",
                environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
                credentialType: CredentialType.ACCESS_TOKEN,
                clientId: this.config.authOptions.clientId,
                realm: this.authority.tenant,
                target: this.scopeSet.printScopesLowerCase()
            };
            var credentialCache = this.cacheManager.getCredentialsFilteredBy(accessTokenFilter);
            var accessTokens = Object.keys(credentialCache.accessTokens).map(function (key) { return credentialCache.accessTokens[key]; });
            if (accessTokens.length < 1) {
                return null;
            }
            else if (accessTokens.length > 1) {
                throw ClientAuthError.createMultipleMatchingTokensInCacheError();
            }
            return accessTokens[0];
        };
        /**
         * Makes a network call to request the token from the service
         * @param request
         * @param authority
         */
        ClientCredentialClient.prototype.executeTokenRequest = function (request, authority) {
            return __awaiter$1(this, void 0, void 0, function () {
                var requestBody, headers, thumbprint, response, responseHandler, tokenResponse;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            requestBody = this.createTokenRequestBody(request);
                            headers = this.createDefaultTokenRequestHeaders();
                            thumbprint = {
                                clientId: this.config.authOptions.clientId,
                                authority: request.authority,
                                scopes: request.scopes
                            };
                            return [4 /*yield*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
                        case 1:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            responseHandler.validateTokenResponse(response.body);
                            return [4 /*yield*/, responseHandler.handleServerTokenResponse(response.body, this.authority, request.resourceRequestMethod, request.resourceRequestUri, undefined, request.scopes)];
                        case 2:
                            tokenResponse = _a.sent();
                            return [2 /*return*/, tokenResponse];
                    }
                });
            });
        };
        /**
         * generate the request to the server in the acceptable format
         * @param request
         */
        ClientCredentialClient.prototype.createTokenRequestBody = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            parameterBuilder.addClientId(this.config.authOptions.clientId);
            parameterBuilder.addScopes(request.scopes, false);
            parameterBuilder.addGrantType(GrantType.CLIENT_CREDENTIALS_GRANT);
            var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
            parameterBuilder.addCorrelationId(correlationId);
            if (this.config.clientCredentials.clientSecret) {
                parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
            }
            if (this.config.clientCredentials.clientAssertion) {
                var clientAssertion = this.config.clientCredentials.clientAssertion;
                parameterBuilder.addClientAssertion(clientAssertion.assertion);
                parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
            }
            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
            }
            return parameterBuilder.createQueryString();
        };
        return ClientCredentialClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * On-Behalf-Of client
     */
    var OnBehalfOfClient = /** @class */ (function (_super) {
        __extends$1(OnBehalfOfClient, _super);
        function OnBehalfOfClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Public API to acquire tokens with on behalf of flow
         * @param request
         */
        OnBehalfOfClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var cachedAuthenticationResult;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.scopeSet = new ScopeSet(request.scopes || []);
                            if (!request.skipCache) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
                        case 1: return [2 /*return*/, _a.sent()];
                        case 2: return [4 /*yield*/, this.getCachedAuthenticationResult(request)];
                        case 3:
                            cachedAuthenticationResult = _a.sent();
                            if (!cachedAuthenticationResult) return [3 /*break*/, 4];
                            return [2 /*return*/, cachedAuthenticationResult];
                        case 4: return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
                        case 5: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * look up cache for tokens
         * @param request
         */
        OnBehalfOfClient.prototype.getCachedAuthenticationResult = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var cachedAccessToken, cachedIdToken, idTokenObject, cachedAccount, localAccountId, accountInfo;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            cachedAccessToken = this.readAccessTokenFromCache(request);
                            if (!cachedAccessToken ||
                                TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
                                return [2 /*return*/, null];
                            }
                            cachedIdToken = this.readIdTokenFromCache(request);
                            cachedAccount = null;
                            if (cachedIdToken) {
                                idTokenObject = new AuthToken(cachedIdToken.secret, this.config.cryptoInterface);
                                localAccountId = idTokenObject.claims.oid ? idTokenObject.claims.oid : idTokenObject.claims.sub;
                                accountInfo = {
                                    homeAccountId: cachedIdToken.homeAccountId,
                                    environment: cachedIdToken.environment,
                                    tenantId: cachedIdToken.realm,
                                    username: Constants.EMPTY_STRING,
                                    localAccountId: localAccountId || ""
                                };
                                cachedAccount = this.readAccountFromCache(accountInfo);
                            }
                            return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
                                account: cachedAccount,
                                accessToken: cachedAccessToken,
                                idToken: cachedIdToken,
                                refreshToken: null,
                                appMetadata: null
                            }, true, idTokenObject)];
                        case 1: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * read access token from cache TODO: CacheManager API should be used here
         * @param request
         */
        OnBehalfOfClient.prototype.readAccessTokenFromCache = function (request) {
            var accessTokenFilter = {
                environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
                credentialType: CredentialType.ACCESS_TOKEN,
                clientId: this.config.authOptions.clientId,
                realm: this.authority.tenant,
                target: this.scopeSet.printScopesLowerCase(),
                oboAssertion: request.oboAssertion
            };
            var credentialCache = this.cacheManager.getCredentialsFilteredBy(accessTokenFilter);
            var accessTokens = Object.keys(credentialCache.accessTokens).map(function (key) { return credentialCache.accessTokens[key]; });
            var numAccessTokens = accessTokens.length;
            if (numAccessTokens < 1) {
                return null;
            }
            else if (numAccessTokens > 1) {
                throw ClientAuthError.createMultipleMatchingTokensInCacheError();
            }
            return accessTokens[0];
        };
        /**
         * read idtoken from cache TODO: CacheManager API should be used here instead
         * @param request
         */
        OnBehalfOfClient.prototype.readIdTokenFromCache = function (request) {
            var idTokenFilter = {
                environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
                credentialType: CredentialType.ID_TOKEN,
                clientId: this.config.authOptions.clientId,
                realm: this.authority.tenant,
                oboAssertion: request.oboAssertion
            };
            var credentialCache = this.cacheManager.getCredentialsFilteredBy(idTokenFilter);
            var idTokens = Object.keys(credentialCache.idTokens).map(function (key) { return credentialCache.idTokens[key]; });
            // When acquiring a token on behalf of an application, there might not be an id token in the cache
            if (idTokens.length < 1) {
                return null;
            }
            return idTokens[0];
        };
        /**
         * read account from cache, TODO: CacheManager API should be used here instead
         * @param account
         */
        OnBehalfOfClient.prototype.readAccountFromCache = function (account) {
            return this.cacheManager.readAccountFromCache(account);
        };
        /**
         * Make a network call to the server requesting credentials
         * @param request
         * @param authority
         */
        OnBehalfOfClient.prototype.executeTokenRequest = function (request, authority) {
            return __awaiter$1(this, void 0, void 0, function () {
                var requestBody, headers, thumbprint, response, responseHandler, tokenResponse;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            requestBody = this.createTokenRequestBody(request);
                            headers = this.createDefaultTokenRequestHeaders();
                            thumbprint = {
                                clientId: this.config.authOptions.clientId,
                                authority: request.authority,
                                scopes: request.scopes
                            };
                            return [4 /*yield*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
                        case 1:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            responseHandler.validateTokenResponse(response.body);
                            return [4 /*yield*/, responseHandler.handleServerTokenResponse(response.body, this.authority, request.resourceRequestMethod, request.resourceRequestUri, undefined, request.scopes, request.oboAssertion)];
                        case 2:
                            tokenResponse = _a.sent();
                            return [2 /*return*/, tokenResponse];
                    }
                });
            });
        };
        /**
         * generate a server request in accepable format
         * @param request
         */
        OnBehalfOfClient.prototype.createTokenRequestBody = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            parameterBuilder.addClientId(this.config.authOptions.clientId);
            parameterBuilder.addScopes(request.scopes);
            parameterBuilder.addGrantType(GrantType.JWT_BEARER);
            parameterBuilder.addClientInfo();
            var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
            parameterBuilder.addCorrelationId(correlationId);
            parameterBuilder.addRequestTokenUse(AADServerParamKeys.ON_BEHALF_OF);
            parameterBuilder.addOboAssertion(request.oboAssertion);
            if (this.config.clientCredentials.clientSecret) {
                parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
            }
            if (this.config.clientCredentials.clientAssertion) {
                var clientAssertion = this.config.clientCredentials.clientAssertion;
                parameterBuilder.addClientAssertion(clientAssertion.assertion);
                parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
            }
            return parameterBuilder.createQueryString();
        };
        return OnBehalfOfClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var SilentFlowClient = /** @class */ (function (_super) {
        __extends$1(SilentFlowClient, _super);
        function SilentFlowClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Retrieves a token from cache if it is still valid, or uses the cached refresh token to renew
         * the given token and returns the renewed token
         * @param request
         */
        SilentFlowClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var e_1, refreshTokenClient;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, this.acquireCachedToken(request)];
                        case 1: return [2 /*return*/, _a.sent()];
                        case 2:
                            e_1 = _a.sent();
                            if (e_1 instanceof ClientAuthError && e_1.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {
                                refreshTokenClient = new RefreshTokenClient(this.config);
                                return [2 /*return*/, refreshTokenClient.acquireTokenByRefreshToken(request)];
                            }
                            else {
                                throw e_1;
                            }
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Retrieves token from cache or throws an error if it must be refreshed.
         * @param request
         */
        SilentFlowClient.prototype.acquireCachedToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var requestScopes, environment, cacheRecord;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            // Cannot renew token if no request object is given.
                            if (!request) {
                                throw ClientConfigurationError.createEmptyTokenRequestError();
                            }
                            // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
                            if (!request.account) {
                                throw ClientAuthError.createNoAccountInSilentRequestError();
                            }
                            requestScopes = new ScopeSet(request.scopes || []);
                            environment = request.authority || Authority.generateEnvironmentFromAuthority(this.authority);
                            cacheRecord = this.cacheManager.readCacheRecord(request.account, this.config.authOptions.clientId, requestScopes, environment);
                            if (!this.isRefreshRequired(request, cacheRecord.accessToken)) return [3 /*break*/, 1];
                            throw ClientAuthError.createRefreshRequiredError();
                        case 1:
                            if (this.config.serverTelemetryManager) {
                                this.config.serverTelemetryManager.incrementCacheHits();
                            }
                            return [4 /*yield*/, this.generateResultFromCacheRecord(cacheRecord, request.resourceRequestMethod, request.resourceRequestUri)];
                        case 2: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * Helper function to build response object from the CacheRecord
         * @param cacheRecord
         */
        SilentFlowClient.prototype.generateResultFromCacheRecord = function (cacheRecord, resourceRequestMethod, resourceRequestUri) {
            return __awaiter$1(this, void 0, void 0, function () {
                var idTokenObj;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (cacheRecord.idToken) {
                                idTokenObj = new AuthToken(cacheRecord.idToken.secret, this.config.cryptoInterface);
                            }
                            return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, idTokenObj, undefined, resourceRequestMethod, resourceRequestUri)];
                        case 1: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        /**
         * Given a request object and an accessTokenEntity determine if the accessToken needs to be refreshed
         * @param request
         * @param cachedAccessToken
         */
        SilentFlowClient.prototype.isRefreshRequired = function (request, cachedAccessToken) {
            if (request.forceRefresh || request.claims) {
                // Must refresh due to request parameters
                return true;
            }
            else if (!cachedAccessToken || TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
                // Must refresh due to expired or non-existent access_token
                return true;
            }
            return false;
        };
        return SilentFlowClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Oauth2.0 Password grant client
     * Note: We are only supporting public clients for password grant and for purely testing purposes
     */
    var UsernamePasswordClient = /** @class */ (function (_super) {
        __extends$1(UsernamePasswordClient, _super);
        function UsernamePasswordClient(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * API to acquire a token by passing the username and password to the service in exchage of credentials
         * password_grant
         * @param request
         */
        UsernamePasswordClient.prototype.acquireToken = function (request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var response, responseHandler, tokenResponse;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.logger.info("in acquireToken call");
                            return [4 /*yield*/, this.executeTokenRequest(this.authority, request)];
                        case 1:
                            response = _a.sent();
                            responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
                            // Validate response. This function throws a server error if an error is returned by the server.
                            responseHandler.validateTokenResponse(response.body);
                            tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority);
                            return [2 /*return*/, tokenResponse];
                    }
                });
            });
        };
        /**
         * Executes POST request to token endpoint
         * @param authority
         * @param request
         */
        UsernamePasswordClient.prototype.executeTokenRequest = function (authority, request) {
            return __awaiter$1(this, void 0, void 0, function () {
                var thumbprint, requestBody, headers;
                return __generator$1(this, function (_a) {
                    thumbprint = {
                        clientId: this.config.authOptions.clientId,
                        authority: authority.canonicalAuthority,
                        scopes: request.scopes
                    };
                    requestBody = this.createTokenRequestBody(request);
                    headers = this.createDefaultTokenRequestHeaders();
                    return [2 /*return*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
                });
            });
        };
        /**
         * Generates a map for all the params to be sent to the service
         * @param request
         */
        UsernamePasswordClient.prototype.createTokenRequestBody = function (request) {
            var parameterBuilder = new RequestParameterBuilder();
            parameterBuilder.addClientId(this.config.authOptions.clientId);
            parameterBuilder.addUsername(request.username);
            parameterBuilder.addPassword(request.password);
            parameterBuilder.addScopes(request.scopes);
            parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
            parameterBuilder.addClientInfo();
            var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
            parameterBuilder.addCorrelationId(correlationId);
            if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
                parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
            }
            return parameterBuilder.createQueryString();
        };
        return UsernamePasswordClient;
    }(BaseClient));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var AuthorityFactory = /** @class */ (function () {
        function AuthorityFactory() {
        }
        /**
         * Create an authority object of the correct type based on the url
         * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)
         *
         * Also performs endpoint discovery.
         *
         * @param authorityUri
         * @param networkClient
         * @param protocolMode
         */
        AuthorityFactory.createDiscoveredInstance = function (authorityUri, networkClient, protocolMode) {
            return __awaiter$1(this, void 0, void 0, function () {
                var acquireTokenAuthority, e_1;
                return __generator$1(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            acquireTokenAuthority = AuthorityFactory.createInstance(authorityUri, networkClient, protocolMode);
                            if (acquireTokenAuthority.discoveryComplete()) {
                                return [2 /*return*/, acquireTokenAuthority];
                            }
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, acquireTokenAuthority.resolveEndpointsAsync()];
                        case 2:
                            _a.sent();
                            return [2 /*return*/, acquireTokenAuthority];
                        case 3:
                            e_1 = _a.sent();
                            throw ClientAuthError.createEndpointDiscoveryIncompleteError(e_1);
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Create an authority object of the correct type based on the url
         * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)
         *
         * Does not perform endpoint discovery.
         *
         * @param authorityUrl
         * @param networkInterface
         * @param protocolMode
         */
        AuthorityFactory.createInstance = function (authorityUrl, networkInterface, protocolMode) {
            // Throw error if authority url is empty
            if (StringUtils.isEmpty(authorityUrl)) {
                throw ClientConfigurationError.createUrlEmptyError();
            }
            return new Authority(authorityUrl, networkInterface, protocolMode);
        };
        return AuthorityFactory;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var ServerTelemetryEntity = /** @class */ (function () {
        function ServerTelemetryEntity() {
            this.failedRequests = [];
            this.errors = [];
            this.cacheHits = 0;
        }
        /**
         * validates if a given cache entry is "Telemetry", parses <key,value>
         * @param key
         * @param entity
         */
        ServerTelemetryEntity.isServerTelemetryEntity = function (key, entity) {
            var validateKey = key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0;
            var validateEntity = true;
            if (entity) {
                validateEntity =
                    entity.hasOwnProperty("failedRequests") &&
                    entity.hasOwnProperty("errors") &&
                    entity.hasOwnProperty("cacheHits");
            }
            return validateKey && validateEntity;
        };
        return ServerTelemetryEntity;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var ThrottlingEntity = /** @class */ (function () {
        function ThrottlingEntity() {
        }
        /**
         * validates if a given cache entry is "Throttling", parses <key,value>
         * @param key
         * @param entity
         */
        ThrottlingEntity.isThrottlingEntity = function (key, entity) {
            var validateKey = false;
            if (key) {
                validateKey = key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0;
            }
            var validateEntity = true;
            if (entity) {
                validateEntity = entity.hasOwnProperty("throttleTime");
            }
            return validateKey && validateEntity;
        };
        return ThrottlingEntity;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var ServerTelemetryManager = /** @class */ (function () {
        function ServerTelemetryManager(telemetryRequest, cacheManager) {
            this.cacheManager = cacheManager;
            this.apiId = telemetryRequest.apiId;
            this.correlationId = telemetryRequest.correlationId;
            this.forceRefresh = telemetryRequest.forceRefresh || false;
            this.telemetryCacheKey = SERVER_TELEM_CONSTANTS.CACHE_KEY + Separators.CACHE_KEY_SEPARATOR + telemetryRequest.clientId;
        }
        /**
         * API to add MSER Telemetry to request
         */
        ServerTelemetryManager.prototype.generateCurrentRequestHeaderValue = function () {
            var forceRefreshInt = this.forceRefresh ? 1 : 0;
            var request = "" + this.apiId + SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR + forceRefreshInt;
            var platformFields = ""; // TODO: Determine what we want to include
            return [SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, request, platformFields].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
        };
        /**
         * API to add MSER Telemetry for the last failed request
         */
        ServerTelemetryManager.prototype.generateLastRequestHeaderValue = function () {
            var lastRequests = this.getLastRequests();
            var maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
            var failedRequests = lastRequests.failedRequests.slice(0, 2 * maxErrors).join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
            var errors = lastRequests.errors.slice(0, maxErrors).join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
            var errorCount = lastRequests.errors.length;
            // Indicate whether this header contains all data or partial data
            var overflow = maxErrors < errorCount ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;
            var platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
            return [SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, lastRequests.cacheHits, failedRequests, errors, platformFields].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
        };
        /**
         * API to cache token failures for MSER data capture
         * @param error
         */
        ServerTelemetryManager.prototype.cacheFailedRequest = function (error) {
            var lastRequests = this.getLastRequests();
            lastRequests.failedRequests.push(this.apiId, this.correlationId);
            if (!StringUtils.isEmpty(error.subError)) {
                lastRequests.errors.push(error.subError);
            }
            else if (!StringUtils.isEmpty(error.errorCode)) {
                lastRequests.errors.push(error.errorCode);
            }
            else if (!!error && error.toString()) {
                lastRequests.errors.push(error.toString());
            }
            else {
                lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR);
            }
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
            return;
        };
        /**
         * Update server telemetry cache entry by incrementing cache hit counter
         */
        ServerTelemetryManager.prototype.incrementCacheHits = function () {
            var lastRequests = this.getLastRequests();
            lastRequests.cacheHits += 1;
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
            return lastRequests.cacheHits;
        };
        /**
         * Get the server telemetry entity from cache or initialize a new one
         */
        ServerTelemetryManager.prototype.getLastRequests = function () {
            var initialValue = new ServerTelemetryEntity();
            var lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey);
            return lastRequests || initialValue;
        };
        /**
         * Remove server telemetry cache entry
         */
        ServerTelemetryManager.prototype.clearTelemetryCache = function () {
            var lastRequests = this.getLastRequests();
            var numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
            var errorCount = lastRequests.errors.length;
            if (numErrorsFlushed === errorCount) {
                // All errors were sent on last request, clear Telemetry cache
                this.cacheManager.removeItem(this.telemetryCacheKey);
            }
            else {
                // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
                var serverTelemEntity = new ServerTelemetryEntity();
                serverTelemEntity.failedRequests = lastRequests.failedRequests.slice(numErrorsFlushed * 2); // failedRequests contains 2 items for each error
                serverTelemEntity.errors = lastRequests.errors.slice(numErrorsFlushed);
                this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity);
            }
        };
        /**
         * Returns the maximum number of errors that can be flushed to the server in the next network request
         * @param serverTelemetryEntity
         */
        ServerTelemetryManager.maxErrorsToSend = function (serverTelemetryEntity) {
            var i;
            var maxErrors = 0;
            var dataSize = 0;
            var errorCount = serverTelemetryEntity.errors.length;
            for (i = 0; i < errorCount; i++) {
                // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
                var apiId = serverTelemetryEntity.failedRequests[2 * i] || Constants.EMPTY_STRING;
                var correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || Constants.EMPTY_STRING;
                var errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;
                // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
                dataSize += apiId.toString().length + correlationId.toString().length + errorCode.length + 3;
                if (dataSize < SERVER_TELEM_CONSTANTS.MAX_HEADER_BYTES) {
                    // Adding this entry to the header would still keep header size below the limit
                    maxErrors += 1;
                }
                else {
                    break;
                }
            }
            return maxErrors;
        };
        return ServerTelemetryManager;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Constants
     */
    var BrowserConstants = {
        // Interaction in progress cache value
        INTERACTION_IN_PROGRESS_VALUE: "interaction_in_progress",
        // Invalid grant error code
        INVALID_GRANT_ERROR: "invalid_grant",
        // Default popup window width
        POPUP_WIDTH: 483,
        // Default popup window height
        POPUP_HEIGHT: 600,
        // Default popup monitor poll interval in milliseconds
        POLL_INTERVAL_MS: 50,
        // msal-browser SKU
        MSAL_SKU: "msal.js.browser",
    };
    (function (BrowserCacheLocation) {
        BrowserCacheLocation["LocalStorage"] = "localStorage";
        BrowserCacheLocation["SessionStorage"] = "sessionStorage";
        BrowserCacheLocation["MemoryStorage"] = "memoryStorage";
    })(exports.BrowserCacheLocation || (exports.BrowserCacheLocation = {}));
    /**
     * HTTP Request types supported by MSAL.
     */
    var HTTP_REQUEST_TYPE;
    (function (HTTP_REQUEST_TYPE) {
        HTTP_REQUEST_TYPE["GET"] = "GET";
        HTTP_REQUEST_TYPE["POST"] = "POST";
    })(HTTP_REQUEST_TYPE || (HTTP_REQUEST_TYPE = {}));
    /**
     * Temporary cache keys for MSAL, deleted after any request.
     */
    var TemporaryCacheKeys;
    (function (TemporaryCacheKeys) {
        TemporaryCacheKeys["AUTHORITY"] = "authority";
        TemporaryCacheKeys["ACQUIRE_TOKEN_ACCOUNT"] = "acquireToken.account";
        TemporaryCacheKeys["SESSION_STATE"] = "session.state";
        TemporaryCacheKeys["REQUEST_STATE"] = "request.state";
        TemporaryCacheKeys["NONCE_IDTOKEN"] = "nonce.id_token";
        TemporaryCacheKeys["ORIGIN_URI"] = "request.origin";
        TemporaryCacheKeys["RENEW_STATUS"] = "token.renew.status";
        TemporaryCacheKeys["URL_HASH"] = "urlHash";
        TemporaryCacheKeys["REQUEST_PARAMS"] = "request.params";
        TemporaryCacheKeys["SCOPES"] = "scopes";
        TemporaryCacheKeys["INTERACTION_STATUS_KEY"] = "interaction.status";
    })(TemporaryCacheKeys || (TemporaryCacheKeys = {}));
    /**
     * API Codes for Telemetry purposes.
     * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
     * 0-99 Silent Flow
     * 800-899 Auth Code Flow
     */
    var ApiId;
    (function (ApiId) {
        ApiId[ApiId["acquireTokenRedirect"] = 861] = "acquireTokenRedirect";
        ApiId[ApiId["acquireTokenPopup"] = 862] = "acquireTokenPopup";
        ApiId[ApiId["ssoSilent"] = 863] = "ssoSilent";
        ApiId[ApiId["acquireTokenSilent_authCode"] = 864] = "acquireTokenSilent_authCode";
        ApiId[ApiId["handleRedirectPromise"] = 865] = "handleRedirectPromise";
        ApiId[ApiId["acquireTokenSilent_silentFlow"] = 61] = "acquireTokenSilent_silentFlow";
    })(ApiId || (ApiId = {}));
    (function (InteractionType) {
        InteractionType["Redirect"] = "redirect";
        InteractionType["Popup"] = "popup";
        InteractionType["Silent"] = "silent";
    })(exports.InteractionType || (exports.InteractionType = {}));
    var DEFAULT_REQUEST = {
        scopes: [Constants.OPENID_SCOPE, Constants.PROFILE_SCOPE]
    };
    // JWK Key Format string (Type MUST be defined for window crypto APIs)
    var KEY_FORMAT_JWK = "jwk";

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility class for math specific functions in browser.
     */
    var MathUtils = /** @class */ (function () {
        function MathUtils() {
        }
        /**
         * Decimal to Hex
         *
         * @param num
         */
        MathUtils.decimalToHex = function (num) {
            var hex = num.toString(16);
            while (hex.length < 2) {
                hex = "0" + hex;
            }
            return hex;
        };
        return MathUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var GuidGenerator = /** @class */ (function () {
        function GuidGenerator(cryptoObj) {
            this.cryptoObj = cryptoObj;
        }
        /*
         * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or
         * pseudo-random numbers.
         * The algorithm is as follows:
         *     Set the two most significant bits (bits 6 and 7) of the
         *        clock_seq_hi_and_reserved to zero and one, respectively.
         *     Set the four most significant bits (bits 12 through 15) of the
         *        time_hi_and_version field to the 4-bit version number from
         *        Section 4.1.3. Version4
         *     Set all the other bits to randomly (or pseudo-randomly) chosen
         *     values.
         * UUID                   = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node
         * time-low               = 4hexOctet
         * time-mid               = 2hexOctet
         * time-high-and-version  = 2hexOctet
         * clock-seq-and-reserved = hexOctet:
         * clock-seq-low          = hexOctet
         * node                   = 6hexOctet
         * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
         * y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10
         * y values are 8, 9, A, B
         */
        GuidGenerator.prototype.generateGuid = function () {
            try {
                var buffer = new Uint8Array(16);
                this.cryptoObj.getRandomValues(buffer);
                // buffer[6] and buffer[7] represents the time_hi_and_version field. We will set the four most significant bits (4 through 7) of buffer[6] to represent decimal number 4 (UUID version number).
                buffer[6] |= 0x40; // buffer[6] | 01000000 will set the 6 bit to 1.
                buffer[6] &= 0x4f; // buffer[6] & 01001111 will set the 4, 5, and 7 bit to 0 such that bits 4-7 == 0100 = "4".
                // buffer[8] represents the clock_seq_hi_and_reserved field. We will set the two most significant bits (6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively.
                buffer[8] |= 0x80; // buffer[8] | 10000000 will set the 7 bit to 1.
                buffer[8] &= 0xbf; // buffer[8] & 10111111 will set the 6 bit to 0.
                return MathUtils.decimalToHex(buffer[0]) + MathUtils.decimalToHex(buffer[1])
                    + MathUtils.decimalToHex(buffer[2]) + MathUtils.decimalToHex(buffer[3])
                    + "-" + MathUtils.decimalToHex(buffer[4]) + MathUtils.decimalToHex(buffer[5])
                    + "-" + MathUtils.decimalToHex(buffer[6]) + MathUtils.decimalToHex(buffer[7])
                    + "-" + MathUtils.decimalToHex(buffer[8]) + MathUtils.decimalToHex(buffer[9])
                    + "-" + MathUtils.decimalToHex(buffer[10]) + MathUtils.decimalToHex(buffer[11])
                    + MathUtils.decimalToHex(buffer[12]) + MathUtils.decimalToHex(buffer[13])
                    + MathUtils.decimalToHex(buffer[14]) + MathUtils.decimalToHex(buffer[15]);
            }
            catch (err) {
                var guidHolder = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
                var hex = "0123456789abcdef";
                var r = 0;
                var guidResponse = "";
                for (var i = 0; i < 36; i++) {
                    if (guidHolder[i] !== "-" && guidHolder[i] !== "4") {
                        // each x and y needs to be random
                        r = Math.random() * 16 | 0;
                    }
                    if (guidHolder[i] === "x") {
                        guidResponse += hex[r];
                    }
                    else if (guidHolder[i] === "y") {
                        // clock-seq-and-reserved first hex is filtered and remaining hex values are random
                        r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
                        r |= 0x8; // set pos 3 to 1 as 1???
                        guidResponse += hex[r];
                    }
                    else {
                        guidResponse += guidHolder[i];
                    }
                }
                return guidResponse;
            }
        };
        /**
         * verifies if a string is  GUID
         * @param guid
         */
        GuidGenerator.isGuid = function (guid) {
            var regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
            return regexGuid.test(guid);
        };
        return GuidGenerator;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility functions for strings in a browser. See here for implementation details:
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_JavaScript's_UTF-16_%3E_UTF-8_%3E_base64
     */
    var BrowserStringUtils = /** @class */ (function () {
        function BrowserStringUtils() {
        }
        /**
         * Converts string to Uint8Array
         * @param sDOMStr
         */
        BrowserStringUtils.stringToUtf8Arr = function (sDOMStr) {
            var nChr;
            var nArrLen = 0;
            var nStrLen = sDOMStr.length;
            /* mapping... */
            for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) {
                nChr = sDOMStr.charCodeAt(nMapIdx);
                nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6;
            }
            var aBytes = new Uint8Array(nArrLen);
            /* transcription... */
            for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) {
                nChr = sDOMStr.charCodeAt(nChrIdx);
                if (nChr < 128) {
                    /* one byte */
                    aBytes[nIdx++] = nChr;
                }
                else if (nChr < 0x800) {
                    /* two bytes */
                    aBytes[nIdx++] = 192 + (nChr >>> 6);
                    aBytes[nIdx++] = 128 + (nChr & 63);
                }
                else if (nChr < 0x10000) {
                    /* three bytes */
                    aBytes[nIdx++] = 224 + (nChr >>> 12);
                    aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
                    aBytes[nIdx++] = 128 + (nChr & 63);
                }
                else if (nChr < 0x200000) {
                    /* four bytes */
                    aBytes[nIdx++] = 240 + (nChr >>> 18);
                    aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
                    aBytes[nIdx++] = 128 + (nChr & 63);
                }
                else if (nChr < 0x4000000) {
                    /* five bytes */
                    aBytes[nIdx++] = 248 + (nChr >>> 24);
                    aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
                    aBytes[nIdx++] = 128 + (nChr & 63);
                }
                else /* if (nChr <= 0x7fffffff) */ {
                    /* six bytes */
                    aBytes[nIdx++] = 252 + (nChr >>> 30);
                    aBytes[nIdx++] = 128 + (nChr >>> 24 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
                    aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
                    aBytes[nIdx++] = 128 + (nChr & 63);
                }
            }
            return aBytes;
        };
        /**
         * Converst string to ArrayBuffer
         * @param dataString
         */
        BrowserStringUtils.stringToArrayBuffer = function (dataString) {
            var data = new ArrayBuffer(dataString.length);
            var dataView = new Uint8Array(data);
            for (var i = 0; i < dataString.length; i++) {
                dataView[i] = dataString.charCodeAt(i);
            }
            return data;
        };
        /**
         * Converts Uint8Array to a string
         * @param aBytes
         */
        BrowserStringUtils.utf8ArrToString = function (aBytes) {
            var sView = "";
            for (var nPart = void 0, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
                nPart = aBytes[nIdx];
                sView += String.fromCharCode(nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
                    /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */
                    (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
                    : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
                        (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
                        : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
                            (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
                            : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
                                (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
                                : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
                                    (nPart - 192 << 6) + aBytes[++nIdx] - 128
                                    : /* nPart < 127 ? */ /* one byte */
                                    nPart);
            }
            return sView;
        };
        return BrowserStringUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class which exposes APIs to encode plaintext to base64 encoded string. See here for implementation details:
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_JavaScript's_UTF-16_%3E_UTF-8_%3E_base64
     */
    var Base64Encode = /** @class */ (function () {
        function Base64Encode() {
        }
        /**
         * Returns URL Safe b64 encoded string from a plaintext string.
         * @param input
         */
        Base64Encode.prototype.urlEncode = function (input) {
            return encodeURIComponent(this.encode(input)
                .replace(/=/g, "")
                .replace(/\+/g, "-")
                .replace(/\//g, "_"));
        };
        /**
         * Returns URL Safe b64 encoded string from an int8Array.
         * @param inputArr
         */
        Base64Encode.prototype.urlEncodeArr = function (inputArr) {
            return this.base64EncArr(inputArr)
                .replace(/=/g, "")
                .replace(/\+/g, "-")
                .replace(/\//g, "_");
        };
        /**
         * Returns b64 encoded string from plaintext string.
         * @param input
         */
        Base64Encode.prototype.encode = function (input) {
            var inputUtf8Arr = BrowserStringUtils.stringToUtf8Arr(input);
            return this.base64EncArr(inputUtf8Arr);
        };
        /**
         * Base64 encode byte array
         * @param aBytes
         */
        Base64Encode.prototype.base64EncArr = function (aBytes) {
            var eqLen = (3 - (aBytes.length % 3)) % 3;
            var sB64Enc = "";
            for (var nMod3 = void 0, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
                nMod3 = nIdx % 3;
                /* Uncomment the following line in order to split the output in lines 76-character long: */
                /*
                 *if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
                 */
                nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
                if (nMod3 === 2 || aBytes.length - nIdx === 1) {
                    sB64Enc += String.fromCharCode(this.uint6ToB64(nUint24 >>> 18 & 63), this.uint6ToB64(nUint24 >>> 12 & 63), this.uint6ToB64(nUint24 >>> 6 & 63), this.uint6ToB64(nUint24 & 63));
                    nUint24 = 0;
                }
            }
            return eqLen === 0 ? sB64Enc : sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
        };
        /**
         * Base64 string to array encoding helper
         * @param nUint6
         */
        Base64Encode.prototype.uint6ToB64 = function (nUint6) {
            return nUint6 < 26 ?
                nUint6 + 65
                : nUint6 < 52 ?
                    nUint6 + 71
                    : nUint6 < 62 ?
                        nUint6 - 4
                        : nUint6 === 62 ?
                            43
                            : nUint6 === 63 ?
                                47
                                :
                                65;
        };
        return Base64Encode;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class which exposes APIs to decode base64 strings to plaintext. See here for implementation details:
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_JavaScript's_UTF-16_%3E_UTF-8_%3E_base64
     */
    var Base64Decode = /** @class */ (function () {
        function Base64Decode() {
        }
        /**
         * Returns a URL-safe plaintext decoded string from b64 encoded input.
         * @param input
         */
        Base64Decode.prototype.decode = function (input) {
            var encodedString = input.replace(/-/g, "+").replace(/_/g, "/");
            switch (encodedString.length % 4) {
                case 0:
                    break;
                case 2:
                    encodedString += "==";
                    break;
                case 3:
                    encodedString += "=";
                    break;
                default:
                    throw new Error("Invalid base64 string");
            }
            var inputUtf8Arr = this.base64DecToArr(encodedString);
            return BrowserStringUtils.utf8ArrToString(inputUtf8Arr);
        };
        /**
         * Decodes base64 into Uint8Array
         * @param base64String
         * @param nBlockSize
         */
        Base64Decode.prototype.base64DecToArr = function (base64String, nBlockSize) {
            var sB64Enc = base64String.replace(/[^A-Za-z0-9\+\/]/g, "");
            var nInLen = sB64Enc.length;
            var nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 >>> 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 >>> 2;
            var aBytes = new Uint8Array(nOutLen);
            for (var nMod3 = void 0, nMod4 = void 0, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
                nMod4 = nInIdx & 3;
                nUint24 |= this.b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
                if (nMod4 === 3 || nInLen - nInIdx === 1) {
                    for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
                        aBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
                    }
                    nUint24 = 0;
                }
            }
            return aBytes;
        };
        /**
         * Base64 string to array decoding helper
         * @param charNum
         */
        Base64Decode.prototype.b64ToUint6 = function (charNum) {
            return charNum > 64 && charNum < 91 ?
                charNum - 65
                : charNum > 96 && charNum < 123 ?
                    charNum - 71
                    : charNum > 47 && charNum < 58 ?
                        charNum + 4
                        : charNum === 43 ?
                            62
                            : charNum === 47 ?
                                63
                                :
                                0;
        };
        return Base64Decode;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * BrowserAuthErrorMessage class containing string constants used by error codes and messages.
     */
    var BrowserAuthErrorMessage = {
        pkceNotGenerated: {
            code: "pkce_not_created",
            desc: "The PKCE code challenge and verifier could not be generated."
        },
        cryptoDoesNotExist: {
            code: "crypto_nonexistent",
            desc: "The crypto object or function is not available."
        },
        httpMethodNotImplementedError: {
            code: "http_method_not_implemented",
            desc: "The HTTP method given has not been implemented in this library."
        },
        emptyNavigateUriError: {
            code: "empty_navigate_uri",
            desc: "Navigation URI is empty. Please check stack trace for more info."
        },
        hashEmptyError: {
            code: "hash_empty_error",
            desc: "Hash value cannot be processed because it is empty."
        },
        interactionInProgress: {
            code: "interaction_in_progress",
            desc: "Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API."
        },
        popUpWindowError: {
            code: "popup_window_error",
            desc: "Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser."
        },
        emptyWindowError: {
            code: "empty_window_error",
            desc: "window.open returned null or undefined window object."
        },
        userCancelledError: {
            code: "user_cancelled",
            desc: "User cancelled the flow."
        },
        monitorPopupTimeoutError: {
            code: "monitor_window_timeout",
            desc: "Token acquisition in popup failed due to timeout."
        },
        monitorIframeTimeoutError: {
            code: "monitor_window_timeout",
            desc: "Token acquisition in iframe failed due to timeout."
        },
        redirectInIframeError: {
            code: "redirect_in_iframe",
            desc: "Code flow is not supported inside an iframe. Please ensure you are using MSAL.js in a top frame of the window if using the redirect APIs, or use the popup APIs."
        },
        blockTokenRequestsInHiddenIframeError: {
            code: "block_iframe_reload",
            desc: "Request was blocked inside an iframe because MSAL detected an authentication response. Please ensure monitorWindowForHash was called."
        },
        iframeClosedPrematurelyError: {
            code: "iframe_closed_prematurely",
            desc: "The iframe being monitored was closed prematurely."
        },
        silentSSOInsufficientInfoError: {
            code: "silent_sso_error",
            desc: "Silent SSO could not be completed - insufficient information was provided. Please provide either a loginHint or sid."
        },
        silentPromptValueError: {
            code: "silent_prompt_value_error",
            desc: "The value given for the prompt value is not valid for silent requests - must be set to 'none'."
        },
        tokenRequestCacheError: {
            code: "token_request_cache_error",
            desc: "The token request could not be fetched from the cache correctly."
        },
        invalidCacheType: {
            code: "invalid_cache_type",
            desc: "Invalid cache type"
        },
        notInBrowserEnvironment: {
            code: "non_browser_environment",
            desc: "Login and token requests are not supported in non-browser environments."
        }
    };
    /**
     * Browser library error class thrown by the MSAL.js library for SPAs
     */
    var BrowserAuthError = /** @class */ (function (_super) {
        __extends(BrowserAuthError, _super);
        function BrowserAuthError(errorCode, errorMessage) {
            var _this = _super.call(this, errorCode, errorMessage) || this;
            Object.setPrototypeOf(_this, BrowserAuthError.prototype);
            _this.name = "BrowserAuthError";
            return _this;
        }
        /**
         * Creates an error thrown when PKCE is not implemented.
         * @param errDetail
         */
        BrowserAuthError.createPkceNotGeneratedError = function (errDetail) {
            return new BrowserAuthError(BrowserAuthErrorMessage.pkceNotGenerated.code, BrowserAuthErrorMessage.pkceNotGenerated.desc + " Detail:" + errDetail);
        };
        /**
         * Creates an error thrown when the crypto object is unavailable.
         * @param errDetail
         */
        BrowserAuthError.createCryptoNotAvailableError = function (errDetail) {
            return new BrowserAuthError(BrowserAuthErrorMessage.cryptoDoesNotExist.code, BrowserAuthErrorMessage.cryptoDoesNotExist.desc + " Detail:" + errDetail);
        };
        /**
         * Creates an error thrown when an HTTP method hasn't been implemented by the browser class.
         * @param method
         */
        BrowserAuthError.createHttpMethodNotImplementedError = function (method) {
            return new BrowserAuthError(BrowserAuthErrorMessage.httpMethodNotImplementedError.code, BrowserAuthErrorMessage.httpMethodNotImplementedError.desc + " Given Method: " + method);
        };
        /**
         * Creates an error thrown when the navigation URI is empty.
         */
        BrowserAuthError.createEmptyNavigationUriError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.emptyNavigateUriError.code, BrowserAuthErrorMessage.emptyNavigateUriError.desc);
        };
        /**
         * Creates an error thrown when the hash string value is unexpectedly empty.
         * @param hashValue
         */
        BrowserAuthError.createEmptyHashError = function (hashValue) {
            return new BrowserAuthError(BrowserAuthErrorMessage.hashEmptyError.code, BrowserAuthErrorMessage.hashEmptyError.desc + " Given Url: " + hashValue);
        };
        /**
         * Creates an error thrown when a browser interaction (redirect or popup) is in progress.
         */
        BrowserAuthError.createInteractionInProgressError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.interactionInProgress.code, BrowserAuthErrorMessage.interactionInProgress.desc);
        };
        /**
         * Creates an error thrown when the popup window could not be opened.
         * @param errDetail
         */
        BrowserAuthError.createPopupWindowError = function (errDetail) {
            var errorMessage = BrowserAuthErrorMessage.popUpWindowError.desc;
            errorMessage = !StringUtils.isEmpty(errDetail) ? errorMessage + " Details: " + errDetail : errorMessage;
            return new BrowserAuthError(BrowserAuthErrorMessage.popUpWindowError.code, errorMessage);
        };
        /**
         * Creates an error thrown when window.open returns an empty window object.
         * @param errDetail
         */
        BrowserAuthError.createEmptyWindowCreatedError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.emptyWindowError.code, BrowserAuthErrorMessage.emptyWindowError.desc);
        };
        /**
         * Creates an error thrown when the user closes a popup.
         */
        BrowserAuthError.createUserCancelledError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.userCancelledError.code, BrowserAuthErrorMessage.userCancelledError.desc);
        };
        /**
         * Creates an error thrown when monitorPopupFromHash times out for a given popup.
         */
        BrowserAuthError.createMonitorPopupTimeoutError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.monitorPopupTimeoutError.code, BrowserAuthErrorMessage.monitorPopupTimeoutError.desc);
        };
        /**
         * Creates an error thrown when monitorIframeFromHash times out for a given iframe.
         */
        BrowserAuthError.createMonitorIframeTimeoutError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.monitorIframeTimeoutError.code, BrowserAuthErrorMessage.monitorIframeTimeoutError.desc);
        };
        /**
         * Creates an error thrown when navigateWindow is called inside an iframe.
         * @param windowParentCheck
         */
        BrowserAuthError.createRedirectInIframeError = function (windowParentCheck) {
            return new BrowserAuthError(BrowserAuthErrorMessage.redirectInIframeError.code, BrowserAuthErrorMessage.redirectInIframeError.desc + " (window.parent !== window) => " + windowParentCheck);
        };
        /**
         * Creates an error thrown when an auth reload is done inside an iframe.
         */
        BrowserAuthError.createBlockReloadInHiddenIframeError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.blockTokenRequestsInHiddenIframeError.code, BrowserAuthErrorMessage.blockTokenRequestsInHiddenIframeError.desc);
        };
        /**
         * Creates an error thrown when an iframe is found to be closed before the timeout is reached.
         */
        BrowserAuthError.createIframeClosedPrematurelyError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.iframeClosedPrematurelyError.code, BrowserAuthErrorMessage.iframeClosedPrematurelyError.desc);
        };
        /**
         * Creates an error thrown when the login_hint, sid or account object is not provided in the ssoSilent API.
         */
        BrowserAuthError.createSilentSSOInsufficientInfoError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.silentSSOInsufficientInfoError.code, BrowserAuthErrorMessage.silentSSOInsufficientInfoError.desc);
        };
        /**
         * Creates an error thrown when a given prompt value is invalid for silent requests.
         */
        BrowserAuthError.createSilentPromptValueError = function (givenPrompt) {
            return new BrowserAuthError(BrowserAuthErrorMessage.silentPromptValueError.code, BrowserAuthErrorMessage.silentPromptValueError.desc + " Given value: " + givenPrompt);
        };
        /**
         * Creates an error thrown when the token request could not be retrieved from the cache
         * @param errDetail
         */
        BrowserAuthError.createTokenRequestCacheError = function (errDetail) {
            return new BrowserAuthError(BrowserAuthErrorMessage.tokenRequestCacheError.code, BrowserAuthErrorMessage.tokenRequestCacheError.desc + " Error Detail: " + errDetail);
        };
        /**
         * Creates an error thrown if cache type is invalid.
         */
        BrowserAuthError.createInvalidCacheTypeError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.invalidCacheType.code, "" + BrowserAuthErrorMessage.invalidCacheType.desc);
        };
        /**
         * Create an error thrown when login and token requests are made from a non-browser environment
         */
        BrowserAuthError.createNonBrowserEnvironmentError = function () {
            return new BrowserAuthError(BrowserAuthErrorMessage.notInBrowserEnvironment.code, BrowserAuthErrorMessage.notInBrowserEnvironment.desc);
        };
        return BrowserAuthError;
    }(AuthError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Constant byte array length
    var RANDOM_BYTE_ARR_LENGTH = 32;
    /**
     * Class which exposes APIs to generate PKCE codes and code verifiers.
     */
    var PkceGenerator = /** @class */ (function () {
        function PkceGenerator(cryptoObj) {
            this.base64Encode = new Base64Encode();
            this.cryptoObj = cryptoObj;
        }
        /**
         * Generates PKCE Codes. See the RFC for more information: https://tools.ietf.org/html/rfc7636
         */
        PkceGenerator.prototype.generateCodes = function () {
            return __awaiter(this, void 0, void 0, function () {
                var codeVerifier, codeChallenge;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            codeVerifier = this.generateCodeVerifier();
                            return [4 /*yield*/, this.generateCodeChallengeFromVerifier(codeVerifier)];
                        case 1:
                            codeChallenge = _a.sent();
                            return [2 /*return*/, {
                                verifier: codeVerifier,
                                challenge: codeChallenge
                            }];
                    }
                });
            });
        };
        /**
         * Generates a random 32 byte buffer and returns the base64
         * encoded string to be used as a PKCE Code Verifier
         */
        PkceGenerator.prototype.generateCodeVerifier = function () {
            try {
                // Generate random values as utf-8
                var buffer = new Uint8Array(RANDOM_BYTE_ARR_LENGTH);
                this.cryptoObj.getRandomValues(buffer);
                // encode verifier as base64
                var pkceCodeVerifierB64 = this.base64Encode.urlEncodeArr(buffer);
                return pkceCodeVerifierB64;
            }
            catch (e) {
                throw BrowserAuthError.createPkceNotGeneratedError(e);
            }
        };
        /**
         * Creates a base64 encoded PKCE Code Challenge string from the
         * hash created from the PKCE Code Verifier supplied
         */
        PkceGenerator.prototype.generateCodeChallengeFromVerifier = function (pkceCodeVerifier) {
            return __awaiter(this, void 0, void 0, function () {
                var pkceHashedCodeVerifier, e_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, this.cryptoObj.sha256Digest(pkceCodeVerifier)];
                        case 1:
                            pkceHashedCodeVerifier = _a.sent();
                            // encode hash as base64
                            return [2 /*return*/, this.base64Encode.urlEncodeArr(new Uint8Array(pkceHashedCodeVerifier))];
                        case 2:
                            e_1 = _a.sent();
                            throw BrowserAuthError.createPkceNotGeneratedError(e_1);
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        return PkceGenerator;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * See here for more info on RsaHashedKeyGenParams: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
     */
    // RSA KeyGen Algorithm
    var PKCS1_V15_KEYGEN_ALG = "RSASSA-PKCS1-v1_5";
    // SHA-256 hashing algorithm
    var S256_HASH_ALG = "SHA-256";
    // MOD length for PoP tokens
    var MODULUS_LENGTH = 2048;
    // Public Exponent
    var PUBLIC_EXPONENT = new Uint8Array([0x01, 0x00, 0x01]);
    /**
     * This class implements functions used by the browser library to perform cryptography operations such as
     * hashing and encoding. It also has helper functions to validate the availability of specific APIs.
     */
    var BrowserCrypto = /** @class */ (function () {
        function BrowserCrypto() {
            if (!(this.hasCryptoAPI())) {
                throw BrowserAuthError.createCryptoNotAvailableError("Browser crypto or msCrypto object not available.");
            }
            this._keygenAlgorithmOptions = {
                name: PKCS1_V15_KEYGEN_ALG,
                hash: S256_HASH_ALG,
                modulusLength: MODULUS_LENGTH,
                publicExponent: PUBLIC_EXPONENT
            };
        }
        /**
         * Returns a sha-256 hash of the given dataString as an ArrayBuffer.
         * @param dataString
         */
        BrowserCrypto.prototype.sha256Digest = function (dataString) {
            return __awaiter(this, void 0, void 0, function () {
                var data;
                return __generator(this, function (_a) {
                    data = BrowserStringUtils.stringToUtf8Arr(dataString);
                    return [2 /*return*/, this.hasIECrypto() ? this.getMSCryptoDigest(S256_HASH_ALG, data) : this.getSubtleCryptoDigest(S256_HASH_ALG, data)];
                });
            });
        };
        /**
         * Populates buffer with cryptographically random values.
         * @param dataBuffer
         */
        BrowserCrypto.prototype.getRandomValues = function (dataBuffer) {
            var cryptoObj = window["msCrypto"] || window.crypto;
            if (!cryptoObj.getRandomValues) {
                throw BrowserAuthError.createCryptoNotAvailableError("getRandomValues does not exist.");
            }
            cryptoObj.getRandomValues(dataBuffer);
        };
        /**
         * Generates a keypair based on current keygen algorithm config.
         * @param extractable
         * @param usages
         */
        BrowserCrypto.prototype.generateKeyPair = function (extractable, usages) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, (this.hasIECrypto() ?
                        this.msCryptoGenerateKey(extractable, usages)
                        : window.crypto.subtle.generateKey(this._keygenAlgorithmOptions, extractable, usages))];
                });
            });
        };
        /**
         * Export key as Json Web Key (JWK)
         * @param key
         * @param format
         */
        BrowserCrypto.prototype.exportJwk = function (key) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.hasIECrypto() ? this.msCryptoExportJwk(key) : window.crypto.subtle.exportKey(KEY_FORMAT_JWK, key)];
                });
            });
        };
        /**
         * Imports key as Json Web Key (JWK), can set extractable and usages.
         * @param key
         * @param format
         * @param extractable
         * @param usages
         */
        BrowserCrypto.prototype.importJwk = function (key, extractable, usages) {
            return __awaiter(this, void 0, void 0, function () {
                var keyString, keyBuffer;
                return __generator(this, function (_a) {
                    keyString = BrowserCrypto.getJwkString(key);
                    keyBuffer = BrowserStringUtils.stringToArrayBuffer(keyString);
                    return [2 /*return*/, this.hasIECrypto() ?
                        this.msCryptoImportKey(keyBuffer, extractable, usages)
                        : window.crypto.subtle.importKey(KEY_FORMAT_JWK, key, this._keygenAlgorithmOptions, extractable, usages)];
                });
            });
        };
        /**
         * Signs given data with given key
         * @param key
         * @param data
         */
        BrowserCrypto.prototype.sign = function (key, data) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.hasIECrypto() ?
                        this.msCryptoSign(key, data)
                        : window.crypto.subtle.sign(this._keygenAlgorithmOptions, key, data)];
                });
            });
        };
        /**
         * Check whether IE crypto or other browser cryptography is available.
         */
        BrowserCrypto.prototype.hasCryptoAPI = function () {
            return this.hasIECrypto() || this.hasBrowserCrypto();
        };
        /**
         * Checks whether IE crypto (AKA msCrypto) is available.
         */
        BrowserCrypto.prototype.hasIECrypto = function () {
            return "msCrypto" in window;
        };
        /**
         * Check whether browser crypto is available.
         */
        BrowserCrypto.prototype.hasBrowserCrypto = function () {
            return "crypto" in window;
        };
        /**
         * Helper function for SHA digest.
         * @param algorithm
         * @param data
         */
        BrowserCrypto.prototype.getSubtleCryptoDigest = function (algorithm, data) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, window.crypto.subtle.digest(algorithm, data)];
                });
            });
        };
        /**
         * IE Helper function for SHA digest.
         * @param algorithm
         * @param data
         */
        BrowserCrypto.prototype.getMSCryptoDigest = function (algorithm, data) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var digestOperation = window["msCrypto"].subtle.digest(algorithm, data.buffer);
                        digestOperation.addEventListener("complete", function (e) {
                            resolve(e.target.result);
                        });
                        digestOperation.addEventListener("error", function (error) {
                            reject(error);
                        });
                    })];
                });
            });
        };
        /**
         * IE Helper function for generating a keypair
         * @param extractable
         * @param usages
         */
        BrowserCrypto.prototype.msCryptoGenerateKey = function (extractable, usages) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var msGenerateKey = window["msCrypto"].subtle.generateKey(_this._keygenAlgorithmOptions, extractable, usages);
                        msGenerateKey.addEventListener("complete", function (e) {
                            resolve(e.target.result);
                        });
                        msGenerateKey.addEventListener("error", function (error) {
                            reject(error);
                        });
                    })];
                });
            });
        };
        /**
         * IE Helper function for exportKey
         * @param key
         * @param format
         */
        BrowserCrypto.prototype.msCryptoExportJwk = function (key) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var msExportKey = window["msCrypto"].subtle.exportKey(KEY_FORMAT_JWK, key);
                        msExportKey.addEventListener("complete", function (e) {
                            var resultBuffer = e.target.result;
                            var resultString = BrowserStringUtils.utf8ArrToString(new Uint8Array(resultBuffer))
                                .replace(/\r/g, "")
                                .replace(/\n/g, "")
                                .replace(/\t/g, "")
                                .split(" ").join("")
                                .replace("\u0000", "");
                            try {
                                resolve(JSON.parse(resultString));
                            }
                            catch (e) {
                                reject(e);
                            }
                        });
                        msExportKey.addEventListener("error", function (error) {
                            reject(error);
                        });
                    })];
                });
            });
        };
        /**
         * IE Helper function for importKey
         * @param key
         * @param format
         * @param extractable
         * @param usages
         */
        BrowserCrypto.prototype.msCryptoImportKey = function (keyBuffer, extractable, usages) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var msImportKey = window["msCrypto"].subtle.importKey(KEY_FORMAT_JWK, keyBuffer, _this._keygenAlgorithmOptions, extractable, usages);
                        msImportKey.addEventListener("complete", function (e) {
                            resolve(e.target.result);
                        });
                        msImportKey.addEventListener("error", function (error) {
                            reject(error);
                        });
                    })];
                });
            });
        };
        /**
         * IE Helper function for sign JWT
         * @param key
         * @param data
         */
        BrowserCrypto.prototype.msCryptoSign = function (key, data) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        var msSign = window["msCrypto"].subtle.sign(_this._keygenAlgorithmOptions, key, data);
                        msSign.addEventListener("complete", function (e) {
                            resolve(e.target.result);
                        });
                        msSign.addEventListener("error", function (error) {
                            reject(error);
                        });
                    })];
                });
            });
        };
        /**
         * Returns stringified jwk.
         * @param jwk
         */
        BrowserCrypto.getJwkString = function (jwk) {
            return JSON.stringify(jwk, Object.keys(jwk).sort());
        };
        return BrowserCrypto;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Storage wrapper for IndexedDB storage in browsers: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
     */
    var DatabaseStorage = /** @class */ (function () {
        function DatabaseStorage(dbName, tableName, version) {
            this.dbName = dbName;
            this.tableName = tableName;
            this.version = version;
            this.dbOpen = false;
        }
        /**
         * Opens IndexedDB instance.
         */
        DatabaseStorage.prototype.open = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (resolve, reject) {
                        // TODO: Add timeouts?
                        var openDB = window.indexedDB.open(_this.dbName, _this.version);
                        openDB.addEventListener("upgradeneeded", function (e) {
                            e.target.result.createObjectStore(_this.tableName);
                        });
                        openDB.addEventListener("success", function (e) {
                            _this.db = e.target.result;
                            _this.dbOpen = true;
                            resolve();
                        });
                        openDB.addEventListener("error", function (error) { return reject(error); });
                    })];
                });
            });
        };
        /**
         * Retrieves item from IndexedDB instance.
         * @param key
         */
        DatabaseStorage.prototype.get = function (key) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!!this.dbOpen) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.open()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
                            // TODO: Add timeouts?
                            var transaction = _this.db.transaction([_this.tableName], "readonly");
                            var objectStore = transaction.objectStore(_this.tableName);
                            var dbGet = objectStore.get(key);
                            dbGet.addEventListener("success", function (e) { return resolve(e.target.result); });
                            dbGet.addEventListener("error", function (e) { return reject(e); });
                        })];
                    }
                });
            });
        };
        /**
         * Adds item to IndexedDB under given key
         * @param key
         * @param payload
         */
        DatabaseStorage.prototype.put = function (key, payload) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!!this.dbOpen) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.open()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
                            // TODO: Add timeouts?
                            var transaction = _this.db.transaction([_this.tableName], "readwrite");
                            var objectStore = transaction.objectStore(_this.tableName);
                            var dbPut = objectStore.put(payload, key);
                            dbPut.addEventListener("success", function (e) { return resolve(e.target.result); });
                            dbPut.addEventListener("error", function (e) { return reject(e); });
                        })];
                    }
                });
            });
        };
        return DatabaseStorage;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements MSAL's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
     * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
     */
    var CryptoOps = /** @class */ (function () {
        function CryptoOps() {
            // Browser crypto needs to be validated first before any other classes can be set.
            this.browserCrypto = new BrowserCrypto();
            this.b64Encode = new Base64Encode();
            this.b64Decode = new Base64Decode();
            this.guidGenerator = new GuidGenerator(this.browserCrypto);
            this.pkceGenerator = new PkceGenerator(this.browserCrypto);
            this.cache = new DatabaseStorage(CryptoOps.DB_NAME, CryptoOps.TABLE_NAME, CryptoOps.DB_VERSION);
        }
        /**
         * Creates a new random GUID - used to populate state and nonce.
         * @returns string (GUID)
         */
        CryptoOps.prototype.createNewGuid = function () {
            return this.guidGenerator.generateGuid();
        };
        /**
         * Encodes input string to base64.
         * @param input
         */
        CryptoOps.prototype.base64Encode = function (input) {
            return this.b64Encode.encode(input);
        };
        /**
         * Decodes input string from base64.
         * @param input
         */
        CryptoOps.prototype.base64Decode = function (input) {
            return this.b64Decode.decode(input);
        };
        /**
         * Generates PKCE codes used in Authorization Code Flow.
         */
        CryptoOps.prototype.generatePkceCodes = function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.pkceGenerator.generateCodes()];
                });
            });
        };
        /**
         * Generates a keypair, stores it and returns a thumbprint
         * @param resourceRequestMethod
         * @param resourceRequestUri
         */
        CryptoOps.prototype.getPublicKeyThumbprint = function (resourceRequestMethod, resourceRequestUri) {
            return __awaiter(this, void 0, void 0, function () {
                var keyPair, publicKeyJwk, pubKeyThumprintObj, publicJwkString, publicJwkBuffer, publicJwkHash, privateKeyJwk, unextractablePrivateKey;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.browserCrypto.generateKeyPair(CryptoOps.EXTRACTABLE, CryptoOps.POP_KEY_USAGES)];
                        case 1:
                            keyPair = _a.sent();
                            return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.publicKey)];
                        case 2:
                            publicKeyJwk = _a.sent();
                            pubKeyThumprintObj = {
                                e: publicKeyJwk.e,
                                kty: publicKeyJwk.kty,
                                n: publicKeyJwk.n
                            };
                            publicJwkString = BrowserCrypto.getJwkString(pubKeyThumprintObj);
                            return [4 /*yield*/, this.browserCrypto.sha256Digest(publicJwkString)];
                        case 3:
                            publicJwkBuffer = _a.sent();
                            publicJwkHash = this.b64Encode.urlEncodeArr(new Uint8Array(publicJwkBuffer));
                            return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.privateKey)];
                        case 4:
                            privateKeyJwk = _a.sent();
                            return [4 /*yield*/, this.browserCrypto.importJwk(privateKeyJwk, false, ["sign"])];
                        case 5:
                            unextractablePrivateKey = _a.sent();
                            // Store Keypair data in keystore
                            this.cache.put(publicJwkHash, {
                                privateKey: unextractablePrivateKey,
                                publicKey: keyPair.publicKey,
                                requestMethod: resourceRequestMethod,
                                requestUri: resourceRequestUri
                            });
                            return [2 /*return*/, publicJwkHash];
                    }
                });
            });
        };
        /**
         * Signs the given object as a jwt payload with private key retrieved by given kid.
         * @param payload
         * @param kid
         */
        CryptoOps.prototype.signJwt = function (payload, kid) {
            return __awaiter(this, void 0, void 0, function () {
                var cachedKeyPair, publicKeyJwk, publicKeyJwkString, header, encodedHeader, encodedPayload, tokenString, tokenBuffer, signatureBuffer, encodedSignature;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.cache.get(kid)];
                        case 1:
                            cachedKeyPair = _a.sent();
                            return [4 /*yield*/, this.browserCrypto.exportJwk(cachedKeyPair.publicKey)];
                        case 2:
                            publicKeyJwk = _a.sent();
                            publicKeyJwkString = BrowserCrypto.getJwkString(publicKeyJwk);
                            header = {
                                alg: publicKeyJwk.alg,
                                type: KEY_FORMAT_JWK
                            };
                            encodedHeader = this.b64Encode.urlEncode(JSON.stringify(header));
                            // Generate payload
                            payload.cnf = {
                                jwk: JSON.parse(publicKeyJwkString)
                            };
                            encodedPayload = this.b64Encode.urlEncode(JSON.stringify(payload));
                            tokenString = encodedHeader + "." + encodedPayload;
                            tokenBuffer = BrowserStringUtils.stringToArrayBuffer(tokenString);
                            return [4 /*yield*/, this.browserCrypto.sign(cachedKeyPair.privateKey, tokenBuffer)];
                        case 3:
                            signatureBuffer = _a.sent();
                            encodedSignature = this.b64Encode.urlEncodeArr(new Uint8Array(signatureBuffer));
                            return [2 /*return*/, tokenString + "." + encodedSignature];
                    }
                });
            });
        };
        CryptoOps.POP_KEY_USAGES = ["sign", "verify"];
        CryptoOps.EXTRACTABLE = true;
        CryptoOps.DB_VERSION = 1;
        CryptoOps.DB_NAME = "msal.db";
        CryptoOps.TABLE_NAME = CryptoOps.DB_NAME + ".keys";
        return CryptoOps;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * BrowserAuthErrorMessage class containing string constants used by error codes and messages.
     */
    var BrowserConfigurationAuthErrorMessage = {
        redirectUriNotSet: {
            code: "redirect_uri_empty",
            desc: "A redirect URI is required for all calls, and none has been set."
        },
        postLogoutUriNotSet: {
            code: "post_logout_uri_empty",
            desc: "A post logout redirect has not been set."
        },
        storageNotSupportedError: {
            code: "storage_not_supported",
            desc: "Given storage configuration option was not supported."
        },
        noRedirectCallbacksSet: {
            code: "no_redirect_callbacks",
            desc: "No redirect callbacks have been set. Please call setRedirectCallbacks() with the appropriate function arguments before continuing. " +
                "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
        },
        invalidCallbackObject: {
            code: "invalid_callback_object",
            desc: "The object passed for the callback was invalid. " +
                "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
        },
        stubPcaInstanceCalled: {
            code: "stubbed_public_client_application_called",
            desc: "Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider."
        },
        inMemRedirectUnavailable: {
            code: "in_mem_redirect_unavailable",
            desc: "Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."
        }
    };
    /**
     * Browser library error class thrown by the MSAL.js library for SPAs
     */
    var BrowserConfigurationAuthError = /** @class */ (function (_super) {
        __extends(BrowserConfigurationAuthError, _super);
        function BrowserConfigurationAuthError(errorCode, errorMessage) {
            var _this = _super.call(this, errorCode, errorMessage) || this;
            _this.name = "BrowserConfigurationAuthError";
            Object.setPrototypeOf(_this, BrowserConfigurationAuthError.prototype);
            return _this;
        }
        /**
         * Creates an error thrown when the redirect uri is empty (not set by caller)
         */
        BrowserConfigurationAuthError.createRedirectUriEmptyError = function () {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.redirectUriNotSet.code, BrowserConfigurationAuthErrorMessage.redirectUriNotSet.desc);
        };
        /**
         * Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
         */
        BrowserConfigurationAuthError.createPostLogoutRedirectUriEmptyError = function () {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.code, BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.desc);
        };
        /**
         * Creates error thrown when given storage location is not supported.
         * @param givenStorageLocation
         */
        BrowserConfigurationAuthError.createStorageNotSupportedError = function (givenStorageLocation) {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.storageNotSupportedError.code, BrowserConfigurationAuthErrorMessage.storageNotSupportedError.desc + " Given Location: " + givenStorageLocation);
        };
        /**
         * Creates error thrown when callback object is invalid.
         * @param callbackObject
         */
        BrowserConfigurationAuthError.createInvalidCallbackObjectError = function (callbackObject) {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.invalidCallbackObject.code, BrowserConfigurationAuthErrorMessage.invalidCallbackObject.desc + " Given value for callback function: " + callbackObject);
        };
        /**
         * Creates error thrown when redirect callbacks are not set before calling loginRedirect() or acquireTokenRedirect().
         */
        BrowserConfigurationAuthError.createRedirectCallbacksNotSetError = function () {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.code, BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.desc);
        };
        /**
         * Creates error thrown when the stub instance of PublicClientApplication is called.
         */
        BrowserConfigurationAuthError.createStubPcaInstanceCalledError = function () {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.code, BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.desc);
        };
        /*
         * Create an error thrown when in-memory storage is used and storeAuthStateInCookie=false.
         */
        BrowserConfigurationAuthError.createInMemoryRedirectUnavailableError = function () {
            return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.code, BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.desc);
        };
        return BrowserConfigurationAuthError;
    }(AuthError));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var BrowserStorage = /** @class */ (function () {
        function BrowserStorage(cacheLocation) {
            this.validateWindowStorage(cacheLocation);
            this.cacheLocation = cacheLocation;
        }
        Object.defineProperty(BrowserStorage.prototype, "windowStorage", {
            get: function () {
                if (!this._windowStorage) {
                    this._windowStorage = window[this.cacheLocation];
                }
                return this._windowStorage;
            },
            enumerable: true,
            configurable: true
        });
        BrowserStorage.prototype.validateWindowStorage = function (cacheLocation) {
            if (cacheLocation !== exports.BrowserCacheLocation.LocalStorage && cacheLocation !== exports.BrowserCacheLocation.SessionStorage) {
                throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
            }
            var storageSupported = !!window[cacheLocation];
            if (!storageSupported) {
                throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
            }
        };
        BrowserStorage.prototype.getItem = function (key) {
            return this.windowStorage.getItem(key);
        };
        BrowserStorage.prototype.setItem = function (key, value) {
            this.windowStorage.setItem(key, value);
        };
        BrowserStorage.prototype.removeItem = function (key) {
            this.windowStorage.removeItem(key);
        };
        BrowserStorage.prototype.getKeys = function () {
            return Object.keys(this.windowStorage);
        };
        BrowserStorage.prototype.containsKey = function (key) {
            return this.windowStorage.hasOwnProperty(key);
        };
        return BrowserStorage;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var MemoryStorage = /** @class */ (function () {
        function MemoryStorage() {
            this.cache = new Map();
        }
        MemoryStorage.prototype.getItem = function (key) {
            return this.cache.get(key) || null;
        };
        MemoryStorage.prototype.setItem = function (key, value) {
            this.cache.set(key, value);
        };
        MemoryStorage.prototype.removeItem = function (key) {
            this.cache.delete(key);
        };
        MemoryStorage.prototype.getKeys = function () {
            var cacheKeys = [];
            this.cache.forEach(function (value, key) {
                cacheKeys.push(key);
            });
            return cacheKeys;
        };
        MemoryStorage.prototype.containsKey = function (key) {
            return this.cache.has(key);
        };
        return MemoryStorage;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var BrowserProtocolUtils = /** @class */ (function () {
        function BrowserProtocolUtils() {
        }
        /**
         * Extracts the BrowserStateObject from the state string.
         * @param browserCrypto
         * @param state
         */
        BrowserProtocolUtils.extractBrowserRequestState = function (browserCrypto, state) {
            if (StringUtils.isEmpty(state)) {
                return null;
            }
            try {
                var requestStateObj = ProtocolUtils.parseRequestState(browserCrypto, state);
                return requestStateObj.libraryState.meta;
            }
            catch (e) {
                throw ClientAuthError.createInvalidStateError(state, e);
            }
        };
        /**
         * Parses properties of server response from url hash
         * @param locationHash Hash from url
         */
        BrowserProtocolUtils.parseServerResponseFromHash = function (locationHash) {
            if (!locationHash) {
                return {};
            }
            var hashUrlString = new UrlString(locationHash);
            return UrlString.getDeserializedHash(hashUrlString.getHash());
        };
        return BrowserProtocolUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements the cache storage interface for MSAL through browser local or session storage.
     * Cookies are only used if storeAuthStateInCookie is true, and are only used for
     * parameters such as state and nonce, generally.
     */
    var BrowserCacheManager = /** @class */ (function (_super) {
        __extends(BrowserCacheManager, _super);
        function BrowserCacheManager(clientId, cacheConfig, cryptoImpl, logger) {
            var _this = _super.call(this, clientId, cryptoImpl) || this;
            // Cookie life calculation (hours * minutes * seconds * ms)
            _this.COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
            _this.cacheConfig = cacheConfig;
            _this.logger = logger;
            _this.browserStorage = _this.setupBrowserStorage(cacheConfig.cacheLocation);
            // Migrate any cache entries from older versions of MSAL.
            _this.migrateCacheEntries();
            return _this;
        }
        /**
         * Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
         * @param cacheLocation
         */
        BrowserCacheManager.prototype.setupBrowserStorage = function (cacheLocation) {
            switch (cacheLocation) {
                case exports.BrowserCacheLocation.LocalStorage:
                case exports.BrowserCacheLocation.SessionStorage:
                    try {
                        return new BrowserStorage(cacheLocation);
                    }
                    catch (e) {
                        this.logger.verbose(e);
                        this.cacheConfig.cacheLocation = exports.BrowserCacheLocation.MemoryStorage;
                        return new MemoryStorage();
                    }
                case exports.BrowserCacheLocation.MemoryStorage:
                default:
                    return new MemoryStorage();
            }
        };
        /**
         * Migrate all old cache entries to new schema. No rollback supported.
         * @param storeAuthStateInCookie
         */
        BrowserCacheManager.prototype.migrateCacheEntries = function () {
            var _this = this;
            var idTokenKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ID_TOKEN;
            var clientInfoKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.CLIENT_INFO;
            var errorKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR;
            var errorDescKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR_DESC;
            var idTokenValue = this.browserStorage.getItem(idTokenKey);
            var clientInfoValue = this.browserStorage.getItem(clientInfoKey);
            var errorValue = this.browserStorage.getItem(errorKey);
            var errorDescValue = this.browserStorage.getItem(errorDescKey);
            var values = [idTokenValue, clientInfoValue, errorValue, errorDescValue];
            var keysToMigrate = [PersistentCacheKeys.ID_TOKEN, PersistentCacheKeys.CLIENT_INFO, PersistentCacheKeys.ERROR, PersistentCacheKeys.ERROR_DESC];
            keysToMigrate.forEach(function (cacheKey, index) { return _this.migrateCacheEntry(cacheKey, values[index]); });
        };
        /**
         * Utility function to help with migration.
         * @param newKey
         * @param value
         * @param storeAuthStateInCookie
         */
        BrowserCacheManager.prototype.migrateCacheEntry = function (newKey, value) {
            if (value) {
                this.setTemporaryCache(newKey, value, true);
            }
        };
        /**
         * Parses passed value as JSON object, JSON.parse() will throw an error.
         * @param input
         */
        BrowserCacheManager.prototype.validateAndParseJson = function (jsonValue) {
            try {
                var parsedJson = JSON.parse(jsonValue);
                /**
                 * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
                 * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
                 * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
                 *
                 */
                return (parsedJson && typeof parsedJson === "object") ? parsedJson : null;
            }
            catch (error) {
                return null;
            }
        };
        /**
         * fetches the entry from the browser storage based off the key
         * @param key
         */
        BrowserCacheManager.prototype.getItem = function (key) {
            return this.browserStorage.getItem(key);
        };
        /**
         * sets the entry in the browser storage
         * @param key
         * @param value
         */
        BrowserCacheManager.prototype.setItem = function (key, value) {
            this.browserStorage.setItem(key, value);
        };
        /**
         * fetch the account entity from the platform cache
         * @param accountKey
         */
        BrowserCacheManager.prototype.getAccount = function (accountKey) {
            var account = this.getItem(accountKey);
            if (StringUtils.isEmpty(account)) {
                return null;
            }
            var parsedAccount = this.validateAndParseJson(account);
            var accountEntity = CacheManager.toObject(new AccountEntity(), parsedAccount);
            if (AccountEntity.isAccountEntity(accountEntity)) {
                return accountEntity;
            }
            return null;
        };
        /**
         * set account entity in the platform cache
         * @param key
         * @param value
         */
        BrowserCacheManager.prototype.setAccount = function (account) {
            var key = account.generateAccountKey();
            this.setItem(key, JSON.stringify(account));
        };
        /**
         * generates idToken entity from a string
         * @param idTokenKey
         */
        BrowserCacheManager.prototype.getIdTokenCredential = function (idTokenKey) {
            var value = this.getItem(idTokenKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedIdToken = this.validateAndParseJson(value);
            var idToken = CacheManager.toObject(new IdTokenEntity(), parsedIdToken);
            if (IdTokenEntity.isIdTokenEntity(idToken)) {
                return idToken;
            }
            return null;
        };
        /**
         * set IdToken credential to the platform cache
         * @param idToken
         */
        BrowserCacheManager.prototype.setIdTokenCredential = function (idToken) {
            var idTokenKey = idToken.generateCredentialKey();
            this.setItem(idTokenKey, JSON.stringify(idToken));
        };
        /**
         * generates accessToken entity from a string
         * @param key
         */
        BrowserCacheManager.prototype.getAccessTokenCredential = function (accessTokenKey) {
            var value = this.getItem(accessTokenKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedAccessToken = this.validateAndParseJson(value);
            var accessToken = CacheManager.toObject(new AccessTokenEntity(), parsedAccessToken);
            if (AccessTokenEntity.isAccessTokenEntity(accessToken)) {
                return accessToken;
            }
            return null;
        };
        /**
         * set accessToken credential to the platform cache
         * @param accessToken
         */
        BrowserCacheManager.prototype.setAccessTokenCredential = function (accessToken) {
            var accessTokenKey = accessToken.generateCredentialKey();
            this.setItem(accessTokenKey, JSON.stringify(accessToken));
        };
        /**
         * generates refreshToken entity from a string
         * @param refreshTokenKey
         */
        BrowserCacheManager.prototype.getRefreshTokenCredential = function (refreshTokenKey) {
            var value = this.getItem(refreshTokenKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedRefreshToken = this.validateAndParseJson(value);
            var refreshToken = CacheManager.toObject(new RefreshTokenEntity(), parsedRefreshToken);
            if (RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {
                return refreshToken;
            }
            return null;
        };
        /**
         * set refreshToken credential to the platform cache
         * @param refreshToken
         */
        BrowserCacheManager.prototype.setRefreshTokenCredential = function (refreshToken) {
            var refreshTokenKey = refreshToken.generateCredentialKey();
            this.setItem(refreshTokenKey, JSON.stringify(refreshToken));
        };
        /**
         * fetch appMetadata entity from the platform cache
         * @param appMetadataKey
         */
        BrowserCacheManager.prototype.getAppMetadata = function (appMetadataKey) {
            var value = this.getItem(appMetadataKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedMetadata = this.validateAndParseJson(value);
            var appMetadata = CacheManager.toObject(new AppMetadataEntity(), parsedMetadata);
            if (AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {
                return appMetadata;
            }
            return null;
        };
        /**
         * set appMetadata entity to the platform cache
         * @param appMetadata
         */
        BrowserCacheManager.prototype.setAppMetadata = function (appMetadata) {
            var appMetadataKey = appMetadata.generateAppMetadataKey();
            this.setItem(appMetadataKey, JSON.stringify(appMetadata));
        };
        /**
         * fetch server telemetry entity from the platform cache
         * @param serverTelemetryKey
         */
        BrowserCacheManager.prototype.getServerTelemetry = function (serverTelemetryKey) {
            var value = this.getItem(serverTelemetryKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedMetadata = this.validateAndParseJson(value);
            var serverTelemetryEntity = CacheManager.toObject(new ServerTelemetryEntity(), parsedMetadata);
            if (ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetryKey, serverTelemetryEntity)) {
                return serverTelemetryEntity;
            }
            return null;
        };
        /**
         * set server telemetry entity to the platform cache
         * @param serverTelemetryKey
         * @param serverTelemetry
         */
        BrowserCacheManager.prototype.setServerTelemetry = function (serverTelemetryKey, serverTelemetry) {
            this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry));
        };
        /**
         * fetch throttling entity from the platform cache
         * @param throttlingCacheKey
         */
        BrowserCacheManager.prototype.getThrottlingCache = function (throttlingCacheKey) {
            var value = this.getItem(throttlingCacheKey);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            var parsedThrottlingCache = this.validateAndParseJson(value);
            var throttlingCache = CacheManager.toObject(new ThrottlingEntity(), parsedThrottlingCache);
            if (ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {
                return throttlingCache;
            }
            return null;
        };
        /**
         * set throttling entity to the platform cache
         * @param throttlingCacheKey
         * @param throttlingCache
         */
        BrowserCacheManager.prototype.setThrottlingCache = function (throttlingCacheKey, throttlingCache) {
            this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache));
        };
        /**
         * Gets cache item with given key.
         * Will retrieve frm cookies if storeAuthStateInCookie is set to true.
         * @param key
         */
        BrowserCacheManager.prototype.getTemporaryCache = function (cacheKey, generateKey) {
            var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
            if (this.cacheConfig.storeAuthStateInCookie) {
                var itemCookie = this.getItemCookie(key);
                if (itemCookie) {
                    return itemCookie;
                }
            }
            var value = this.getItem(key);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            return value;
        };
        /**
         * Sets the cache item with the key and value given.
         * Stores in cookie if storeAuthStateInCookie is set to true.
         * This can cause cookie overflow if used incorrectly.
         * @param key
         * @param value
         */
        BrowserCacheManager.prototype.setTemporaryCache = function (cacheKey, value, generateKey) {
            var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
            this.setItem(key, value);
            if (this.cacheConfig.storeAuthStateInCookie) {
                this.setItemCookie(key, value);
            }
        };
        /**
         * Removes the cache item with the given key.
         * Will also clear the cookie item if storeAuthStateInCookie is set to true.
         * @param key
         */
        BrowserCacheManager.prototype.removeItem = function (key) {
            this.browserStorage.removeItem(key);
            if (this.cacheConfig.storeAuthStateInCookie) {
                this.clearItemCookie(key);
            }
            return true;
        };
        /**
         * Checks whether key is in cache.
         * @param key
         */
        BrowserCacheManager.prototype.containsKey = function (key) {
            return this.browserStorage.containsKey(key);
        };
        /**
         * Gets all keys in window.
         */
        BrowserCacheManager.prototype.getKeys = function () {
            return this.browserStorage.getKeys();
        };
        /**
         * Clears all cache entries created by MSAL (except tokens).
         */
        BrowserCacheManager.prototype.clear = function () {
            var _this = this;
            this.removeAllAccounts();
            this.removeAppMetadata();
            this.browserStorage.getKeys().forEach(function (cacheKey) {
                // Check if key contains msal prefix; For now, we are clearing all the cache items created by MSAL.js
                if (_this.browserStorage.containsKey(cacheKey) && ((cacheKey.indexOf(Constants.CACHE_PREFIX) !== -1) || (cacheKey.indexOf(_this.clientId) !== -1))) {
                    _this.removeItem(cacheKey);
                }
            });
        };
        /**
         * Add value to cookies
         * @param cookieName
         * @param cookieValue
         * @param expires
         */
        BrowserCacheManager.prototype.setItemCookie = function (cookieName, cookieValue, expires) {
            var cookieStr = encodeURIComponent(cookieName) + "=" + encodeURIComponent(cookieValue) + ";path=/;";
            if (expires) {
                var expireTime = this.getCookieExpirationTime(expires);
                cookieStr += "expires=" + expireTime + ";";
            }
            document.cookie = cookieStr;
        };
        /**
         * Get one item by key from cookies
         * @param cookieName
         */
        BrowserCacheManager.prototype.getItemCookie = function (cookieName) {
            var name = encodeURIComponent(cookieName) + "=";
            var cookieList = document.cookie.split(";");
            for (var i = 0; i < cookieList.length; i++) {
                var cookie = cookieList[i];
                while (cookie.charAt(0) === " ") {
                    cookie = cookie.substring(1);
                }
                if (cookie.indexOf(name) === 0) {
                    return decodeURIComponent(cookie.substring(name.length, cookie.length));
                }
            }
            return "";
        };
        /**
         * Clear an item in the cookies by key
         * @param cookieName
         */
        BrowserCacheManager.prototype.clearItemCookie = function (cookieName) {
            this.setItemCookie(cookieName, "", -1);
        };
        /**
         * Clear all msal cookies
         */
        BrowserCacheManager.prototype.clearMsalCookie = function (stateString) {
            var nonceKey = stateString ? this.generateNonceKey(stateString) : this.generateStateKey(TemporaryCacheKeys.NONCE_IDTOKEN);
            this.clearItemCookie(this.generateStateKey(stateString));
            this.clearItemCookie(nonceKey);
            this.clearItemCookie(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
        };
        /**
         * Get cookie expiration time
         * @param cookieLifeDays
         */
        BrowserCacheManager.prototype.getCookieExpirationTime = function (cookieLifeDays) {
            var today = new Date();
            var expr = new Date(today.getTime() + cookieLifeDays * this.COOKIE_LIFE_MULTIPLIER);
            return expr.toUTCString();
        };
        /**
         * Gets the cache object referenced by the browser
         */
        BrowserCacheManager.prototype.getCache = function () {
            return this.browserStorage;
        };
        /**
         * interface compat, we cannot overwrite browser cache; Functionality is supported by individual entities in browser
         */
        BrowserCacheManager.prototype.setCache = function () {
            // sets nothing
        };
        /**
         * Prepend msal.<client-id> to each key; Skip for any JSON object as Key (defined schemas do not need the key appended: AccessToken Keys or the upcoming schema)
         * @param key
         * @param addInstanceId
         */
        BrowserCacheManager.prototype.generateCacheKey = function (key) {
            var generatedKey = this.validateAndParseJson(key);
            if (!generatedKey) {
                if (StringUtils.startsWith(key, Constants.CACHE_PREFIX) || StringUtils.startsWith(key, PersistentCacheKeys.ADAL_ID_TOKEN)) {
                    return key;
                }
                return Constants.CACHE_PREFIX + "." + this.clientId + "." + key;
            }
            return JSON.stringify(key);
        };
        /**
         * Create authorityKey to cache authority
         * @param state
         */
        BrowserCacheManager.prototype.generateAuthorityKey = function (stateString) {
            var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
            return this.generateCacheKey(TemporaryCacheKeys.AUTHORITY + "." + stateId);
        };
        /**
         * Create Nonce key to cache nonce
         * @param state
         */
        BrowserCacheManager.prototype.generateNonceKey = function (stateString) {
            var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
            return this.generateCacheKey(TemporaryCacheKeys.NONCE_IDTOKEN + "." + stateId);
        };
        /**
         * Creates full cache key for the request state
         * @param stateString State string for the request
         */
        BrowserCacheManager.prototype.generateStateKey = function (stateString) {
            // Use the library state id to key temp storage for uniqueness for multiple concurrent requests
            var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
            return this.generateCacheKey(TemporaryCacheKeys.REQUEST_STATE + "." + stateId);
        };
        /**
         * Sets the cacheKey for and stores the authority information in cache
         * @param state
         * @param authority
         */
        BrowserCacheManager.prototype.setAuthorityCache = function (authority, state) {
            // Cache authorityKey
            var authorityCacheKey = this.generateAuthorityKey(state);
            this.setItem(authorityCacheKey, authority);
        };
        /**
         * Gets the cached authority based on the cached state. Returns empty if no cached state found.
         */
        BrowserCacheManager.prototype.getCachedAuthority = function (cachedState) {
            var stateCacheKey = this.generateStateKey(cachedState);
            var state = this.getTemporaryCache(stateCacheKey);
            if (!state) {
                return null;
            }
            var authorityCacheKey = this.generateAuthorityKey(state);
            return this.getTemporaryCache(authorityCacheKey);
        };
        /**
         * Updates account, authority, and state in cache
         * @param serverAuthenticationRequest
         * @param account
         */
        BrowserCacheManager.prototype.updateCacheEntries = function (state, nonce, authorityInstance) {
            // Cache the request state
            var stateCacheKey = this.generateStateKey(state);
            this.setTemporaryCache(stateCacheKey, state, false);
            // Cache the nonce
            var nonceCacheKey = this.generateNonceKey(state);
            this.setTemporaryCache(nonceCacheKey, nonce, false);
            // Cache authorityKey
            this.setAuthorityCache(authorityInstance, state);
        };
        /**
         * Reset all temporary cache items
         * @param state
         */
        BrowserCacheManager.prototype.resetRequestCache = function (state) {
            var _this = this;
            // check state and remove associated cache items
            this.getKeys().forEach(function (key) {
                if (!StringUtils.isEmpty(state) && key.indexOf(state) !== -1) {
                    _this.removeItem(key);
                }
            });
            // delete generic interactive request parameters
            if (state) {
                this.removeItem(this.generateStateKey(state));
                this.removeItem(this.generateNonceKey(state));
                this.removeItem(this.generateAuthorityKey(state));
            }
            this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
            this.removeItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
            this.removeItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
            this.removeItem(this.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS_KEY));
        };
        BrowserCacheManager.prototype.cleanRequestByState = function (stateString) {
            // Interaction is completed - remove interaction status.
            if (stateString) {
                var stateKey = this.generateStateKey(stateString);
                var cachedState = this.getItem(stateKey);
                this.resetRequestCache(cachedState || "");
            }
        };
        BrowserCacheManager.prototype.cleanRequestByInteractionType = function (interactionType) {
            var _this = this;
            this.getKeys().forEach(function (key) {
                if (key.indexOf(TemporaryCacheKeys.REQUEST_STATE) === -1) {
                    return;
                }
                var value = _this.browserStorage.getItem(key);
                var parsedState = BrowserProtocolUtils.extractBrowserRequestState(_this.cryptoImpl, value);
                if (parsedState.interactionType === interactionType) {
                    _this.resetRequestCache(value);
                }
            });
        };
        BrowserCacheManager.prototype.cacheCodeRequest = function (authCodeRequest, browserCrypto) {
            var encodedValue = browserCrypto.base64Encode(JSON.stringify(authCodeRequest));
            this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
        };
        /**
         * Gets the token exchange parameters from the cache. Throws an error if nothing is found.
         */
        BrowserCacheManager.prototype.getCachedRequest = function (state, browserCrypto) {
            try {
                // Get token request from cache and parse as TokenExchangeParameters.
                var encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, true);
                var parsedRequest = JSON.parse(browserCrypto.base64Decode(encodedTokenRequest));
                this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
                // Get cached authority and use if no authority is cached with request.
                if (StringUtils.isEmpty(parsedRequest.authority)) {
                    var authorityCacheKey = this.generateAuthorityKey(state);
                    var cachedAuthority = this.getTemporaryCache(authorityCacheKey);
                    parsedRequest.authority = cachedAuthority;
                }
                return parsedRequest;
            }
            catch (err) {
                throw BrowserAuthError.createTokenRequestCacheError(err);
            }
        };
        return BrowserCacheManager;
    }(CacheManager));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
     */
    var FetchClient = /** @class */ (function () {
        function FetchClient() {
        }
        /**
         * Fetch Client for REST endpoints - Get request
         * @param url
         * @param headers
         * @param body
         */
        FetchClient.prototype.sendGetRequestAsync = function (url, options) {
            return __awaiter(this, void 0, void 0, function () {
                var response, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, fetch(url, {
                            method: HTTP_REQUEST_TYPE.GET,
                            headers: this.getFetchHeaders(options)
                        })];
                        case 1:
                            response = _b.sent();
                            _a = {
                                headers: this.getHeaderDict(response.headers)
                            };
                            return [4 /*yield*/, response.json()];
                        case 2: return [2 /*return*/, (_a.body = (_b.sent()),
                            _a.status = response.status,
                            _a)];
                    }
                });
            });
        };
        /**
         * Fetch Client for REST endpoints - Post request
         * @param url
         * @param headers
         * @param body
         */
        FetchClient.prototype.sendPostRequestAsync = function (url, options) {
            return __awaiter(this, void 0, void 0, function () {
                var reqBody, response, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            reqBody = (options && options.body) || "";
                            return [4 /*yield*/, fetch(url, {
                                method: HTTP_REQUEST_TYPE.POST,
                                headers: this.getFetchHeaders(options),
                                body: reqBody
                            })];
                        case 1:
                            response = _b.sent();
                            _a = {
                                headers: this.getHeaderDict(response.headers)
                            };
                            return [4 /*yield*/, response.json()];
                        case 2: return [2 /*return*/, (_a.body = (_b.sent()),
                            _a.status = response.status,
                            _a)];
                    }
                });
            });
        };
        /**
         * Get Fetch API Headers object from string map
         * @param inputHeaders
         */
        FetchClient.prototype.getFetchHeaders = function (options) {
            var headers = new Headers();
            if (!(options && options.headers)) {
                return headers;
            }
            Object.keys(options.headers).forEach(function (key) {
                headers.append(key, options.headers[key]);
            });
            return headers;
        };
        FetchClient.prototype.getHeaderDict = function (headers) {
            var headerDict = {};
            headers.forEach(function (value, key) {
                headerDict[key] = value;
            });
            return headerDict;
        };
        return FetchClient;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This client implements the XMLHttpRequest class to send GET and POST requests.
     */
    var XhrClient = /** @class */ (function () {
        function XhrClient() {
        }
        /**
         * XhrClient for REST endpoints - Get request
         * @param url
         * @param headers
         * @param body
         */
        XhrClient.prototype.sendGetRequestAsync = function (url, options) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.GET, options)];
                });
            });
        };
        /**
         * XhrClient for REST endpoints - Post request
         * @param url
         * @param headers
         * @param body
         */
        XhrClient.prototype.sendPostRequestAsync = function (url, options) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.POST, options)];
                });
            });
        };
        /**
         * Helper for XhrClient requests.
         * @param url
         * @param method
         * @param options
         */
        XhrClient.prototype.sendRequestAsync = function (url, method, options) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.open(method, url, /* async: */ true);
                _this.setXhrHeaders(xhr, options);
                xhr.onload = function () {
                    if (xhr.status < 200 || xhr.status >= 300) {
                        reject(xhr.responseText);
                    }
                    try {
                        var jsonResponse = JSON.parse(xhr.responseText);
                        var networkResponse = {
                            headers: _this.getHeaderDict(xhr),
                            body: jsonResponse,
                            status: xhr.status
                        };
                        resolve(networkResponse);
                    }
                    catch (e) {
                        reject(xhr.responseText);
                    }
                };
                xhr.onerror = function () {
                    reject(xhr.status);
                };
                if (method === "POST" && options.body) {
                    xhr.send(options.body);
                }
                else if (method === "GET") {
                    xhr.send();
                }
                else {
                    throw BrowserAuthError.createHttpMethodNotImplementedError(method);
                }
            });
        };
        /**
         * Helper to set XHR headers for request.
         * @param xhr
         * @param options
         */
        XhrClient.prototype.setXhrHeaders = function (xhr, options) {
            if (options && options.headers) {
                Object.keys(options.headers).forEach(function (key) {
                    xhr.setRequestHeader(key, options.headers[key]);
                });
            }
        };
        /**
         * Gets a string map of the headers received in the response.
         *
         * Algorithm comes from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
         * @param xhr
         */
        XhrClient.prototype.getHeaderDict = function (xhr) {
            var headerString = xhr.getAllResponseHeaders();
            var headerArr = headerString.trim().split(/[\r\n]+/);
            var headerDict = {};
            headerArr.forEach(function (value) {
                var parts = value.split(": ");
                var headerName = parts.shift();
                var headerVal = parts.join(": ");
                headerDict[headerName] = headerVal;
            });
            return headerDict;
        };
        return XhrClient;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility class for browser specific functions
     */
    var BrowserUtils = /** @class */ (function () {
        function BrowserUtils() {
        }
        // #region Window Navigation and URL management
        /**
         * Used to redirect the browser to the STS authorization endpoint
         * @param {string} urlNavigate - URL of the authorization endpoint
         * @param {boolean} noHistory - boolean flag, uses .replace() instead of .assign() if true
         */
        BrowserUtils.navigateWindow = function (urlNavigate, navigationTimeout, logger, noHistory) {
            if (noHistory) {
                window.location.replace(urlNavigate);
            }
            else {
                window.location.assign(urlNavigate);
            }
            // To block code from running after navigation, this should not throw if navigation succeeds
            return new Promise(function (resolve) {
                setTimeout(function () {
                    logger.warning("Expected to navigate away from the current page but timeout occurred.");
                    resolve();
                }, navigationTimeout);
            });
        };
        /**
         * Clears hash from window url.
         */
        BrowserUtils.clearHash = function () {
            // Office.js sets history.replaceState to null
            if (typeof history.replaceState === "function") {
                // Full removes "#" from url
                history.replaceState(null, null, "" + window.location.pathname + window.location.search);
            }
            else {
                window.location.hash = "";
            }
        };
        /**
         * Replaces current hash with hash from provided url
         */
        BrowserUtils.replaceHash = function (url) {
            var urlParts = url.split("#");
            urlParts.shift(); // Remove part before the hash
            window.location.hash = urlParts.length > 0 ? urlParts.join("#") : "";
        };
        /**
         * Returns boolean of whether the current window is in an iframe or not.
         */
        BrowserUtils.isInIframe = function () {
            return window.parent !== window;
        };
        // #endregion
        /**
         * Returns current window URL as redirect uri
         */
        BrowserUtils.getCurrentUri = function () {
            return window.location.href.split("?")[0].split("#")[0];
        };
        /**
         * Gets the homepage url for the current window location.
         */
        BrowserUtils.getHomepage = function () {
            var currentUrl = new UrlString(window.location.href);
            var urlComponents = currentUrl.getUrlComponents();
            return urlComponents.Protocol + "//" + urlComponents.HostNameAndPort + "/";
        };
        /**
         * Returns best compatible network client object.
         */
        BrowserUtils.getBrowserNetworkClient = function () {
            if (window.fetch && window.Headers) {
                return new FetchClient();
            }
            else {
                return new XhrClient();
            }
        };
        /**
         * Throws error if we have completed an auth and are
         * attempting another auth request inside an iframe.
         */
        BrowserUtils.blockReloadInHiddenIframes = function () {
            var isResponseHash = UrlString.hashContainsKnownProperties(window.location.hash);
            // return an error if called from the hidden iframe created by the msal js silent calls
            if (isResponseHash && BrowserUtils.isInIframe()) {
                throw BrowserAuthError.createBlockReloadInHiddenIframeError();
            }
        };
        /**
         * Block redirect operations in iframes unless explicitly allowed
         * @param interactionType Interaction type for the request
         * @param allowRedirectInIframe Config value to allow redirects when app is inside an iframe
         */
        BrowserUtils.blockRedirectInIframe = function (interactionType, allowRedirectInIframe) {
            var isIframedApp = BrowserUtils.isInIframe();
            if (interactionType === exports.InteractionType.Redirect && isIframedApp && !allowRedirectInIframe) {
                // If we are not in top frame, we shouldn't redirect. This is also handled by the service.
                throw BrowserAuthError.createRedirectInIframeError(isIframedApp);
            }
        };
        /**
         * Throws error if token requests are made in non-browser environment
         * @param isBrowserEnvironment Flag indicating if environment is a browser.
         */
        BrowserUtils.blockNonBrowserEnvironment = function (isBrowserEnvironment) {
            if (!isBrowserEnvironment) {
                throw BrowserAuthError.createNonBrowserEnvironmentError();
            }
        };
        /**
         * Returns boolean of whether current browser is an Internet Explorer or Edge browser.
         */
        BrowserUtils.detectIEOrEdge = function () {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            var msie11 = ua.indexOf("Trident/");
            var msedge = ua.indexOf("Edge/");
            var isIE = msie > 0 || msie11 > 0;
            var isEdge = msedge > 0;
            return isIE || isEdge;
        };
        return BrowserUtils;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Default timeout for popup windows and iframes in milliseconds
    var DEFAULT_POPUP_TIMEOUT_MS = 60000;
    var DEFAULT_IFRAME_TIMEOUT_MS = 6000;
    var DEFAULT_REDIRECT_TIMEOUT_MS = 30000;
    /**
     * MSAL function that sets the default options when not explicitly configured from app developer
     *
     * @param auth
     * @param cache
     * @param system
     *
     * @returns Configuration object
     */
    function buildConfiguration(_a) {
        var userInputAuth = _a.auth, userInputCache = _a.cache, userInputSystem = _a.system;
        // Default auth options for browser
        var DEFAULT_AUTH_OPTIONS = {
            clientId: "",
            authority: "" + Constants.DEFAULT_AUTHORITY,
            knownAuthorities: [],
            cloudDiscoveryMetadata: "",
            redirectUri: "",
            postLogoutRedirectUri: "",
            navigateToLoginRequestUrl: true,
            clientCapabilities: [],
            protocolMode: exports.ProtocolMode.AAD
        };
        // Default cache options for browser
        var DEFAULT_CACHE_OPTIONS = {
            cacheLocation: exports.BrowserCacheLocation.SessionStorage,
            storeAuthStateInCookie: false
        };
        // Default logger options for browser
        var DEFAULT_LOGGER_OPTIONS = {
            loggerCallback: function () { },
            logLevel: exports.LogLevel.Info,
            piiLoggingEnabled: false
        };
        // Default system options for browser
        var DEFAULT_BROWSER_SYSTEM_OPTIONS = __assign(__assign({}, DEFAULT_SYSTEM_OPTIONS), {
            loggerOptions: DEFAULT_LOGGER_OPTIONS, networkClient: BrowserUtils.getBrowserNetworkClient(), loadFrameTimeout: 0,
            // If loadFrameTimeout is provided, use that as default.
            windowHashTimeout: (userInputSystem && userInputSystem.loadFrameTimeout) || DEFAULT_POPUP_TIMEOUT_MS, iframeHashTimeout: (userInputSystem && userInputSystem.loadFrameTimeout) || DEFAULT_IFRAME_TIMEOUT_MS, navigateFrameWait: BrowserUtils.detectIEOrEdge() ? 500 : 0, redirectNavigationTimeout: DEFAULT_REDIRECT_TIMEOUT_MS, asyncPopups: false, allowRedirectInIframe: false
        });
        var overlayedConfig = {
            auth: __assign(__assign({}, DEFAULT_AUTH_OPTIONS), userInputAuth),
            cache: __assign(__assign({}, DEFAULT_CACHE_OPTIONS), userInputCache),
            system: __assign(__assign({}, DEFAULT_BROWSER_SYSTEM_OPTIONS), userInputSystem)
        };
        return overlayedConfig;
    }

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Abstract class which defines operations for a browser interaction handling class.
     */
    var InteractionHandler = /** @class */ (function () {
        function InteractionHandler(authCodeModule, storageImpl) {
            this.authModule = authCodeModule;
            this.browserStorage = storageImpl;
        }
        /**
         * Function to handle response parameters from hash.
         * @param locationHash
         */
        InteractionHandler.prototype.handleCodeResponse = function (locationHash, authority, networkModule) {
            return __awaiter(this, void 0, void 0, function () {
                var serverParams, stateKey, requestState, authCodeResponse, nonceKey, cachedNonce, tokenResponse;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            // Check that location hash isn't empty.
                            if (StringUtils.isEmpty(locationHash)) {
                                throw BrowserAuthError.createEmptyHashError(locationHash);
                            }
                            serverParams = BrowserProtocolUtils.parseServerResponseFromHash(locationHash);
                            stateKey = this.browserStorage.generateStateKey(serverParams.state);
                            requestState = this.browserStorage.getTemporaryCache(stateKey);
                            authCodeResponse = this.authModule.handleFragmentResponse(locationHash, requestState);
                            nonceKey = this.browserStorage.generateNonceKey(requestState);
                            cachedNonce = this.browserStorage.getTemporaryCache(nonceKey);
                            // Assign code to request
                            this.authCodeRequest.code = authCodeResponse.code;
                            if (!authCodeResponse.cloud_instance_host_name) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.updateTokenEndpointAuthority(authCodeResponse.cloud_instance_host_name, authority, networkModule)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            authCodeResponse.nonce = cachedNonce;
                            authCodeResponse.state = requestState;
                            return [4 /*yield*/, this.authModule.acquireToken(this.authCodeRequest, authCodeResponse)];
                        case 3:
                            tokenResponse = _a.sent();
                            this.browserStorage.cleanRequestByState(serverParams.state);
                            return [2 /*return*/, tokenResponse];
                    }
                });
            });
        };
        InteractionHandler.prototype.updateTokenEndpointAuthority = function (cloudInstanceHostname, authority, networkModule) {
            return __awaiter(this, void 0, void 0, function () {
                var cloudInstanceAuthorityUri, cloudInstanceAuthority;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!!authority.isAuthorityAlias(cloudInstanceHostname)) return [3 /*break*/, 2];
                            cloudInstanceAuthorityUri = "https://" + cloudInstanceHostname + "/" + authority.tenant + "/";
                            return [4 /*yield*/, AuthorityFactory.createDiscoveredInstance(cloudInstanceAuthorityUri, networkModule, authority.protocolMode)];
                        case 1:
                            cloudInstanceAuthority = _a.sent();
                            this.authModule.updateAuthority(cloudInstanceAuthority);
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        };
        return InteractionHandler;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var RedirectHandler = /** @class */ (function (_super) {
        __extends(RedirectHandler, _super);
        function RedirectHandler(authCodeModule, storageImpl, browserCrypto) {
            var _this = _super.call(this, authCodeModule, storageImpl) || this;
            _this.browserCrypto = browserCrypto;
            return _this;
        }
        /**
         * Redirects window to given URL.
         * @param urlNavigate
         */
        RedirectHandler.prototype.initiateAuthRequest = function (requestUrl, authCodeRequest, params) {
            // Navigate if valid URL
            if (!StringUtils.isEmpty(requestUrl)) {
                // Cache start page, returns to this page after redirectUri if navigateToLoginRequestUrl is true
                if (params.redirectStartPage) {
                    this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, params.redirectStartPage, true);
                }
                // Set interaction status in the library.
                this.browserStorage.setTemporaryCache(TemporaryCacheKeys.INTERACTION_STATUS_KEY, BrowserConstants.INTERACTION_IN_PROGRESS_VALUE, true);
                this.browserStorage.cacheCodeRequest(authCodeRequest, this.browserCrypto);
                this.authModule.logger.infoPii("Navigate to:" + requestUrl);
                // If onRedirectNavigate is implemented, invoke it and provide requestUrl
                if (typeof params.onRedirectNavigate === "function") {
                    this.authModule.logger.verbose("Invoking onRedirectNavigate callback");
                    var navigate = params.onRedirectNavigate(requestUrl);
                    // Returning false from onRedirectNavigate will stop navigation
                    if (navigate !== false) {
                        this.authModule.logger.verbose("onRedirectNavigate did not return false, navigating");
                        return BrowserUtils.navigateWindow(requestUrl, params.redirectTimeout, this.authModule.logger);
                    }
                    else {
                        this.authModule.logger.verbose("onRedirectNavigate returned false, stopping navigation");
                        return Promise.resolve();
                    }
                }
                else {
                    // Navigate window to request URL
                    this.authModule.logger.verbose("Navigating window to navigate url");
                    return BrowserUtils.navigateWindow(requestUrl, params.redirectTimeout, this.authModule.logger);
                }
            }
            else {
                // Throw error if request URL is empty.
                this.authModule.logger.info("Navigate url is empty");
                throw BrowserAuthError.createEmptyNavigationUriError();
            }
        };
        /**
         * Handle authorization code response in the window.
         * @param hash
         */
        RedirectHandler.prototype.handleCodeResponse = function (locationHash, authority, networkModule, clientId) {
            return __awaiter(this, void 0, void 0, function () {
                var serverParams, stateKey, requestState, authCodeResponse, nonceKey, cachedNonce, tokenResponse;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            // Check that location hash isn't empty.
                            if (StringUtils.isEmpty(locationHash)) {
                                throw BrowserAuthError.createEmptyHashError(locationHash);
                            }
                            // Interaction is completed - remove interaction status.
                            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS_KEY));
                            serverParams = BrowserProtocolUtils.parseServerResponseFromHash(locationHash);
                            stateKey = this.browserStorage.generateStateKey(serverParams.state);
                            requestState = this.browserStorage.getTemporaryCache(stateKey);
                            authCodeResponse = this.authModule.handleFragmentResponse(locationHash, requestState);
                            nonceKey = this.browserStorage.generateNonceKey(requestState);
                            cachedNonce = this.browserStorage.getTemporaryCache(nonceKey);
                            this.authCodeRequest = this.browserStorage.getCachedRequest(requestState, this.browserCrypto);
                            // Assign code to request
                            this.authCodeRequest.code = authCodeResponse.code;
                            if (!authCodeResponse.cloud_instance_host_name) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.updateTokenEndpointAuthority(authCodeResponse.cloud_instance_host_name, authority, networkModule)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            authCodeResponse.nonce = cachedNonce;
                            authCodeResponse.state = requestState;
                            // Remove throttle if it exists
                            if (clientId) {
                                ThrottlingUtils.removeThrottle(this.browserStorage, clientId, this.authCodeRequest.authority, this.authCodeRequest.scopes);
                            }
                            return [4 /*yield*/, this.authModule.acquireToken(this.authCodeRequest, authCodeResponse)];
                        case 3:
                            tokenResponse = _a.sent();
                            this.browserStorage.cleanRequestByState(serverParams.state);
                            return [2 /*return*/, tokenResponse];
                    }
                });
            });
        };
        return RedirectHandler;
    }(InteractionHandler));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements the interaction handler base class for browsers. It is written specifically for handling
     * popup window scenarios. It includes functions for monitoring the popup window for a hash.
     */
    var PopupHandler = /** @class */ (function (_super) {
        __extends(PopupHandler, _super);
        function PopupHandler(authCodeModule, storageImpl) {
            var _this = _super.call(this, authCodeModule, storageImpl) || this;
            // Properly sets this reference for the unload event.
            _this.unloadWindow = _this.unloadWindow.bind(_this);
            return _this;
        }
        /**
         * Opens a popup window with given request Url.
         * @param requestUrl
         */
        PopupHandler.prototype.initiateAuthRequest = function (requestUrl, authCodeRequest, params) {
            // Check that request url is not empty.
            if (!StringUtils.isEmpty(requestUrl)) {
                // Save auth code request
                this.authCodeRequest = authCodeRequest;
                // Set interaction status in the library.
                this.browserStorage.setTemporaryCache(TemporaryCacheKeys.INTERACTION_STATUS_KEY, BrowserConstants.INTERACTION_IN_PROGRESS_VALUE, true);
                this.authModule.logger.infoPii("Navigate to:" + requestUrl);
                // Open the popup window to requestUrl.
                return this.openPopup(requestUrl, params.popup);
            }
            else {
                // Throw error if request URL is empty.
                this.authModule.logger.error("Navigate url is empty");
                throw BrowserAuthError.createEmptyNavigationUriError();
            }
        };
        /**
         * Monitors a window until it loads a url with a known hash, or hits a specified timeout.
         * @param popupWindow - window that is being monitored
         * @param timeout - milliseconds until timeout
         * @param urlNavigate - url that was navigated to
         */
        PopupHandler.prototype.monitorPopupForHash = function (popupWindow, timeout) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                if (timeout < DEFAULT_POPUP_TIMEOUT_MS) {
                    _this.authModule.logger.warning("system.loadFrameTimeout or system.windowHashTimeout set to lower (" + timeout + "ms) than the default (" + DEFAULT_POPUP_TIMEOUT_MS + "ms). This may result in timeouts.");
                }
                var maxTicks = timeout / BrowserConstants.POLL_INTERVAL_MS;
                var ticks = 0;
                var intervalId = setInterval(function () {
                    if (popupWindow.closed) {
                        // Window is closed
                        _this.cleanPopup();
                        clearInterval(intervalId);
                        reject(BrowserAuthError.createUserCancelledError());
                        return;
                    }
                    var href;
                    try {
                        /*
                         * Will throw if cross origin,
                         * which should be caught and ignored
                         * since we need the interval to keep running while on STS UI.
                         */
                        href = popupWindow.location.href;
                    }
                    catch (e) { }
                    // Don't process blank pages or cross domain
                    if (StringUtils.isEmpty(href) || href === "about:blank") {
                        return;
                    }
                    // Only run clock when we are on same domain
                    ticks++;
                    var contentHash = popupWindow.location.hash;
                    if (UrlString.hashContainsKnownProperties(contentHash)) {
                        // Success case
                        _this.cleanPopup(popupWindow);
                        clearInterval(intervalId);
                        resolve(contentHash);
                        return;
                    }
                    else if (ticks > maxTicks) {
                        // Timeout error
                        _this.cleanPopup(popupWindow);
                        clearInterval(intervalId);
                        reject(BrowserAuthError.createMonitorPopupTimeoutError());
                        return;
                    }
                }, BrowserConstants.POLL_INTERVAL_MS);
            });
        };
        /**
         * @hidden
         *
         * Configures popup window for login.
         *
         * @param urlNavigate
         * @param title
         * @param popUpWidth
         * @param popUpHeight
         * @ignore
         * @hidden
         */
        PopupHandler.prototype.openPopup = function (urlNavigate, popup) {
            try {
                var popupWindow = void 0;
                // Popup window passed in, setting url to navigate to
                if (popup) {
                    popupWindow = popup;
                    popupWindow.location.assign(urlNavigate);
                }
                else if (typeof popup === "undefined") {
                    // Popup will be undefined if it was not passed in
                    popupWindow = PopupHandler.openSizedPopup(urlNavigate);
                }
                // Popup will be null if popups are blocked
                if (!popupWindow) {
                    throw BrowserAuthError.createEmptyWindowCreatedError();
                }
                if (popupWindow.focus) {
                    popupWindow.focus();
                }
                this.currentWindow = popupWindow;
                window.addEventListener("beforeunload", this.unloadWindow);
                return popupWindow;
            }
            catch (e) {
                this.authModule.logger.error("error opening popup " + e.message);
                this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS_KEY));
                throw BrowserAuthError.createPopupWindowError(e.toString());
            }
        };
        PopupHandler.openSizedPopup = function (urlNavigate) {
            if (urlNavigate === void 0) { urlNavigate = "about:blank"; }
            /**
             * adding winLeft and winTop to account for dual monitor
             * using screenLeft and screenTop for IE8 and earlier
             */
            var winLeft = window.screenLeft ? window.screenLeft : window.screenX;
            var winTop = window.screenTop ? window.screenTop : window.screenY;
            /**
             * window.innerWidth displays browser window"s height and width excluding toolbars
             * using document.documentElement.clientWidth for IE8 and earlier
             */
            var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            var left = Math.max(0, ((width / 2) - (BrowserConstants.POPUP_WIDTH / 2)) + winLeft);
            var top = Math.max(0, ((height / 2) - (BrowserConstants.POPUP_HEIGHT / 2)) + winTop);
            return window.open(urlNavigate, Constants.LIBRARY_NAME, "width=" + BrowserConstants.POPUP_WIDTH + ", height=" + BrowserConstants.POPUP_HEIGHT + ", top=" + top + ", left=" + left);
        };
        /**
         * Event callback to unload main window.
         */
        PopupHandler.prototype.unloadWindow = function (e) {
            this.browserStorage.cleanRequestByInteractionType(exports.InteractionType.Popup);
            this.currentWindow.close();
            // Guarantees browser unload will happen, so no other errors will be thrown.
            delete e["returnValue"];
        };
        /**
         * Closes popup, removes any state vars created during popup calls.
         * @param popupWindow
         */
        PopupHandler.prototype.cleanPopup = function (popupWindow) {
            if (popupWindow) {
                // Close window.
                popupWindow.close();
            }
            // Remove window unload function
            window.removeEventListener("beforeunload", this.unloadWindow);
            // Interaction is completed - remove interaction status.
            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS_KEY));
        };
        return PopupHandler;
    }(InteractionHandler));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var SilentHandler = /** @class */ (function (_super) {
        __extends(SilentHandler, _super);
        function SilentHandler(authCodeModule, storageImpl, navigateFrameWait) {
            var _this = _super.call(this, authCodeModule, storageImpl) || this;
            _this.navigateFrameWait = navigateFrameWait;
            return _this;
        }
        /**
         * Creates a hidden iframe to given URL using user-requested scopes as an id.
         * @param urlNavigate
         * @param userRequestScopes
         */
        SilentHandler.prototype.initiateAuthRequest = function (requestUrl, authCodeRequest) {
            return __awaiter(this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (StringUtils.isEmpty(requestUrl)) {
                                // Throw error if request URL is empty.
                                this.authModule.logger.info("Navigate url is empty");
                                throw BrowserAuthError.createEmptyNavigationUriError();
                            }
                            // Save auth code request
                            this.authCodeRequest = authCodeRequest;
                            if (!this.navigateFrameWait) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.loadFrame(requestUrl)];
                        case 1:
                            _a = _b.sent();
                            return [3 /*break*/, 3];
                        case 2:
                            _a = this.loadFrameSync(requestUrl);
                            _b.label = 3;
                        case 3: return [2 /*return*/, _a];
                    }
                });
            });
        };
        /**
         * Monitors an iframe content window until it loads a url with a known hash, or hits a specified timeout.
         * @param iframe
         * @param timeout
         */
        SilentHandler.prototype.monitorIframeForHash = function (iframe, timeout) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                if (timeout < DEFAULT_IFRAME_TIMEOUT_MS) {
                    _this.authModule.logger.warning("system.loadFrameTimeout or system.iframeHashTimeout set to lower (" + timeout + "ms) than the default (" + DEFAULT_IFRAME_TIMEOUT_MS + "ms). This may result in timeouts.");
                }
                /*
                 * Polling for iframes can be purely timing based,
                 * since we don't need to account for interaction.
                 */
                var nowMark = window.performance.now();
                var timeoutMark = nowMark + timeout;
                var intervalId = setInterval(function () {
                    if (window.performance.now() > timeoutMark) {
                        _this.removeHiddenIframe(iframe);
                        clearInterval(intervalId);
                        reject(BrowserAuthError.createMonitorIframeTimeoutError());
                        return;
                    }
                    var href;
                    try {
                        /*
                         * Will throw if cross origin,
                         * which should be caught and ignored
                         * since we need the interval to keep running while on STS UI.
                         */
                        href = iframe.contentWindow.location.href;
                    }
                    catch (e) { }
                    if (StringUtils.isEmpty(href)) {
                        return;
                    }
                    var contentHash = iframe.contentWindow.location.hash;
                    if (UrlString.hashContainsKnownProperties(contentHash)) {
                        // Success case
                        _this.removeHiddenIframe(iframe);
                        clearInterval(intervalId);
                        resolve(contentHash);
                        return;
                    }
                }, BrowserConstants.POLL_INTERVAL_MS);
            });
        };
        /**
         * @hidden
         * Loads iframe with authorization endpoint URL
         * @ignore
         */
        SilentHandler.prototype.loadFrame = function (urlNavigate) {
            /*
             * This trick overcomes iframe navigation in IE
             * IE does not load the page consistently in iframe
             */
            var _this = this;
            return new Promise(function (resolve, reject) {
                var frameHandle = _this.createHiddenIframe();
                setTimeout(function () {
                    if (!frameHandle) {
                        reject("Unable to load iframe");
                        return;
                    }
                    frameHandle.src = urlNavigate;
                    resolve(frameHandle);
                }, _this.navigateFrameWait);
            });
        };
        /**
         * @hidden
         * Loads the iframe synchronously when the navigateTimeFrame is set to `0`
         * @param urlNavigate
         * @param frameName
         * @param logger
         */
        SilentHandler.prototype.loadFrameSync = function (urlNavigate) {
            var frameHandle = this.createHiddenIframe();
            frameHandle.src = urlNavigate;
            return frameHandle;
        };
        /**
         * @hidden
         * Creates a new hidden iframe or gets an existing one for silent token renewal.
         * @ignore
         */
        SilentHandler.prototype.createHiddenIframe = function () {
            var authFrame = document.createElement("iframe");
            authFrame.style.visibility = "hidden";
            authFrame.style.position = "absolute";
            authFrame.style.width = authFrame.style.height = "0";
            authFrame.style.border = "0";
            authFrame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
            document.getElementsByTagName("body")[0].appendChild(authFrame);
            return authFrame;
        };
        /**
         * @hidden
         * Removes a hidden iframe from the page.
         * @ignore
         */
        SilentHandler.prototype.removeHiddenIframe = function (iframe) {
            if (document.body === iframe.parentNode) {
                document.body.removeChild(iframe);
            }
        };
        return SilentHandler;
    }(InteractionHandler));

    var name$1 = "@azure/msal-browser";
    var version$1 = "2.8.0";

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    (function (EventType) {
        EventType["LOGIN_START"] = "msal:loginStart";
        EventType["LOGIN_SUCCESS"] = "msal:loginSuccess";
        EventType["LOGIN_FAILURE"] = "msal:loginFailure";
        EventType["ACQUIRE_TOKEN_START"] = "msal:acquireTokenStart";
        EventType["ACQUIRE_TOKEN_SUCCESS"] = "msal:acquireTokenSuccess";
        EventType["ACQUIRE_TOKEN_FAILURE"] = "msal:acquireTokenFailure";
        EventType["ACQUIRE_TOKEN_NETWORK_START"] = "msal:acquireTokenFromNetworkStart";
        EventType["SSO_SILENT_START"] = "msal:ssoSilentStart";
        EventType["SSO_SILENT_SUCCESS"] = "msal:ssoSilentSuccess";
        EventType["SSO_SILENT_FAILURE"] = "msal:ssoSilentFailure";
        EventType["HANDLE_REDIRECT_START"] = "msal:handleRedirectStart";
        EventType["HANDLE_REDIRECT_END"] = "msal:handleRedirectEnd";
        EventType["LOGOUT_START"] = "msal:logoutStart";
        EventType["LOGOUT_SUCCESS"] = "msal:logoutSuccess";
        EventType["LOGOUT_FAILURE"] = "msal:logoutFailure";
    })(exports.EventType || (exports.EventType = {}));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var ClientApplication = /** @class */ (function () {
        /**
         * @constructor
         * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
         *
         * Important attributes in the Configuration object for auth are:
         * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
         * - authority: the authority URL for your application.
         * - redirect_uri: the uri of your application registered in the portal.
         *
         * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
         * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
         * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
         * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
         * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
         * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
         *
         * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
         * Full B2C functionality will be available in this library in future versions.
         *
         * @param {@link (Configuration:type)} configuration object for the MSAL PublicClientApplication instance
         */
        function ClientApplication(configuration) {
            /*
             * If loaded in an environment where window is not available,
             * set internal flag to false so that further requests fail.
             * This is to support server-side rendering environments.
             */
            this.isBrowserEnvironment = typeof window !== "undefined";
            if (!this.isBrowserEnvironment) {
                return;
            }
            // Set the configuration.
            this.config = buildConfiguration(configuration);
            // Initialize the crypto class.
            this.browserCrypto = new CryptoOps();
            // Initialize the network module class.
            this.networkClient = this.config.system.networkClient;
            // Initialize logger
            this.logger = new Logger(this.config.system.loggerOptions, name$1, version$1);
            // Initialize the browser storage class.
            this.browserStorage = new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger);
            // Array of events
            this.eventCallbacks = new Map();
            // Initialize default authority instance
            TrustedAuthority.setTrustedAuthoritiesFromConfig(this.config.auth.knownAuthorities, this.config.auth.cloudDiscoveryMetadata);
            this.defaultAuthority = null;
        }
        // #region Redirect Flow
        /**
         * Event handler function which allows users to fire events after the PublicClientApplication object
         * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
         * auth flows.
         * @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
         * @returns {Promise.<AuthenticationResult | null>} token response or null. If the return value is null, then no auth redirect was detected.
         */
        ClientApplication.prototype.handleRedirectPromise = function (hash) {
            return __awaiter(this, void 0, void 0, function () {
                var loggedInAccounts;
                var _this = this;
                return __generator(this, function (_a) {
                    this.emitEvent(exports.EventType.HANDLE_REDIRECT_START, exports.InteractionType.Redirect);
                    loggedInAccounts = this.getAllAccounts();
                    if (this.isBrowserEnvironment) {
                        return [2 /*return*/, this.handleRedirectResponse(hash)
                            .then(function (result) {
                                if (result) {
                                    // Emit login event if number of accounts change
                                    var isLoggingIn = loggedInAccounts.length < _this.getAllAccounts().length;
                                    if (isLoggingIn) {
                                        _this.emitEvent(exports.EventType.LOGIN_SUCCESS, exports.InteractionType.Redirect, result);
                                    }
                                    else {
                                        _this.emitEvent(exports.EventType.ACQUIRE_TOKEN_SUCCESS, exports.InteractionType.Redirect, result);
                                    }
                                }
                                _this.emitEvent(exports.EventType.HANDLE_REDIRECT_END, exports.InteractionType.Redirect);
                                return result;
                            })
                            .catch(function (e) {
                                // Emit login event if there is an account
                                if (loggedInAccounts.length > 0) {
                                    _this.emitEvent(exports.EventType.ACQUIRE_TOKEN_FAILURE, exports.InteractionType.Redirect, null, e);
                                }
                                else {
                                    _this.emitEvent(exports.EventType.LOGIN_FAILURE, exports.InteractionType.Redirect, null, e);
                                }
                                _this.emitEvent(exports.EventType.HANDLE_REDIRECT_END, exports.InteractionType.Redirect);
                                throw e;
                            })];
                    }
                    return [2 /*return*/, null];
                });
            });
        };
        /**
         * Checks if navigateToLoginRequestUrl is set, and:
         * - if true, performs logic to cache and navigate
         * - if false, handles hash string and parses response
         */
        ClientApplication.prototype.handleRedirectResponse = function (hash) {
            return __awaiter(this, void 0, void 0, function () {
                var responseHash, loginRequestUrl, loginRequestUrlNormalized, currentUrlNormalized, handleHashResult, homepage;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.interactionInProgress()) {
                                this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
                                return [2 /*return*/, null];
                            }
                            responseHash = this.getRedirectResponseHash(hash || window.location.hash);
                            if (StringUtils.isEmpty(responseHash)) {
                                // Not a recognized server response hash or hash not associated with a redirect request
                                return [2 /*return*/, null];
                            }
                            loginRequestUrl = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, true);
                            loginRequestUrlNormalized = UrlString.removeHashFromUrl(loginRequestUrl || "");
                            currentUrlNormalized = UrlString.removeHashFromUrl(window.location.href);
                            if (!(loginRequestUrlNormalized === currentUrlNormalized && this.config.auth.navigateToLoginRequestUrl)) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.handleHash(responseHash)];
                        case 1:
                            handleHashResult = _a.sent();
                            if (loginRequestUrl.indexOf("#") > -1) {
                                // Replace current hash with non-msal hash, if present
                                BrowserUtils.replaceHash(loginRequestUrl);
                            }
                            return [2 /*return*/, handleHashResult];
                        case 2:
                            if (!!this.config.auth.navigateToLoginRequestUrl) return [3 /*break*/, 3];
                            return [2 /*return*/, this.handleHash(responseHash)];
                        case 3:
                            if (!!BrowserUtils.isInIframe()) return [3 /*break*/, 7];
                            /*
                             * Returned from authority using redirect - need to perform navigation before processing response
                             * Cache the hash to be retrieved after the next redirect
                             */
                            this.browserStorage.setTemporaryCache(TemporaryCacheKeys.URL_HASH, responseHash, true);
                            if (!(!loginRequestUrl || loginRequestUrl === "null")) return [3 /*break*/, 5];
                            homepage = BrowserUtils.getHomepage();
                            // Cache the homepage under ORIGIN_URI to ensure cached hash is processed on homepage
                            this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, homepage, true);
                            this.logger.warning("Unable to get valid login request url from cache, redirecting to home page");
                            return [4 /*yield*/, BrowserUtils.navigateWindow(homepage, this.config.system.redirectNavigationTimeout, this.logger, true)];
                        case 4:
                            _a.sent();
                            return [3 /*break*/, 7];
                        case 5:
                            // Navigate to page that initiated the redirect request
                            return [4 /*yield*/, BrowserUtils.navigateWindow(loginRequestUrl, this.config.system.redirectNavigationTimeout, this.logger, true)];
                        case 6:
                            // Navigate to page that initiated the redirect request
                            _a.sent();
                            _a.label = 7;
                        case 7: return [2 /*return*/, null];
                    }
                });
            });
        };
        /**
         * Gets the response hash for a redirect request
         * Returns null if interactionType in the state value is not "redirect" or the hash does not contain known properties
         * @returns {string}
         */
        ClientApplication.prototype.getRedirectResponseHash = function (hash) {
            // Get current location hash from window or cache.
            var isResponseHash = UrlString.hashContainsKnownProperties(hash);
            var cachedHash = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.URL_HASH, true);
            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.URL_HASH));
            var responseHash = isResponseHash ? hash : cachedHash;
            if (responseHash) {
                // Deserialize hash fragment response parameters.
                var serverParams = UrlString.getDeserializedHash(responseHash);
                var platformStateObj = BrowserProtocolUtils.extractBrowserRequestState(this.browserCrypto, serverParams.state);
                if (platformStateObj.interactionType !== exports.InteractionType.Redirect) {
                    return null;
                }
                else {
                    BrowserUtils.clearHash();
                    return responseHash;
                }
            }
            this.browserStorage.cleanRequestByInteractionType(exports.InteractionType.Redirect);
            return null;
        };
        /**
         * Checks if hash exists and handles in window.
         * @param responseHash
         * @param interactionHandler
         */
        ClientApplication.prototype.handleHash = function (responseHash) {
            return __awaiter(this, void 0, void 0, function () {
                var encodedTokenRequest, cachedRequest, serverTelemetryManager, serverParams, currentAuthority, authClient, interactionHandler, e_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            encodedTokenRequest = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, true);
                            cachedRequest = JSON.parse(this.browserCrypto.base64Decode(encodedTokenRequest));
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.handleRedirectPromise, cachedRequest.correlationId);
                            serverParams = BrowserProtocolUtils.parseServerResponseFromHash(responseHash);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 4, , 5]);
                            currentAuthority = this.browserStorage.getCachedAuthority(serverParams.state);
                            return [4 /*yield*/, this.createAuthCodeClient(serverTelemetryManager, currentAuthority)];
                        case 2:
                            authClient = _a.sent();
                            interactionHandler = new RedirectHandler(authClient, this.browserStorage, this.browserCrypto);
                            return [4 /*yield*/, interactionHandler.handleCodeResponse(responseHash, authClient.authority, this.networkClient, this.config.auth.clientId)];
                        case 3: return [2 /*return*/, _a.sent()];
                        case 4:
                            e_1 = _a.sent();
                            serverTelemetryManager.cacheFailedRequest(e_1);
                            this.browserStorage.cleanRequestByInteractionType(exports.InteractionType.Redirect);
                            throw e_1;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
         * the page, so any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param {@link (RedirectRequest:type)}
         */
        ClientApplication.prototype.acquireTokenRedirect = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var isLoggedIn, validRequest, serverTelemetryManager, authCodeRequest, authClient, interactionHandler, navigateUrl, redirectStartPage, e_2;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            // Preflight request
                            this.preflightBrowserEnvironmentCheck(exports.InteractionType.Redirect);
                            isLoggedIn = this.getAllAccounts().length > 0;
                            if (isLoggedIn) {
                                this.emitEvent(exports.EventType.ACQUIRE_TOKEN_START, exports.InteractionType.Redirect, request);
                            }
                            else {
                                this.emitEvent(exports.EventType.LOGIN_START, exports.InteractionType.Redirect, request);
                            }
                            validRequest = this.preflightInteractiveRequest(request, exports.InteractionType.Redirect);
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenRedirect, validRequest.correlationId);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 5, , 6]);
                            return [4 /*yield*/, this.initializeAuthorizationCodeRequest(validRequest)];
                        case 2:
                            authCodeRequest = _a.sent();
                            return [4 /*yield*/, this.createAuthCodeClient(serverTelemetryManager, validRequest.authority)];
                        case 3:
                            authClient = _a.sent();
                            interactionHandler = new RedirectHandler(authClient, this.browserStorage, this.browserCrypto);
                            return [4 /*yield*/, authClient.getAuthCodeUrl(validRequest)];
                        case 4:
                            navigateUrl = _a.sent();
                            redirectStartPage = (request && request.redirectStartPage) || window.location.href;
                            // Show the UI once the url has been created. Response will come back in the hash, which will be handled in the handleRedirectCallback function.
                            return [2 /*return*/, interactionHandler.initiateAuthRequest(navigateUrl, authCodeRequest, {
                                redirectTimeout: this.config.system.redirectNavigationTimeout,
                                redirectStartPage: redirectStartPage,
                                onRedirectNavigate: request.onRedirectNavigate
                            })];
                        case 5:
                            e_2 = _a.sent();
                            // If logged in, emit acquire token events
                            if (isLoggedIn) {
                                this.emitEvent(exports.EventType.ACQUIRE_TOKEN_FAILURE, exports.InteractionType.Redirect, null, e_2);
                            }
                            else {
                                this.emitEvent(exports.EventType.LOGIN_FAILURE, exports.InteractionType.Redirect, null, e_2);
                            }
                            serverTelemetryManager.cacheFailedRequest(e_2);
                            this.browserStorage.cleanRequestByState(validRequest.state);
                            throw e_2;
                        case 6: return [2 /*return*/];
                    }
                });
            });
        };
        // #endregion
        // #region Popup Flow
        /**
         * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
         * @param {@link (PopupRequest:type)}
         *
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        ClientApplication.prototype.acquireTokenPopup = function (request) {
            try {
                this.preflightBrowserEnvironmentCheck(exports.InteractionType.Popup);
            }
            catch (e) {
                // Since this function is syncronous we need to reject
                return Promise.reject(e);
            }
            // asyncPopups flag is true. Acquires token without first opening popup. Popup will be opened later asynchronously.
            if (this.config.system.asyncPopups) {
                return this.acquireTokenPopupAsync(request);
            }
            else {
                // asyncPopups flag is set to false. Opens popup before acquiring token.
                var popup = PopupHandler.openSizedPopup();
                return this.acquireTokenPopupAsync(request, popup);
            }
        };
        /**
         * Helper which obtains an access_token for your API via opening a popup window in the user's browser
         * @param {@link (PopupRequest:type)}
         *
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        ClientApplication.prototype.acquireTokenPopupAsync = function (request, popup) {
            return __awaiter(this, void 0, void 0, function () {
                var loggedInAccounts, validRequest, serverTelemetryManager, authCodeRequest, authClient, navigateUrl, interactionHandler, popupParameters, popupWindow, hash, result, isLoggingIn, e_3;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            loggedInAccounts = this.getAllAccounts();
                            if (loggedInAccounts.length > 0) {
                                this.emitEvent(exports.EventType.ACQUIRE_TOKEN_START, exports.InteractionType.Popup, request);
                            }
                            else {
                                this.emitEvent(exports.EventType.LOGIN_START, exports.InteractionType.Popup, request);
                            }
                            validRequest = this.preflightInteractiveRequest(request, exports.InteractionType.Popup);
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenPopup, validRequest.correlationId);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 7, , 8]);
                            return [4 /*yield*/, this.initializeAuthorizationCodeRequest(validRequest)];
                        case 2:
                            authCodeRequest = _a.sent();
                            return [4 /*yield*/, this.createAuthCodeClient(serverTelemetryManager, validRequest.authority)];
                        case 3:
                            authClient = _a.sent();
                            return [4 /*yield*/, authClient.getAuthCodeUrl(validRequest)];
                        case 4:
                            navigateUrl = _a.sent();
                            interactionHandler = new PopupHandler(authClient, this.browserStorage);
                            popupParameters = {
                                popup: popup
                            };
                            popupWindow = interactionHandler.initiateAuthRequest(navigateUrl, authCodeRequest, popupParameters);
                            return [4 /*yield*/, interactionHandler.monitorPopupForHash(popupWindow, this.config.system.windowHashTimeout)];
                        case 5:
                            hash = _a.sent();
                            // Remove throttle if it exists
                            ThrottlingUtils.removeThrottle(this.browserStorage, this.config.auth.clientId, authCodeRequest.authority, authCodeRequest.scopes);
                            return [4 /*yield*/, interactionHandler.handleCodeResponse(hash, authClient.authority, this.networkClient)];
                        case 6:
                            result = _a.sent();
                            isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
                            if (isLoggingIn) {
                                this.emitEvent(exports.EventType.LOGIN_SUCCESS, exports.InteractionType.Popup, result);
                            }
                            else {
                                this.emitEvent(exports.EventType.ACQUIRE_TOKEN_SUCCESS, exports.InteractionType.Popup, result);
                            }
                            return [2 /*return*/, result];
                        case 7:
                            e_3 = _a.sent();
                            if (loggedInAccounts.length > 0) {
                                this.emitEvent(exports.EventType.ACQUIRE_TOKEN_FAILURE, exports.InteractionType.Popup, null, e_3);
                            }
                            else {
                                this.emitEvent(exports.EventType.LOGIN_FAILURE, exports.InteractionType.Popup, null, e_3);
                            }
                            serverTelemetryManager.cacheFailedRequest(e_3);
                            this.browserStorage.cleanRequestByState(validRequest.state);
                            throw e_3;
                        case 8: return [2 /*return*/];
                    }
                });
            });
        };
        // #endregion
        // #region Silent Flow
        /**
         * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
         * - Any browser using a form of Intelligent Tracking Prevention
         * - If there is not an established session with the service
         *
         * In these cases, the request must be done inside a popup or full frame redirect.
         *
         * For the cases where interaction is required, you cannot send a request with prompt=none.
         *
         * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
         * you session on the server still exists.
         * @param {@link AuthorizationUrlRequest}
         *
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        ClientApplication.prototype.ssoSilent = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var silentTokenResult, e_4;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.preflightBrowserEnvironmentCheck(exports.InteractionType.Silent);
                            this.emitEvent(exports.EventType.SSO_SILENT_START, exports.InteractionType.Silent, request);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, this.acquireTokenByIframe(request)];
                        case 2:
                            silentTokenResult = _a.sent();
                            this.emitEvent(exports.EventType.SSO_SILENT_SUCCESS, exports.InteractionType.Silent, silentTokenResult);
                            return [2 /*return*/, silentTokenResult];
                        case 3:
                            e_4 = _a.sent();
                            this.emitEvent(exports.EventType.SSO_SILENT_FAILURE, exports.InteractionType.Silent, null, e_4);
                            throw e_4;
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * This function uses a hidden iframe to fetch an authorization code from the eSTS. To be used for silent refresh token acquisition and renewal.
         * @param {@link AuthorizationUrlRequest}
         * @param request
         */
        ClientApplication.prototype.acquireTokenByIframe = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var silentRequest, serverTelemetryManager, authCodeRequest, authClient, navigateUrl, e_5;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            // Check that we have some SSO data
                            if (StringUtils.isEmpty(request.loginHint) && StringUtils.isEmpty(request.sid) && (!request.account || StringUtils.isEmpty(request.account.username))) {
                                throw BrowserAuthError.createSilentSSOInsufficientInfoError();
                            }
                            // Check that prompt is set to none, throw error if it is set to anything else.
                            if (request.prompt && request.prompt !== PromptValue.NONE) {
                                throw BrowserAuthError.createSilentPromptValueError(request.prompt);
                            }
                            silentRequest = this.initializeAuthorizationRequest(__assign(__assign({}, request), { prompt: PromptValue.NONE }), exports.InteractionType.Silent);
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.ssoSilent, silentRequest.correlationId);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 6, , 7]);
                            return [4 /*yield*/, this.initializeAuthorizationCodeRequest(silentRequest)];
                        case 2:
                            authCodeRequest = _a.sent();
                            return [4 /*yield*/, this.createAuthCodeClient(serverTelemetryManager, silentRequest.authority)];
                        case 3:
                            authClient = _a.sent();
                            return [4 /*yield*/, authClient.getAuthCodeUrl(silentRequest)];
                        case 4:
                            navigateUrl = _a.sent();
                            return [4 /*yield*/, this.silentTokenHelper(navigateUrl, authCodeRequest, authClient)];
                        case 5: return [2 /*return*/, _a.sent()];
                        case 6:
                            e_5 = _a.sent();
                            serverTelemetryManager.cacheFailedRequest(e_5);
                            this.browserStorage.cleanRequestByState(silentRequest.state);
                            throw e_5;
                        case 7: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Use this function to obtain a token before every call to the API / resource provider
         *
         * MSAL return's a cached token when available
         * Or it send's a request to the STS to obtain a new token using a refresh token.
         *
         * @param {@link (SilentRequest:type)}
         *
         * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         *
         */
        ClientApplication.prototype.acquireTokenByRefreshToken = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var silentRequest, serverTelemetryManager, refreshTokenClient, e_6, isServerError, isInteractionRequiredError, isInvalidGrantError;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.emitEvent(exports.EventType.ACQUIRE_TOKEN_NETWORK_START, exports.InteractionType.Silent, request);
                            // block the reload if it occurred inside a hidden iframe
                            BrowserUtils.blockReloadInHiddenIframes();
                            silentRequest = __assign(__assign({}, request), this.initializeBaseRequest(request));
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, silentRequest.correlationId);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 4, , 7]);
                            return [4 /*yield*/, this.createRefreshTokenClient(serverTelemetryManager, silentRequest.authority)];
                        case 2:
                            refreshTokenClient = _a.sent();
                            return [4 /*yield*/, refreshTokenClient.acquireTokenByRefreshToken(silentRequest)];
                        case 3:
                            // Send request to renew token. Auth module will throw errors if token cannot be renewed.
                            return [2 /*return*/, _a.sent()];
                        case 4:
                            e_6 = _a.sent();
                            serverTelemetryManager.cacheFailedRequest(e_6);
                            isServerError = e_6 instanceof ServerError;
                            isInteractionRequiredError = e_6 instanceof InteractionRequiredAuthError;
                            isInvalidGrantError = (e_6.errorCode === BrowserConstants.INVALID_GRANT_ERROR);
                            if (!(isServerError && isInvalidGrantError && !isInteractionRequiredError)) return [3 /*break*/, 6];
                            return [4 /*yield*/, this.acquireTokenByIframe(request)];
                        case 5: return [2 /*return*/, _a.sent()];
                        case 6: throw e_6;
                        case 7: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Helper which acquires an authorization code silently using a hidden iframe from given url
         * using the scopes requested as part of the id, and exchanges the code for a set of OAuth tokens.
         * @param navigateUrl
         * @param userRequestScopes
         */
        ClientApplication.prototype.silentTokenHelper = function (navigateUrl, authCodeRequest, authClient) {
            return __awaiter(this, void 0, void 0, function () {
                var silentHandler, msalFrame, hash;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            silentHandler = new SilentHandler(authClient, this.browserStorage, this.config.system.navigateFrameWait);
                            return [4 /*yield*/, silentHandler.initiateAuthRequest(navigateUrl, authCodeRequest)];
                        case 1:
                            msalFrame = _a.sent();
                            return [4 /*yield*/, silentHandler.monitorIframeForHash(msalFrame, this.config.system.iframeHashTimeout)];
                        case 2:
                            hash = _a.sent();
                            // Handle response from hash string
                            return [2 /*return*/, silentHandler.handleCodeResponse(hash, authClient.authority, this.networkClient)];
                    }
                });
            });
        };
        // #endregion
        // #region Logout
        /**
         * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param {@link (EndSessionRequest:type)}
         */
        ClientApplication.prototype.logout = function (logoutRequest) {
            return __awaiter(this, void 0, void 0, function () {
                var validLogoutRequest, authClient, logoutUri, navigate, e_7;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            this.preflightBrowserEnvironmentCheck(exports.InteractionType.Redirect);
                            this.emitEvent(exports.EventType.LOGOUT_START, exports.InteractionType.Redirect, logoutRequest);
                            validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
                            return [4 /*yield*/, this.createAuthCodeClient(null, logoutRequest && logoutRequest.authority)];
                        case 1:
                            authClient = _a.sent();
                            logoutUri = authClient.getLogoutUri(validLogoutRequest);
                            this.emitEvent(exports.EventType.LOGOUT_SUCCESS, exports.InteractionType.Redirect, validLogoutRequest);
                            // Check if onRedirectNavigate is implemented, and invoke it if so
                            if (logoutRequest && typeof logoutRequest.onRedirectNavigate === "function") {
                                navigate = logoutRequest.onRedirectNavigate(logoutUri);
                                if (navigate !== false) {
                                    this.logger.verbose("Logout onRedirectNavigate did not return false, navigating");
                                    return [2 /*return*/, BrowserUtils.navigateWindow(logoutUri, this.config.system.redirectNavigationTimeout, this.logger)];
                                }
                                else {
                                    this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation");
                                }
                            }
                            else {
                                return [2 /*return*/, BrowserUtils.navigateWindow(logoutUri, this.config.system.redirectNavigationTimeout, this.logger)];
                            }
                            return [3 /*break*/, 3];
                        case 2:
                            e_7 = _a.sent();
                            this.emitEvent(exports.EventType.LOGOUT_FAILURE, exports.InteractionType.Redirect, null, e_7);
                            throw e_7;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        // #endregion
        // #region Account APIs
        /**
         * Returns all accounts that MSAL currently has data for.
         * (the account object is created at the time of successful login)
         * or empty array when no accounts are found
         * @returns {@link AccountInfo[]} - Array of account objects in cache
         */
        ClientApplication.prototype.getAllAccounts = function () {
            return this.isBrowserEnvironment ? this.browserStorage.getAllAccounts() : [];
        };
        /**
         * Returns the signed in account matching username.
         * (the account object is created at the time of successful login)
         * or null when no matching account is found.
         * This API is provided for convenience but getAccountById should be used for best reliability
         * @returns {@link AccountInfo} - the account object stored in MSAL
         */
        ClientApplication.prototype.getAccountByUsername = function (userName) {
            var allAccounts = this.getAllAccounts();
            if (!StringUtils.isEmpty(userName) && allAccounts && allAccounts.length) {
                return allAccounts.filter(function (accountObj) { return accountObj.username.toLowerCase() === userName.toLowerCase(); })[0] || null;
            }
            else {
                return null;
            }
        };
        /**
         * Returns the signed in account matching homeAccountId.
         * (the account object is created at the time of successful login)
         * or null when no matching account is found
         * @returns {@link AccountInfo} - the account object stored in MSAL
         */
        ClientApplication.prototype.getAccountByHomeId = function (homeAccountId) {
            var allAccounts = this.getAllAccounts();
            if (!StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {
                return allAccounts.filter(function (accountObj) { return accountObj.homeAccountId === homeAccountId; })[0] || null;
            }
            else {
                return null;
            }
        };
        /**
         * Returns the signed in account matching localAccountId.
         * (the account object is created at the time of successful login)
         * or null when no matching account is found
         * @returns {@link AccountInfo} - the account object stored in MSAL
         */
        ClientApplication.prototype.getAccountByLocalId = function (localAccountId) {
            var allAccounts = this.getAllAccounts();
            if (!StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {
                return allAccounts.filter(function (accountObj) { return accountObj.localAccountId === localAccountId; })[0] || null;
            }
            else {
                return null;
            }
        };
        // #endregion
        // #region Helpers
        /**
         *
         * Use to get the redirect uri configured in MSAL or null.
         * @returns {string} redirect URL
         *
         */
        ClientApplication.prototype.getRedirectUri = function (requestRedirectUri) {
            var redirectUri = requestRedirectUri || this.config.auth.redirectUri || BrowserUtils.getCurrentUri();
            return UrlString.getAbsoluteUrl(redirectUri, BrowserUtils.getCurrentUri());
        };
        /**
         * Use to get the post logout redirect uri configured in MSAL or null.
         *
         * @returns {string} post logout redirect URL
         */
        ClientApplication.prototype.getPostLogoutRedirectUri = function (requestPostLogoutRedirectUri) {
            var postLogoutRedirectUri = requestPostLogoutRedirectUri || this.config.auth.postLogoutRedirectUri || BrowserUtils.getCurrentUri();
            return UrlString.getAbsoluteUrl(postLogoutRedirectUri, BrowserUtils.getCurrentUri());
        };
        /**
         * Used to get a discovered version of the default authority.
         */
        ClientApplication.prototype.getDiscoveredDefaultAuthority = function () {
            return __awaiter(this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!!this.defaultAuthority) return [3 /*break*/, 2];
                            _a = this;
                            return [4 /*yield*/, AuthorityFactory.createDiscoveredInstance(this.config.auth.authority, this.config.system.networkClient, this.config.auth.protocolMode)];
                        case 1:
                            _a.defaultAuthority = _b.sent();
                            _b.label = 2;
                        case 2: return [2 /*return*/, this.defaultAuthority];
                    }
                });
            });
        };
        /**
         * Helper to check whether interaction is in progress.
         */
        ClientApplication.prototype.interactionInProgress = function () {
            // Check whether value in cache is present and equal to expected value
            return (this.browserStorage.getTemporaryCache(TemporaryCacheKeys.INTERACTION_STATUS_KEY, true)) === BrowserConstants.INTERACTION_IN_PROGRESS_VALUE;
        };
        /**
         * Creates an Authorization Code Client with the given authority, or the default authority.
         * @param authorityUrl
         */
        ClientApplication.prototype.createAuthCodeClient = function (serverTelemetryManager, authorityUrl) {
            return __awaiter(this, void 0, void 0, function () {
                var clientConfig;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.getClientConfiguration(serverTelemetryManager, authorityUrl)];
                        case 1:
                            clientConfig = _a.sent();
                            return [2 /*return*/, new AuthorizationCodeClient(clientConfig)];
                    }
                });
            });
        };
        /**
         * Creates an Silent Flow Client with the given authority, or the default authority.
         * @param authorityUrl
         */
        ClientApplication.prototype.createSilentFlowClient = function (serverTelemetryManager, authorityUrl) {
            return __awaiter(this, void 0, void 0, function () {
                var clientConfig;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.getClientConfiguration(serverTelemetryManager, authorityUrl)];
                        case 1:
                            clientConfig = _a.sent();
                            return [2 /*return*/, new SilentFlowClient(clientConfig)];
                    }
                });
            });
        };
        /**
         * Creates a Refresh Client with the given authority, or the default authority.
         * @param authorityUrl
         */
        ClientApplication.prototype.createRefreshTokenClient = function (serverTelemetryManager, authorityUrl) {
            return __awaiter(this, void 0, void 0, function () {
                var clientConfig;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.getClientConfiguration(serverTelemetryManager, authorityUrl)];
                        case 1:
                            clientConfig = _a.sent();
                            return [2 /*return*/, new RefreshTokenClient(clientConfig)];
                    }
                });
            });
        };
        /**
         * Creates a Client Configuration object with the given request authority, or the default authority.
         * @param requestAuthority
         */
        ClientApplication.prototype.getClientConfiguration = function (serverTelemetryManager, requestAuthority) {
            return __awaiter(this, void 0, void 0, function () {
                var discoveredAuthority, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!(!StringUtils.isEmpty(requestAuthority) && requestAuthority !== this.config.auth.authority)) return [3 /*break*/, 2];
                            return [4 /*yield*/, AuthorityFactory.createDiscoveredInstance(requestAuthority, this.config.system.networkClient, this.config.auth.protocolMode)];
                        case 1:
                            _a = _b.sent();
                            return [3 /*break*/, 4];
                        case 2: return [4 /*yield*/, this.getDiscoveredDefaultAuthority()];
                        case 3:
                            _a = _b.sent();
                            _b.label = 4;
                        case 4:
                            discoveredAuthority = _a;
                            return [2 /*return*/, {
                                authOptions: {
                                    clientId: this.config.auth.clientId,
                                    authority: discoveredAuthority,
                                    knownAuthorities: this.config.auth.knownAuthorities,
                                    cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
                                    clientCapabilities: this.config.auth.clientCapabilities,
                                    protocolMode: this.config.auth.protocolMode
                                },
                                systemOptions: {
                                    tokenRenewalOffsetSeconds: this.config.system.tokenRenewalOffsetSeconds
                                },
                                loggerOptions: {
                                    loggerCallback: this.config.system.loggerOptions.loggerCallback,
                                    piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled
                                },
                                cryptoInterface: this.browserCrypto,
                                networkInterface: this.networkClient,
                                storageInterface: this.browserStorage,
                                serverTelemetryManager: serverTelemetryManager,
                                libraryInfo: {
                                    sku: BrowserConstants.MSAL_SKU,
                                    version: version$1,
                                    cpu: "",
                                    os: ""
                                }
                            }];
                    }
                });
            });
        };
        /**
         * Helper to validate app environment before making a request.
         */
        ClientApplication.prototype.preflightInteractiveRequest = function (request, interactionType) {
            // block the reload if it occurred inside a hidden iframe
            BrowserUtils.blockReloadInHiddenIframes();
            // Check if interaction is in progress. Throw error if true.
            if (this.interactionInProgress()) {
                throw BrowserAuthError.createInteractionInProgressError();
            }
            return this.initializeAuthorizationRequest(request, interactionType);
        };
        /**
         * Helper to validate app environment before making an auth request
         * * @param request
         */
        ClientApplication.prototype.preflightBrowserEnvironmentCheck = function (interactionType) {
            // Block request if not in browser environment
            BrowserUtils.blockNonBrowserEnvironment(this.isBrowserEnvironment);
            // Block redirects if in an iframe
            BrowserUtils.blockRedirectInIframe(interactionType, this.config.system.allowRedirectInIframe);
            // Block auth requests inside a hidden iframe
            BrowserUtils.blockReloadInHiddenIframes();
            // Block redirects if memory storage is enabled but storeAuthStateInCookie is not
            if (interactionType === exports.InteractionType.Redirect &&
                this.config.cache.cacheLocation === exports.BrowserCacheLocation.MemoryStorage &&
                !this.config.cache.storeAuthStateInCookie) {
                throw BrowserConfigurationAuthError.createInMemoryRedirectUnavailableError();
            }
        };
        /**
         * Initializer function for all request APIs
         * @param request
         */
        ClientApplication.prototype.initializeBaseRequest = function (request) {
            var authority = request.authority;
            if (StringUtils.isEmpty(authority)) {
                authority = this.config.auth.authority;
            }
            var scopes = __spread(((request && request.scopes) || []));
            var correlationId = (request && request.correlationId) || this.browserCrypto.createNewGuid();
            var validatedRequest = __assign(__assign({}, request), {
                correlationId: correlationId,
                authority: authority,
                scopes: scopes
            });
            return validatedRequest;
        };
        ClientApplication.prototype.initializeServerTelemetryManager = function (apiId, correlationId, forceRefresh) {
            var telemetryPayload = {
                clientId: this.config.auth.clientId,
                correlationId: correlationId,
                apiId: apiId,
                forceRefresh: forceRefresh || false
            };
            return new ServerTelemetryManager(telemetryPayload, this.browserStorage);
        };
        /**
         * Helper to initialize required request parameters for interactive APIs and ssoSilent()
         * @param request
         */
        ClientApplication.prototype.initializeAuthorizationRequest = function (request, interactionType) {
            var redirectUri = this.getRedirectUri(request.redirectUri);
            var browserState = {
                interactionType: interactionType
            };
            var state = ProtocolUtils.setRequestState(this.browserCrypto, (request && request.state) || "", browserState);
            var nonce = request.nonce;
            if (StringUtils.isEmpty(nonce)) {
                nonce = this.browserCrypto.createNewGuid();
            }
            var authenticationScheme = request.authenticationScheme || exports.AuthenticationScheme.BEARER;
            var validatedRequest = __assign(__assign({}, this.initializeBaseRequest(request)), { redirectUri: redirectUri, state: state, nonce: nonce, responseMode: ResponseMode.FRAGMENT, authenticationScheme: authenticationScheme });
            // Check for ADAL SSO
            if (StringUtils.isEmpty(validatedRequest.loginHint)) {
                // Only check for adal token if no SSO params are being used
                var adalIdTokenString = this.browserStorage.getTemporaryCache(PersistentCacheKeys.ADAL_ID_TOKEN);
                if (!StringUtils.isEmpty(adalIdTokenString)) {
                    var adalIdToken = new AuthToken(adalIdTokenString, this.browserCrypto);
                    this.browserStorage.removeItem(PersistentCacheKeys.ADAL_ID_TOKEN);
                    if (adalIdToken.claims && adalIdToken.claims.upn) {
                        validatedRequest.loginHint = adalIdToken.claims.upn;
                    }
                }
            }
            this.browserStorage.updateCacheEntries(validatedRequest.state, validatedRequest.nonce, validatedRequest.authority);
            return validatedRequest;
        };
        /**
         * Generates an auth code request tied to the url request.
         * @param request
         */
        ClientApplication.prototype.initializeAuthorizationCodeRequest = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var generatedPkceParams, authCodeRequest;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.browserCrypto.generatePkceCodes()];
                        case 1:
                            generatedPkceParams = _a.sent();
                            authCodeRequest = __assign(__assign({}, request), { redirectUri: request.redirectUri, code: "", codeVerifier: generatedPkceParams.verifier });
                            request.codeChallenge = generatedPkceParams.challenge;
                            request.codeChallengeMethod = Constants.S256_CODE_CHALLENGE_METHOD;
                            return [2 /*return*/, authCodeRequest];
                    }
                });
            });
        };
        /**
         * Initializer for the logout request.
         * @param logoutRequest
         */
        ClientApplication.prototype.initializeLogoutRequest = function (logoutRequest) {
            var validLogoutRequest = __assign({ correlationId: this.browserCrypto.createNewGuid() }, logoutRequest);
            validLogoutRequest.postLogoutRedirectUri = this.getPostLogoutRedirectUri(logoutRequest ? logoutRequest.postLogoutRedirectUri : "");
            return validLogoutRequest;
        };
        /**
         * Emits events by calling callback with event message
         * @param eventType
         * @param interactionType
         * @param payload
         * @param error
         */
        ClientApplication.prototype.emitEvent = function (eventType, interactionType, payload, error) {
            var _this = this;
            if (this.isBrowserEnvironment) {
                var message_1 = {
                    eventType: eventType,
                    interactionType: interactionType || null,
                    payload: payload || null,
                    error: error || null,
                    timestamp: Date.now()
                };
                this.logger.info("Emitting event: " + eventType);
                this.eventCallbacks.forEach(function (callback, callbackId) {
                    _this.logger.verbose("Emitting event to callback " + callbackId + ": " + eventType);
                    callback.apply(null, [message_1]);
                });
            }
        };
        /**
         * Adds event callbacks to array
         * @param callback
         */
        ClientApplication.prototype.addEventCallback = function (callback) {
            if (this.isBrowserEnvironment) {
                var callbackId = this.browserCrypto.createNewGuid();
                this.eventCallbacks.set(callbackId, callback);
                this.logger.verbose("Event callback registered with id: " + callbackId);
                return callbackId;
            }
            return null;
        };
        ClientApplication.prototype.removeEventCallback = function (callbackId) {
            this.eventCallbacks.delete(callbackId);
            this.logger.verbose("Event callback " + callbackId + " removed.");
        };
        /**
         * Returns the logger instance
         */
        ClientApplication.prototype.getLogger = function () {
            return this.logger;
        };
        /**
         * Replaces the default logger set in configurations with new Logger with new configurations
         * @param logger Logger instance
         */
        ClientApplication.prototype.setLogger = function (logger) {
            this.logger = logger;
        };
        return ClientApplication;
    }());

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The PublicClientApplication class is the object exposed by the library to perform authentication and authorization functions in Single Page Applications
     * to obtain JWT tokens as described in the OAuth 2.0 Authorization Code Flow with PKCE specification.
     */
    var PublicClientApplication = /** @class */ (function (_super) {
        __extends(PublicClientApplication, _super);
        /**
         * @constructor
         * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
         *
         * Important attributes in the Configuration object for auth are:
         * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
         * - authority: the authority URL for your application.
         * - redirect_uri: the uri of your application registered in the portal.
         *
         * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
         * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
         * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
         * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
         * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
         * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
         *
         * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
         * Full B2C functionality will be available in this library in future versions.
         *
         * @param {@link (Configuration:type)} configuration object for the MSAL PublicClientApplication instance
         */
        function PublicClientApplication(configuration) {
            return _super.call(this, configuration) || this;
        }
        /**
         * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
         * any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param {@link (RedirectRequest:type)}
         */
        PublicClientApplication.prototype.loginRedirect = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    return [2 /*return*/, this.acquireTokenRedirect(request || DEFAULT_REQUEST)];
                });
            });
        };
        /**
         * Use when initiating the login process via opening a popup window in the user's browser
         *
         * @param {@link (PopupRequest:type)}
         *
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        PublicClientApplication.prototype.loginPopup = function (request) {
            return this.acquireTokenPopup(request || DEFAULT_REQUEST);
        };
        /**
         * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
         *
         * @param {@link (SilentRequest:type)}
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        PublicClientApplication.prototype.acquireTokenSilent = function (request) {
            return __awaiter(this, void 0, void 0, function () {
                var silentRequest, serverTelemetryManager, silentAuthClient, cachedToken, e_1, tokenRenewalResult, tokenRenewalError_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.preflightBrowserEnvironmentCheck(exports.InteractionType.Silent);
                            silentRequest = __assign(__assign(__assign({}, request), this.initializeBaseRequest(request)), { forceRefresh: request.forceRefresh || false });
                            this.emitEvent(exports.EventType.ACQUIRE_TOKEN_START, exports.InteractionType.Silent, request);
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 4, , 9]);
                            serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, silentRequest.correlationId);
                            return [4 /*yield*/, this.createSilentFlowClient(serverTelemetryManager, silentRequest.authority)];
                        case 2:
                            silentAuthClient = _a.sent();
                            return [4 /*yield*/, silentAuthClient.acquireCachedToken(silentRequest)];
                        case 3:
                            cachedToken = _a.sent();
                            this.emitEvent(exports.EventType.ACQUIRE_TOKEN_SUCCESS, exports.InteractionType.Silent, cachedToken);
                            return [2 /*return*/, cachedToken];
                        case 4:
                            e_1 = _a.sent();
                            _a.label = 5;
                        case 5:
                            _a.trys.push([5, 7, , 8]);
                            return [4 /*yield*/, this.acquireTokenByRefreshToken(silentRequest)];
                        case 6:
                            tokenRenewalResult = _a.sent();
                            this.emitEvent(exports.EventType.ACQUIRE_TOKEN_SUCCESS, exports.InteractionType.Silent, tokenRenewalResult);
                            return [2 /*return*/, tokenRenewalResult];
                        case 7:
                            tokenRenewalError_1 = _a.sent();
                            this.emitEvent(exports.EventType.ACQUIRE_TOKEN_FAILURE, exports.InteractionType.Silent, null, tokenRenewalError_1);
                            throw tokenRenewalError_1;
                        case 8: return [3 /*break*/, 9];
                        case 9: return [2 /*return*/];
                    }
                });
            });
        };
        return PublicClientApplication;
    }(ClientApplication));

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    var stubbedPublicClientApplication = {
        acquireTokenPopup: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        acquireTokenRedirect: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        acquireTokenSilent: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        getAllAccounts: function () {
            return [];
        },
        getAccountByHomeId: function () {
            return null;
        },
        getAccountByUsername: function () {
            return null;
        },
        getAccountByLocalId: function () {
            return null;
        },
        handleRedirectPromise: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        loginPopup: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        loginRedirect: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        logout: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        ssoSilent: function () {
            return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError);
        },
        addEventCallback: function () {
            return null;
        },
        removeEventCallback: function () {
            return;
        },
        getLogger: function () {
            throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
        },
        setLogger: function () {
            return;
        }
    };

    exports.AuthError = AuthError;
    exports.AuthErrorMessage = AuthErrorMessage;
    exports.BrowserAuthError = BrowserAuthError;
    exports.BrowserAuthErrorMessage = BrowserAuthErrorMessage;
    exports.BrowserConfigurationAuthError = BrowserConfigurationAuthError;
    exports.BrowserConfigurationAuthErrorMessage = BrowserConfigurationAuthErrorMessage;
    exports.BrowserUtils = BrowserUtils;
    exports.InteractionRequiredAuthError = InteractionRequiredAuthError;
    exports.Logger = Logger;
    exports.PublicClientApplication = PublicClientApplication;
    exports.StringUtils = StringUtils;
    exports.UrlString = UrlString;
    exports.stubbedPublicClientApplication = stubbedPublicClientApplication;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=msal-browser.js.map
;
/**
 * angular-environment Plugin
 *
 * An useful plugin that allows you to set up different information
 * such as api endpoints, urls, variables, etc, based on the context of scripts execution:
 * development, stage, production or any other custom environment you want to create.
 *
 * For more information, issues, etc, check out:
 * http://github.com/juanpablob/angular-environment
 */

angular.module('environment', []).
	provider('envService', function() {

		'use strict';

		var local = {};

		local.pregQuote = function(string, delimiter) {
			return (string + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
		};

		local.stringToRegex = function(string) {
			return new RegExp(local.pregQuote(string).replace(/\\\*/g, '.*').replace(/\\\?/g, '.'), 'g');
		};

		this.environment = 'development'; // default
		this.data = {}; // user defined environments data

		/**
		 * config() allow pass as object the
		 * desired environments with their domains
		 * and variables
		 *
		 * @param {Object} config
		 * @return {Void}
		 */
		this.config = function(config) {
			this.data = config;
		};

		/**
		 * set() set the desired environment
		 * based on the passed string
		 *
		 * @param {String} environment
		 * @return {Void}
		 */
		this.set = function(environment) {
			this.environment = environment;
		};

		/**
		 * get() returns the current environment
		 *
		 * @return {Void}
		 */
		this.get = function() {
			return this.environment;
		};

		/**
		 * read() returns the desired variable based
		 * on passed argument
		 *
		 * @param {String} variable
		 * @return {Void}
		 */
		this.read = function(variable) {
			if (typeof variable === 'undefined' || variable === '' || variable === 'all') {
				return this.data.vars[this.get()];
			}
			else if (typeof this.data.vars[this.get()][variable] === 'undefined') {
				return this.data.vars.defaults[variable];
			}

			return this.data.vars[this.get()][variable];
		};

		/**
		 * is() checks if the passed environment
		 * matches with the current environment
		 *
		 * @param {String} environment
		 * @return {Boolean}
		 */
		this.is = function(environment) {
			return (environment === this.environment);
		};

		/**
		 * check() looks for a match between
		 * the actual domain (where the script is running)
		 * and any of the domains under env constant in
		 * order to set the running environment
		 *
		 * @return {Void}
		 */
		this.check = function() {
			var	self = this,
					location = window.location.host,
					matches = [],
					keepGoing = true;

			angular.forEach(this.data.domains, function(v, k) {
				angular.forEach(v, function(v) {
					if (location.match(local.stringToRegex(v))) {
						matches.push({
							environment: k,
							domain: v
						});
					}
				});
			});

			angular.forEach(matches, function(v, k) {
				if (keepGoing) {
					if (location === v.domain) {
						keepGoing = false;
					}
					console.log(v.domain);
					self.environment = v.environment;
				}
			});
		};

		this.$get = function() {
			return this;
		};
	});
;
var app = angular.module('faom', ['environment']);

app.config(function ($httpProvider, envServiceProvider, envProvider) {
    $httpProvider.interceptors.push('jsonpInterceptor');
    envServiceProvider.config(envProvider.config);
    envServiceProvider.check();
});


app.factory('jsonpInterceptor', function ($timeout, $window, $q) {
    return {
        'request': function (config) {
            if (config.method === 'JSONP') {
                var callbackId = angular.callbacks.counter.toString(36);
                config.callbackName = 'angular_callbacks_' + callbackId;
                config.url = config.url.replace('JSON_CALLBACK', config.callbackName);

                $timeout(function () {
                    $window[config.callbackName] = angular.callbacks['_' + callbackId];
                }, 0, false);
            }

            return config;
        },

        'response': function (response) {
            var config = response.config;
            if (config.method === 'JSONP') {
                delete $window[config.callbackName]; // cleanup
            }

            return response;
        },

        'responseError': function (rejection) {
            var config = rejection.config;
            if (config.method === 'JSONP') {
                delete $window[config.callbackName]; // cleanup
            }

            return $q.reject(rejection);
        }
    };
});;
angular.module('faom').constant('realTimeConstants', {
    maximumExportDays: 90
});
angular.module('faom').constant('roleNameConstants', {
    agency: "agency",
    carrier: "carrier",
    distributor: "distributor",
    donorLocation: "donorlocation",
    donor: "donor",
    donorExecutive: "donorexec",
    fano: "fano",
    foodbankAdministrator: "foodbankadmin",
    foodbankRealtimeCoordinator: "foodbankrtcoord",
    foodbankUser: "foodbankuser",
    foodbankDriver: "foodbankdriver",
    foodbankEpantryCoordinator: "foodbankepancoord",  //This is foodbank orderAhead
    foodbankLogisticsCoordinator: "foodbanklogisticscoord",
    transportationProvider: "transprovider",
    foodcoordStateAssociations: "foodcoordstateasso",
    foodcoordCoops: "foodcoordcoops",
    bulkofferDonor: "bulkofferdonor",
    lightweightPosting: "lightweightposting"
})
;
angular.module('faom').constant('produceMatchingConstants', {
    produceMatchingGroup: 'Produce Matching Group',
    manageOffers: 'Manage Offers',
    browseOrders: 'Browse And Order',
    viewOrders: 'View Your Orders',
    readOnlyManageOffers: 'Read-Only Manage Offers',
    maxAdminFeePerLb: 0.02,
    donorUserTypes: {
        nationalCorporate: 0,
        produceMatching: 1,
        locationOnly: 2,
        marketplace: 3,
    }
})
;
angular.module('faom').constant('entityTypesCodeConstants', {
    FoodBank: 0,
    Agency: 1,
    Donor: 2,
    DonorLocation: 3,
    Distributor: 4,
    Carrier: 5,
    Coops: 6,
    StateAssociation: 7,
    FoodBankLocation: 8,
    Cluster: 9,
    TransportationProvider: 10,
    NationalOffice: 11
});
angular.module('faom').factory('claimsService', ['roleNameConstants', 'produceMatchingConstants', 'entityTypesCodeConstants', '$rootScope', '$window', function (roleNameConstants, produceMatchingConstants, entityTypesCodeConstants, $rootScope, $window) {
    var vm = this;
    vm.sessionMetadata = null;
    vm.metadataObject = {
        userRole: "",
        userName: "User",
        defaultControllerPath: "",
        defaultRolePrefix: "",
        roleHelpResourceStateName: "",
        isFoodBankTypeRole: function () {
            return vm.checkIfRoleIsFoodBankType(this.userRole);
        },
        dashboardStateName: "",
        hasRole: true,
        isAdmin: false,
        isLocked: false,
        idTokenClaims: {}
    };
    vm.lightweightPostingAccount = null;

    //formats the claims received from the token
    vm.parseClaim = function (claims) {
        if (claims != null) {
            var json = claims.split(",").map(function (claim) {
                return claim.trim();
            });
            return json;
        } else return [];
    }
    //parameter used so it can be used for global purposes
    vm.checkIfRoleIsFoodBankType = function (role) {
        //added 'foodbank' to support some legacy
        switch (role.toLowerCase()) {
            case 'foodbank':
                return true;
            case roleNameConstants.foodbankAdministrator:
                return true;
            case roleNameConstants.foodbankRealtimeCoordinator:
                return true;
            case roleNameConstants.foodbankUser:
                return true;
            case roleNameConstants.foodbankEpantryCoordinator:
                return true;
            case roleNameConstants.foodcoordCoops:
                return true;
            case roleNameConstants.foodcoordStateAssociations:
                return true;
            case roleNameConstants.foodbankLogisticsCoordinator:
                return true;
            default:
                return false;
        }
    }

    vm.getDataForCurrentUser = function (userRole) {
        vm.metadataObject.userRole = userRole ? userRole.toLowerCase() : '';
        switch (vm.metadataObject.userRole) {
            case roleNameConstants.agency:
                vm.metadataObject.defaultControllerPath = "/Agency";
                vm.metadataObject.dashboardStateName = "app.receipts.new";
                vm.metadataObject.roleHelpResourceStateName = "app.agency-help-resources";
                vm.metadataObject.defaultRolePrefix = "Agency";
                break;
            case roleNameConstants.carrier:
                vm.metadataObject.defaultRolePrefix = "Carrier";
                vm.metadataObject.defaultControllerPath = "/Carrier";
                vm.metadataObject.dashboardStateName = "app.carrier-new-transaction";
                vm.metadataObject.roleHelpResourceStateName = "app.carrier-help-resources";
                break;
            case roleNameConstants.distributor:
                vm.metadataObject.defaultRolePrefix = "Distributor";
                vm.metadataObject.defaultControllerPath = "/Distributor";
                vm.metadataObject.dashboardStateName = "app.distributor-new-transaction";
                vm.metadataObject.roleHelpResourceStateName = "app.distributor-help-resources";
                break;
            case roleNameConstants.donorLocation:
                vm.metadataObject.defaultControllerPath = "/Donor";
                vm.metadataObject.defaultRolePrefix = "Donor";
                vm.metadataObject.dashboardStateName = "app.donor-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.donor-help-resources";
                break;
            case roleNameConstants.donorExecutive:
                vm.metadataObject.defaultControllerPath = "/Donor";
                vm.metadataObject.defaultRolePrefix = "Donor";
                vm.metadataObject.dashboardStateName = "app.donor-executive-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.donor-help-resources";
                break;
            case roleNameConstants.donor:
                vm.metadataObject.defaultControllerPath = "/Donor";
                vm.metadataObject.dashboardStateName = "app.donor-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.donor-help-resources";
                vm.metadataObject.defaultRolePrefix = "Donor";
                break;
            case roleNameConstants.bulkofferDonor:
                vm.metadataObject.defaultControllerPath = "/Donor";
                vm.metadataObject.dashboardStateName = 'app.marketplace-supplier-dashboard'
                vm.metadataObject.roleHelpResourceStateName = "app.donor-help-resources";
                vm.metadataObject.defaultRolePrefix = "Donor";
                break;
            case roleNameConstants.fano:
                vm.metadataObject.defaultControllerPath = "/FeedingAmerica";
                vm.metadataObject.dashboardStateName = "app.fa-dashboard";
                vm.metadataObject.defaultRolePrefix = "FeedingAmerica";
                vm.metadataObject.roleHelpResourceStateName = "app.fano-help-resources";
                vm.metadataObject.isAdmin = true;
                break;
            case roleNameConstants.foodbankAdministrator:
                vm.metadataObject.defaultControllerPath = "/FoodBank";
                vm.metadataObject.dashboardStateName = "app.foodbank-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                vm.metadataObject.defaultRolePrefix = "FoodBank";
                vm.metadataObject.isAdmin = true;
                break;
            case roleNameConstants.foodbankRealtimeCoordinator:
                vm.metadataObject.defaultControllerPath = "/FoodBank";
                vm.metadataObject.dashboardStateName = "app.foodbank-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                vm.metadataObject.defaultRolePrefix = "FoodBank";
                break;
            case roleNameConstants.foodbankLogisticsCoordinator:
                vm.metadataObject.defaultControllerPath = "/FoodBank";
                vm.metadataObject.dashboardStateName = "app.foodbank-distributor-transactions";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                vm.metadataObject.defaultRolePrefix = "FoodBank";
                break;
            case roleNameConstants.foodcoordStateAssociations:
                vm.metadataObject.defaultControllerPath = "/StateAssociation";
                vm.metadataObject.dashboardStateName = "app.offer-wizard.landing-page";
                vm.metadataObject.roleHelpResourceStateName = "#";
                vm.metadataObject.defaultRolePrefix = "StateAssociation";
                break;
            case roleNameConstants.foodcoordCoops:
                vm.metadataObject.defaultControllerPath = "/Coops";
                vm.metadataObject.dashboardStateName = "app.offer-wizard.landing-page";
                vm.metadataObject.roleHelpResourceStateName = "#";
                vm.metadataObject.defaultRolePrefix = "Coops";
                break;
            case roleNameConstants.foodbankUser:
                vm.metadataObject.defaultControllerPath = "/FoodBank";
                vm.metadataObject.dashboardStateName = "app.foodbank-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                vm.metadataObject.defaultRolePrefix = "FoodBank";
                break;
            case roleNameConstants.foodbankEpantryCoordinator:
                vm.metadataObject.defaultControllerPath = "/FoodBank";
                vm.metadataObject.dashboardStateName = "app.orderahead-dashboard";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                vm.metadataObject.defaultRolePrefix = "FoodBank";
                break;
            case roleNameConstants.transportationProvider:
                vm.metadataObject.defaultRolePrefix = "TransportationProvider";
                vm.metadataObject.defaultControllerPath = "/TransportationProvider";
                vm.metadataObject.dashboardStateName = "app.transportation-provider-transactions";
                vm.metadataObject.roleHelpResourceStateName = "app.transportationprovider-help-resources";
                break;
            case roleNameConstants.foodbankDriver:
                vm.metadataObject.defaultControllerPath = "/UnregisteredUser";
                vm.metadataObject.dashboardStateName = "unregistered-user";
                break;
            case roleNameConstants.lightweightPosting:
                vm.metadataObject.defaultControllerPath = (vm.getCurrentAccount().username.indexOf('foodbank_') > -1 ||
                    vm.getCurrentAccount().username.indexOf('stateassociation_') > -1 ||
                    vm.getCurrentAccount().username.indexOf('coop_') > -1) ? '/FoodBank' : '/Donor';
                vm.metadataObject.defaultRolePrefix = "LightweightPosting";
                vm.metadataObject.roleHelpResourceStateName = "app.foodbank-help-resources";
                break;
            default:
                vm.metadataObject = {
                    defaultControllerPath: "/UnregisteredUser",
                    dashboardStateName: "unregistered-user",
                    hasRole: false
                };
        }

        return vm.metadataObject;
    };

    vm.cachedUserAccount = null;
    vm.cachedUserAccountTime = null;
    vm.CACHE_USER_ACCOUNT_DURATION_SECONDS = 10;

    vm.getCurrentAccount = function () {
        if (vm.lightweightPostingAccount) {
            return vm.lightweightPostingAccount.account;
        }

        var accounts = $rootScope.msal.getAllAccounts();
        var currentAccount = JSON.parse(localStorage.getItem('currentAccount') || '{}');
        var username = currentAccount['username'];
        var index = accounts.map(function (x) { return x.username; }).indexOf(username);
        if (index === -1) {
            return null;
        }
        return accounts[index];
    }

    vm.getUserContext = function () {
        var userAccount = null;
        if (vm.cachedUserAccount && vm.cachedUserAccountTime) {
            var durationSinceLastUserAccountCache = ((new Date()) - vm.cachedUserAccountTime) / 1000;

            if (durationSinceLastUserAccountCache < vm.CACHE_USER_ACCOUNT_DURATION_SECONDS)
                userAccount = vm.cachedUserAccount;
        }

        if (!userAccount) {
            var userAccount = vm.getCurrentAccount();
            vm.cachedUserAccount = userAccount;
            vm.cachedUserAccountTime = new Date();
        }

        if (userAccount != null) {
            if (vm.sessionMetadata == null || (vm.sessionMetadata.userName !== userAccount.name)) {
                var idTokenClaims = userAccount.idTokenClaims;
                var userRole = idTokenClaims.extension_Role;
                vm.sessionMetadata = vm.getDataForCurrentUser(userRole);
                vm.sessionMetadata.userName = userAccount.name;
                vm.sessionMetadata.isLocked = false;
                vm.sessionMetadata.isDeactivated = false;
                vm.sessionMetadata.idTokenClaims = idTokenClaims;
                vm.updateExtensionsToMap(idTokenClaims);
            }
            return vm.sessionMetadata;
        } else {
            vm.metadataObject.hasRole = false;
            return vm.metadataObject;
        }
    }

    vm.checkIfFeatureIsReadOnly = function (featureName, subfeatureName) {
        //subfeature is optional if checking top level only
        var extensionsToMap = vm.getUserContext().extensionsToMap;
        if (extensionsToMap === null || typeof extensionsToMap === 'undefined') {
            return false;
        }
        if (subfeatureName === null || typeof subfeatureName === 'undefined') {
            return extensionsToMap.hasOwnProperty('Read-Only ' + featureName);
        } else {
            if (extensionsToMap.hasOwnProperty(featureName)) {
                return extensionsToMap[featureName].filter(function (item) { return item.indexOf('Read-Only ' + subfeatureName) >= 0 }).length > 0;
            } else {
                return false;
            }
        }
    }

    vm.getExtensionsToMapFromToken = function (token) {
        var extensionsToMap = {};

        try {
            var parsedFeatures = vm.parseClaim(token.extension_Features);

            parsedFeatures.forEach(function (value, i) {
                extensionsToMap[parsedFeatures[i]] = vm.parseClaim(
                    token["extension_SubFeatures_" + i]
                );
            });
        } catch { }

        return extensionsToMap;
    }

    vm.getExtensionsFromSessionMenu = function (appSessionMenu) {
        var extensionsToMap = {};

        try {
            var sessionMenu = {};
            appSessionMenu.forEach((value, i) => {
                sessionMenu[Object.keys(value)[0]] = Object.values(value)[0];
            });
            extensionsToMap = sessionMenu;
        } catch { }

        return extensionsToMap;
    }

    vm.updateExtensionsToMap = function (idTokenClaims) {
        try {
            var extensionsToMap = null;

            if (idTokenClaims) {
                extensionsToMap = vm.getExtensionsToMapFromToken(idTokenClaims);
            }

            if ($rootScope.app && $rootScope.app.session && $rootScope.app.session.Menu && $rootScope.app.session.Menu.length && vm.sessionMetadata) {
                extensionsToMap = vm.getExtensionsFromSessionMenu($rootScope.app.session.Menu);
            }

            if (extensionsToMap !== null) {
                vm.sessionMetadata.extensionsToMap = extensionsToMap;
            }
        } catch { }
    };

    $rootScope.$on('App.SessionUpdated',
        function (event, args) {
            vm.updateExtensionsToMap();
        });

    vm.isLightweightPostingDonor = function () {
        return vm.isLightweightPostingUser() && vm.getCurrentAccount().username.indexOf('donor_') > -1
    }

    vm.isLightweightPostingFoodBank = function () {
        return vm.isLightweightPostingUser() && vm.getCurrentAccount().username.indexOf('foodbank_') > -1
    }

    vm.isLightweightPostingStateAssociation = function () {
        return vm.isLightweightPostingUser() && vm.getCurrentAccount().username.indexOf('stateassociation_') > -1
    }

    vm.isLightweightPostingCoop = function () {
        return vm.isLightweightPostingUser() && vm.getCurrentAccount().username.indexOf('coop_') > -1
    }

    vm.isLightweightPostingUser = function () {
        var userContext = vm.getUserContext();

        return !!(userContext && roleNameConstants && userContext.userRole === roleNameConstants.lightweightPosting);
    };

    vm.setLightweightPostingAccount = function (account) {
        vm.lightweightPostingAccount = account;
    };

    vm.isProducePurchasingEnabled = function () {
        return !!($rootScope.app && ($rootScope.app.getConfigValue('Produce.Purchasing.Enabled', 'false', true) === true));
    };

    return {
        getUserContext: vm.getUserContext,
        roleNameConstants: roleNameConstants,
        produceMatchingConstants: produceMatchingConstants,
        entityTypesCodeConstants: entityTypesCodeConstants,
        checkIfFeatureIsReadOnly: vm.checkIfFeatureIsReadOnly,
        checkIfRoleIsFoodBankType: vm.checkIfRoleIsFoodBankType, // This is used in instances where we are checking with a role name outside the service
        isLightweightPostingUser: vm.isLightweightPostingUser,
        isLightweightPostingDonor: vm.isLightweightPostingDonor,
        isLightweightPostingFoodBank: vm.isLightweightPostingFoodBank,
        isLightweightPostingStateAssociation: vm.isLightweightPostingStateAssociation,
        isLightweightPostingCoop: vm.isLightweightPostingCoop,
        setLightweightPostingAccount: vm.setLightweightPostingAccount,
        isProducePurchasingEnabled: vm.isProducePurchasingEnabled
    };
}
])
;
angular.module('faom').factory('organizationService', ['$http', function ($http) {

    var lockedStateName = 'app.organization-is-locked';
    var lockedControllerPath = '/orgLocked';
    var deactivatedStateName = 'no-org';

    return {
        lockedStateName: lockedStateName,
        deactivatedStateName: deactivatedStateName,
        lockedControllerPath: lockedControllerPath
    };
}
]);
angular.module('faom').factory('msalService', ['$window', 'envService', 'claimsService', '$rootScope', 'browserUtilityService',
    function ($window, envService, claimsService, $rootScope, browserUtilityService) {
        var service = {};
        var requestObj = {
            scopes: [envService.read('scopes')]
        };

        var origin = window.location.origin;
        var msalConfig = {
            auth: {
                clientId: envService.read('clientId'), //This is your client ID
                authority:
                    envService.read('authority'),
                knownAuthorities: [envService.read('baseAuthority')],
                redirectUri: origin + "/Preloader",
                postLogoutRedirectUri: origin,
                navigateToLoginRequestUrl: false
            },
            cache: {
                cacheLocation: 'localStorage',
                storeAuthStateInCookie: browserUtilityService.isInternetExplorer || browserUtilityService.isEdge
            }
        };

        // This flag is set to true immediately after all key auth initialization is complete and the user is fully logged in
        // Note: global state used so that parts of the application that do not (or can not) access the msalService are able
        // to take advantage of this information.
        $window.appAuthInitializationComplete = false;

        // A length of time after a login request to prevent subsequent login requests.
        var LOGIN_LOCK_DURATION_SECONDS = 10;

        // How long a target redirect URL (used in post-auth redirect) stays active in local storage
        // This duration effectively locks out any other accidental interpretations of post-auth redirects
        // while it is active. Note that this should ideally be long enough for most users to complete the
        // steps needed to sign in.
        var REDIRECT_SNAPSHOT_LIFESPAN_SECONDS = 300; // 5 Minutes (60*5)

        // Used to set a time-limited login lock, valid for current browser window
        // Prevents subsequent login requests until either cleared or after LOGIN_LOCK_DURATION_SECONDS
        var setLoginLock = function () {
            $window.loginLockTime = new Date();
        }

        // Removes the login lock, regardless of duration since set
        var clearLoginLock = function () {
            $window.loginLockTime = null;
        }

        var setAuthProcessingComplete = function () {
            // This is referenced in preloader.component.js as a temporary measure [January 2023]
            // ToDo: Remove when possible, ideally before MSAL refactor
            $window.appAuthInitializationComplete = true;
            $rootScope.$broadcast('appAuthInitializationComplete');
        }

        service.isAuthProcessingComplete = function () {
            try {
                return $window.appAuthInitializationComplete || false;
            } catch (error) {
                return false;
            }
        }

        // Returns true if login is locked, false otherwise
        var checkIsLoginLocked = function () {
            if (!$window.loginLockTime)
                return false;

            var durationSinceLastLock = ((new Date()) - $window.loginLockTime) / 1000;
            return durationSinceLastLock < LOGIN_LOCK_DURATION_SECONDS;
        }

        /*
         * Saves a snapshot of the URL that the user is trying to reach.
         * Used for post-login redirects.
         * Snapshot Conditions:
         *  (1) No Prior Recent Snapshot
         *  (2) Snapshot URL is not '/Preloader', '/account/login', '/' or ''
         * */
        service.snapshotTargetUrl = function () {
            try {
                var targetUrl = $window.location.pathname + $window.location.hash;

                if (targetUrl.indexOf('/Preloader') === -1
                    && targetUrl != '/'
                    && targetUrl != '/account/login'
                    && targetUrl != '') {
                    var existingSnapshot = service.getLastActiveRedirectSnapshot();

                    if (!existingSnapshot) {
                        console.log('[Auth][MSAL][STU] Creating Potential URL Snapshot for Post-Auth Redirect: "' + targetUrl + "'");
                        localStorage.setItem('targetUrl', targetUrl);
                        localStorage.setItem('targetUrlCaptureTime', new Date());
                    }
                }
            } catch (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Failed to snapshot local URL", { error: error });
                }
            }
        }

        /*
         * Obtains the last known (active) URL that the user is attempting to reach.
         * Active URLs are ones that are saved within REDIRECT_SNAPSHOT_LIFESPAN_SECONDS ago
         * */
        service.getLastActiveRedirectSnapshot = function () {
            try {
                var lastRedirectSnapshotTimeStored = localStorage.getItem("targetUrlCaptureTime");
                if (lastRedirectSnapshotTimeStored !== null) {
                    var lastRedirectSnapshotTime = Date.parse(lastRedirectSnapshotTimeStored);

                    if (!isNaN(lastRedirectSnapshotTime)) {
                        var durationSinceLastSnapshot = ((new Date()) - lastRedirectSnapshotTime) / 1000;

                        if (durationSinceLastSnapshot < REDIRECT_SNAPSHOT_LIFESPAN_SECONDS) {
                            // redirect is still active
                            return localStorage.getItem("targetUrl");
                        } else {
                            console.log('[Auth][MSAL][LARS] Potentially Relevant Post-Auth Redirect Snapshot Expired (Duration: ' + durationSinceLastSnapshot + ' Seconds)');
                        }
                    }
                }
            } catch (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Failed to identify existing snapshot URL or valid time", { error: error });
                }
            }
        }

        /*
         * Clear prior URL snapshot and timing information.
         * Call this method after successful processing of a saved destination URL
         * */
        service.clearActiveUrlSnapshot = function () {
            localStorage.removeItem("targetUrl");
            localStorage.removeItem("targetUrlCaptureTime");
        }

        var cachedLightweightPostingAccount = null;
        var isLightweightPostingAccountValid = false;

        try {
            cachedLightweightPostingAccount = JSON.parse(localStorage.getItem('lightweightPostingAccount'));
            isLightweightPostingAccountValid = !!(cachedLightweightPostingAccount &&
                cachedLightweightPostingAccount.account &&
                cachedLightweightPostingAccount.account.idTokenClaims &&
                cachedLightweightPostingAccount.account.idTokenClaims.exp > (new Date().getTime() / 1000));
        } catch { }

        var bootstrapAuth = $window.location.pathname != '/account/login'
            && $window.location.pathname != '/account/login/reset'
            && isLightweightPostingAccountValid === false;

        console.log('[Auth][MSAL] Initializing App Auth State');
        service.userAgentApplication = new msal.PublicClientApplication(msalConfig);
        $rootScope.msal = service.userAgentApplication;

        if (bootstrapAuth) {
            /*
            * ///////////////////////////////////////////////////////
            * ///////////////////////////////////////////////////////
            * Main Application Authentication Startup Below
            */

            var urlNotExempted = $window.location.href.indexOf('join/continue') === -1
                && $window.location.href.indexOf('join/volunteer/continue') === -1
                && $window.location.href.indexOf('/volunteers/signup') === -1
                && $window.location.href.indexOf('/agency/join/') === -1
                && $window.location.href.indexOf('/donate') === -1;

            console.log('[Auth][MSAL] Bootstrap Eligible');
            console.log('Relevant Url for Auth Exception Tracking: ' + $window.location.href);
            console.log('URL Exempted?: ' + (!urlNotExempted ? 'Yes' : 'No'));

            // Before processing auth status, capture* the target URL that the user is attempting to visit and
            // save to local storage (*see method for specific conditions).
            // Note: this is cleared (see clearActiveUrlSnapshot call below) if it turns out that the user is already
            // authenticated. In that case, a post-login redirect will not be required.
            service.snapshotTargetUrl();

            setLoginLock();

            service.userAgentApplication.handleRedirectPromise().then(function (response) {
                clearLoginLock();
                if (response) {
                    // (This path executes after the user is redirected back into the application after authentication with B2C)
                    console.log('[Auth][MSAL][HRD-A] User Agent Redirect Promise Finished - With Response (After B2C Redirect)');
                    var usedAccounts = JSON.parse(localStorage.getItem('usedAccounts') || '[]');
                    var currentAccount = response.account;
                    // Remove account before adding new from respose; fixes duplicate issue
                    usedAccounts = usedAccounts.filter(function (x) { return x['username'] !== currentAccount['username']; });
                    usedAccounts.push(currentAccount);
                    localStorage.setItem('usedAccounts', JSON.stringify(usedAccounts));
                    localStorage.setItem('currentAccount', JSON.stringify(currentAccount));
                    var userContext = claimsService.getUserContext();

                    if (urlNotExempted) {
                        // This is the primary redirect after login. The other preloader redirect is a backup.
                        // After the redirect (and a new page load) execution will continue in the HRD-B path below
                        // Note: Post-Auth complete broadcast does not happen here because of imminent redirect
                        console.log('[Auth][MSAL][HRD-A-0] Processing Primary Post-Auth Redirect...');
                        service.processPostAuthRedirect(userContext);
                    } else {
                        console.log('[Auth][MSAL][HRD-A-1] Skipping Post-Auth Redirect (Exempted Because URL)...');
                    }
                } else {
                    console.log('[Auth][MSAL][HRD-B] User Agent Redirect Promise Finished - Without Response (Site Load) ');

                    /*
                     * This was tried but did not appear to work:
                    var isAuthenticated = $rootScope.msal.getAllAccounts().length > 0
                        && !($rootScope.msal.getAllAccounts().length == 1 && $rootScope.msal.getAllAccounts()[0] != {});
                    */

                    // Use aquireTokenSilent to check auth state after page load
                    // (per https://stackoverflow.com/a/54374262/39315. Note that checking account list
                    // for at least one non-empty account did not apppear to work in practice)
                    service.acquireTokenSilent().then(function (accessTokenResponse) {
                        console.log('[Auth][MSAL][HRD-B-0] User Authenticated (+Clearing Post-Auth Redirect)');

                        // Clear snapshot taken above so that user is not accidentally redirected to the current url
                        // after the next login attempt.
                        service.clearActiveUrlSnapshot();

                        // Authentication Initialization Completed Here
                        setAuthProcessingComplete();
                    }).fail(function (error) {
                        if (urlNotExempted) {
                            console.log('[Auth][MSAL][HRD-B-1] User Unauthenticated - Starting Login... (' + error + ')');
                            service.login();
                        } else {
                            console.log('[Auth][MSAL][HRD-B-2] Invitation / Registration Detected - Allowing Unauthenticated User')
                        }
                    });
                }
            }).catch(function (error) {
                console.log(error);
                clearLoginLock();
                var errorMessage = error ? (error.errorMessage || '') : '';
                if (errorMessage.indexOf("AADB2C90118") > -1) {
                    try {
                        service.userAgentPasswordResetApplication = new msal.PublicClientApplication(msalConfig);
                        service.userAgentPasswordResetApplication.config.auth.authority =
                            envService.read('passwordResetAuthority');
                        service.userAgentPasswordResetApplication.loginRedirect(requestObj);
                    } catch (err) {
                        console.log(err);
                    }
                } else if (errorMessage.indexOf("AADB2C90091") > -1) {
                    service.userAgentApplication.loginRedirect(requestObj);
                }
                else {
                    if (window.Rollbar !== undefined) {
                        Rollbar.error("Fallthrough error in msalService.userAgentApplication.handleRedirectPromise, expected in certain situations", { error: error }, function () {
                            $window.location.href = "/account/login/reset";
                        });
                    }
                }
            });
        } else {
            if (isLightweightPostingAccountValid && cachedLightweightPostingAccount) {
                claimsService.setLightweightPostingAccount(cachedLightweightPostingAccount);
                setAuthProcessingComplete();
            }
        }

        // This processes the typical post-auth redirect after login completes successfully.
        // It will redirect the user to the original URL they attempted to visit (if known)
        // or otherwise fall back to the default controller path for the user type
        service.processPostAuthRedirect = function (userContext) {
            try {
                var defaultPath = userContext.defaultControllerPath;
                var existingRedirectSnapshot = service.getLastActiveRedirectSnapshot();

                if (existingRedirectSnapshot) {
                    service.clearActiveUrlSnapshot();
                    console.log('[Auth][PAR] Existing target URL is ' + existingRedirectSnapshot);
                    if (existingRedirectSnapshot.indexOf(defaultPath) !== -1) {
                        console.log('[Auth][PAR] Navigating to Target');
                        $window.location.href = existingRedirectSnapshot;
                    } else {
                        console.log('[Auth][PAR] Navigating to Default Path: ' + defaultPath);
                        $window.location.href = defaultPath;
                    }
                } else {
                    $window.location.href = defaultPath;
                }
            } catch (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Failed to process post-auth redirect, redirecting user to default path", { error: error }, function () {
                        $window.location.href = userContext.defaultControllerPath;
                    });
                }
            }
        }

        // Starts a login via redirect
        // If skipLockCheck is supplied it will ignore the login lock (see above)
        service.login = function (skipLockCheck) {
            console.log('[Auth][MSAL] Attempting to Start Login (via service.login)');

            var loginIsLocked = checkIsLoginLocked();
            if (!skipLockCheck && loginIsLocked)
                return false;

            setLoginLock();

            console.log('[Auth][MSAL] Starting Login, Login Lock Acquired/Skipped');

            requestObj.account = service.getCurrentAccount();

            service.userAgentApplication.loginRedirect(requestObj).catch(function (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Fallthrough error in msalService.login, expected in certain situations", { requestObj: requestObj }, function () {
                        $window.location.href = "/account/login/reset";
                    });
                }
            });
        }
        service.getRecentAccounts = function (take, filterOutUserName) {
            var usedAccounts = JSON.parse(localStorage.getItem('usedAccounts') || '[]');
            for (var i = 0; i < usedAccounts.length; i++) {
                var account = usedAccounts[i];
                var date = new Date(account.idTokenClaims.auth_time * 1000);
                account.lastLogin = date.toLocaleString('en-US');
            }
            usedAccounts = usedAccounts.filter(function (a) { return a.username !== filterOutUserName });
            return usedAccounts.reverse().slice(0, take);
        };
        service.switchUser = function (username) {
            // Somwhere in the msal base files, it checks for empty loginHint and reverts it to use
            // the username of the logged in user. Chaning it to a single space gets around this.
            if (!username) {
                username = ' ';
            }

            var usedAccounts = JSON.parse(localStorage.getItem('usedAccounts') || '[]');
            var filtered = usedAccounts.filter(function (a) { return a.username === username });
            var account = filtered && filtered.length ? filtered[0] : null;
            // Check for the claims idp property
            // If the idp is present, we can assume the login is not email based
            if (account && account.idTokenClaims.idp !== undefined) {
                username = ' ';
            }

            requestObj['prompt'] = 'select_account';
            requestObj['loginHint'] = username;
            requestObj['authority'] = msalConfig.auth.authority;

            localStorage.setItem('currentAccount', '{}');
            service.userAgentApplication.loginRedirect(requestObj);
        };
        service.removeUser = function (username) {
            var usedAccounts = JSON.parse(localStorage.getItem('usedAccounts') || '[]');
            // Remove user from recently used list
            var filteredUsedAccounts = usedAccounts.filter(function (x) { return x['username'] !== username; });
            localStorage.setItem('usedAccounts', JSON.stringify(filteredUsedAccounts));
        };
        service.logOut = function (redirectUrl) {
            try {
                if (cachedLightweightPostingAccount) {
                    service.cleanMsalTokens(true);
                    setTimeout(function () {
                        $window.location = redirectUrl || '/';
                    }, 1500)
                } else {
                    requestObj.account = service.getCurrentAccount();
                    service.cleanMsalTokens();
                    service.userAgentApplication.logout(requestObj);
                }
                localStorage.setItem('currentAccount', '{}');
                localStorage.removeItem('noorgFixAttempts');
                localStorage.removeItem('lightweightPostingAccount');
            } catch (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Fallthrough error in msalService.logOut", { error: error });
                }
            }
        };

        service.cleanMsalTokens = function (clearAllMsalTokens) {
            // Needs to line up with an active flow that is used in production
            // (preferably with all environments) - used to find related items in local storage
            var relatedFlowMarker = 'B2C_1_mealconnect_signupsignin';

            if (!localStorage)
                return;

            try {
                var currentAccount = service.getCurrentAccount();
                clearAllMsalTokens = clearAllMsalTokens || !currentAccount;

                for (var i = 0; i < localStorage.length; i++) {
                    var key = localStorage.key(i);
                    var isMsalToken = key.indexOf('msal') > -1 || key.toLowerCase().indexOf(relatedFlowMarker.toLowerCase()) > -1;
                    var isTokenToRemove = clearAllMsalTokens || key.indexOf(currentAccount.localAccountId) === -1;

                    if (isMsalToken && isTokenToRemove) {
                        localStorage.removeItem(key);
                    }
                }
            } catch (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Fallthrough error in msalService.cleanMsalTokens", { error: error });
                }
            }
        };

        service.getCurrentAccount = function () {
            if (isLightweightPostingAccountValid && cachedLightweightPostingAccount) {
                return cachedLightweightPostingAccount.account;
            }

            var accounts = $rootScope.msal.getAllAccounts();
            var currentAccount = JSON.parse(localStorage.getItem('currentAccount') || '{}');
            var username = currentAccount['username'];
            var index = accounts.map(function (x) { return x.username; }).indexOf(username);
            if (index === -1) {
                return null;
            }
            return accounts[index];
        };

        service.acquireTokenRedirect = function (authority, redirectRelativePath, request) {
            if (redirectRelativePath || authority) {
                if (redirectRelativePath)
                    msalConfig.auth.redirectUri = origin + redirectRelativePath;

                if (authority)
                    msalConfig.auth.authority = authority

                service.userAgentApplication = new msal.PublicClientApplication(msalConfig);
                $rootScope.msal = service.userAgentApplication;
                //getCurrentAccount needs to be called from the claims service, but a reference to msalService there
                //would create a circular dependency.
                $rootScope.msal.getCurrentAccount = service.getCurrentAccount();
            }

            service.userAgentApplication.acquireTokenRedirect(angular.extend(requestObj, request)).catch(function (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Fallthrough error in msalService.acquireTokenRedirect", { error: error });
                }
            });
        }

        service.acquireTokenSilent = function () {
            // Per related docs, this will use an internal cache when possible
            // However, it may skip the cache due to expiration configuration on dev/local
            // See https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-acquire-cache-tokens

            var dfd = $.Deferred();

            if (isLightweightPostingAccountValid && cachedLightweightPostingAccount) {
                setTimeout(function () {
                    if (cachedLightweightPostingAccount.access_token) {
                        dfd.resolve({ accessToken: cachedLightweightPostingAccount.access_token });
                    } else {
                        dfd.resolve({ accessToken: "" });
                    }
                })

                return dfd.promise();
            }

            requestObj.account = service.getCurrentAccount();

            service.userAgentApplication.acquireTokenSilent(requestObj).then(function (accessTokenResponse) {
                dfd.resolve(accessTokenResponse);
            }).catch(function (error) {
                if (window.Rollbar !== undefined) {
                    Rollbar.error("Fallthrough error in msalService.acquireTokenSilent", { error: error });
                }
                return dfd.reject(error);
            });

            return dfd.promise();
        }

        return service;
    }]);
;
angular.module('faom').provider('env', function () {
    this.config = {
        domains: {
            development: ['localhost', 'app-unifiedplatform-nonprod-dev', 'app-unifiedplatform-qa-001-dev'],
            test: ['app-unifiedplatform-nonprod-qa', 'app-unifiedplatform-qa-001'],
            uat: ['app-unifiedplatform-nonprod-uat'],
            prod: ['mealconnect.org', 'www.mealconnect.org', 'app-unifiedplatform-prod.azurewebsites.net', 'onlinemarketplace.org']
        },
        vars: {
            development: {
                clientId: 'c9fa740f-ad7d-446d-9177-a54b31825873',
                baseAuthority: 'feedingamericadev.b2clogin.com',
                authority:
                    'https://feedingamericadev.b2clogin.com/feedingamericadev.onmicrosoft.com/B2C_1_mealconnect_signupsignin',
                scopes: 'https://feedingamericadev.onmicrosoft.com/api/unifiedplatform.read',
                passwordResetAuthority: 'https://feedingamericadev.b2clogin.com/feedingamericadev.onmicrosoft.com/B2C_1_password_reset'
            },
            test: {
                clientId: 'b13d5f18-565a-43e4-9c82-dfd661128299',
                baseAuthority: 'feedingamericaqa.b2clogin.com',
                authority:
                    'https://feedingamericaqa.b2clogin.com/feedingamericaqa.onmicrosoft.com/B2C_1_mealconnect_signupsignin',
                scopes: 'https://feedingamericaqa.onmicrosoft.com/api/unifiedplatform.read',
                passwordResetAuthority: 'https://feedingamericaqa.b2clogin.com/feedingamericaqa.onmicrosoft.com/B2C_1_password_reset'
            },
            uat: {
                clientId: '93792d60-e9cd-404a-8b95-896e2bb0f36b',
                baseAuthority: 'feedingamericauat.b2clogin.com',
                authority:
                    'https://feedingamericauat.b2clogin.com/feedingamericauat.onmicrosoft.com/B2C_1_mealconnect_signupsignin',
                scopes: 'https://feedingamericauat.onmicrosoft.com/api/unifiedplatform.read',
                passwordResetAuthority: 'https://feedingamericauat.b2clogin.com/feedingamericauat.onmicrosoft.com/B2C_1_password_reset'
            },
            prod: {
                clientId: '98428d3c-769c-4271-9b3c-b5906957f9cd',
                baseAuthority: 'feedingamericab2c.b2clogin.com',
                authority:
                    'https://feedingamericab2c.b2clogin.com/feedingamericab2c.onmicrosoft.com/B2C_1_mealconnect_signupsignin',
                scopes: 'https://feedingamericab2c.onmicrosoft.com/api/unifiedplatform.read',
                passwordResetAuthority: 'https://feedingamericab2c.b2clogin.com/feedingamericab2c.onmicrosoft.com/B2C_1_password_reset'
            },
            defaults: {
                clientId: '98428d3c-769c-4271-9b3c-b5906957f9cd',
                baseAuthority: 'feedingamericab2c.b2clogin.com',
                authority:
                    'https://feedingamericab2c.b2clogin.com/feedingamericab2c.onmicrosoft.com/B2C_1_mealconnect_signupsignin',
                scopes: 'https://feedingamericab2c.onmicrosoft.com/api/unifiedplatform.read',
                passwordResetAuthority: 'https://feedingamericab2c.b2clogin.com/feedingamericab2c.onmicrosoft.com/B2C_1_password_reset'
            }
        }
    };
    this.$get = function () {
        return {
            config: this.config
        }
    };
});
;
angular.module('faom').controller('LoginShellController', ['$scope', '$window', '$timeout', '$log', 'msalService', function ($scope, $window, $timeout, $log, msalService) {

        var vm = this;

        var tryExtractReturnUrl = function () {
            try {
                var name = 'r'
                var url = $window.location.href;
                name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regexS = "[\\?&]" + name + "=([^&]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(url);
                return results == null ? null : results[1];
            }
            catch (err) {
                $log.error('Failed to check for return url parameter');
            }
        }


        try {
            // 'r' must be present & first parameter
            if (window.location.href.indexOf('?r=') !== -1) {
                if (window.location.href.indexOf('&k=ae0f99b4') == -1) {
                    var returnUrl = tryExtractReturnUrl();

                    // Look for unencoded hash
                    if (returnUrl && returnUrl.indexOf('#')) {
                        // Key is set and checked on load as an attempt to prevent infinite redirect loop
                        // (and other related issues) on failure.
                        $window.location.href = '/login?r=' + encodeURIComponent(returnUrl.replace('%2f', '/')) + '&k=ae0f99b4';
                    };
                }
            }
        } catch (err) {
            $log.error('Failed to perform return url replacement');
        }
        
        vm.busy = false;
        vm.expanded = false;

        vm.eMailLoginInProgress = true;
        vm.passwordResetInProgress = false;

        vm.lastError = '';

        vm.expand = function () {
            vm.expanded = true;
        };

        vm.unexpand = function () {
            vm.expanded = false;
        };

        vm.backToOptions = function () {
            vm.eMailLoginInProgress = false;
            vm.lastError = null;
        };

        vm.backToEmail = function () {
            vm.passwordResetInProgress = false;
            vm.lastError = null;
        };

        vm.startForgotPasswordProcess = function () {
            vm.lastError = null;
            vm.passwordResetInProgress = true;
        };

        vm.startLogin = function () {

            msalService.cleanMsalTokens();

            // Allow MSAL service to initialize, in case that's helpful
            // If proven helpful, consider refactoring in the future to wait explicitly for init
            $timeout(function () {
                msalService.login(true);
            }, 250);
        }

        vm.startReset = function () {
            vm.busy = true;
            msalService.logOut();
        }

        vm.tryInitiateLogin = function (providerName) {

            if (providerName === 'email') {
                vm.eMailLoginInProgress = true;
                vm.passwordResetInProgress = false;
                return;
            }

            vm.busy = true;
        };

    }]);;
angular.module('faom')
    .controller('organizationLockedCtrl',
        ['$scope', '$rootScope', 'msalService','claimsService',
            function ($scope, $rootScope, msalService, claimsService) {
                $scope.userRole = claimsService.getUserContext().userRole;
                $scope.claimsService = claimsService;
                $scope.signOut = function () {
                    angular.element('body').css('overflow', 'hidden');
                    $rootScope.app.signingOut = true;
                    msalService.logOut();
                };

            }
        ]);;
angular.module('faom')
    .controller('UnregisteredUserCtrl',
        ['$log', '$scope','$rootScope', '$http', '$window', '$timeout', 'msalService', 'claimsService',
            function ($log, $scope, $rootScope, $http, $window, $timeout, msalService, claimsService) {
                $scope.userContext = claimsService.getUserContext();
                $scope.userRole = $scope.userContext.userRole;
                $scope.claimsService = claimsService;
                $scope.ready = false;
                $scope.hasAccount = false;

                var MAX_FIX_NOORG_ATTEMPTS = 3;
                var FIX_NOORG_STORAGE_KEY = 'noorgFixAttempts';
                var HAS_ACCOUNT_STORAGE_KEY = 'noorgHasAccount';
                var numberOfAttempts = parseInt(localStorage.getItem(FIX_NOORG_STORAGE_KEY));

                var checkNoorg = function () {
                    $scope.checkingOrg = true;

                    $http.put('/api/user/noorg/check')
                        .then(function (response) {
                            numberOfAttempts++;
                            localStorage.setItem(FIX_NOORG_STORAGE_KEY, numberOfAttempts);

                            if (response && response.data === true) {
                                localStorage.setItem(HAS_ACCOUNT_STORAGE_KEY, true);
                                $timeout(function () {
                                    $window.location.href = "/account/login/reset";
                                }, 10000);
                            } else {
                                $scope.checkingOrg = false;
                            }
                        }, function () {
                            $scope.checkingOrg = false;
                        });
                }

                try {
                    if (isNaN(numberOfAttempts)) {
                        numberOfAttempts = 0;
                    }

                    if (numberOfAttempts < MAX_FIX_NOORG_ATTEMPTS) {
                        checkNoorg();
                    }

                    if (numberOfAttempts >= MAX_FIX_NOORG_ATTEMPTS) {
                        $scope.hasAccount = localStorage.getItem(HAS_ACCOUNT_STORAGE_KEY) || false;

                        if ($scope.hasAccount && Rollbar) {
                            Rollbar.error('Maximum no-org fix attempts reached for user with account', $scope.userContext);
                        }
                    }
                } catch (e) {
                    $log.log('Failed to fix noorg user');
                } finally {
                    $scope.ready = true;
                }

                $scope.signOut = function () {
	                angular.element('body').css('overflow', 'hidden');
	                $rootScope.app.signingOut = true;
	                msalService.logOut();
                };

            }
        ]);
;
