{"version":3,"sources":["node_modules/ionic-appauth/lib/auth-action.js","node_modules/base64-js/index.js","node_modules/@openid/appauth/built/errors.js","node_modules/@openid/appauth/built/crypto_utils.js","node_modules/@openid/appauth/built/flags.js","node_modules/@openid/appauth/built/logger.js","node_modules/@openid/appauth/built/authorization_request.js","node_modules/@openid/appauth/built/authorization_request_handler.js","node_modules/@openid/appauth/built/authorization_response.js","node_modules/@openid/appauth/built/xhr.js","node_modules/@openid/appauth/built/authorization_service_configuration.js","node_modules/@openid/appauth/built/query_string_utils.js","node_modules/@openid/appauth/built/storage.js","node_modules/@openid/appauth/built/redirect_based_handler.js","node_modules/@openid/appauth/built/revoke_token_request.js","node_modules/@openid/appauth/built/token_request.js","node_modules/@openid/appauth/built/token_response.js","node_modules/@openid/appauth/built/token_request_handler.js","node_modules/@openid/appauth/built/types.js","node_modules/@openid/appauth/built/index.js","node_modules/ionic-appauth/lib/user-info-request-handler.js","node_modules/ionic-appauth/lib/end-session-request-handler.js","node_modules/ionic-appauth/lib/authorization-request-handler.js","node_modules/ionic-appauth/lib/auth-browser.js","node_modules/ionic-appauth/lib/end-session-request.js","node_modules/guid-typescript/dist/guid.js","node_modules/ionic-appauth/lib/auth-session.js","node_modules/ionic-appauth/lib/auth-observer.js","node_modules/ionic-appauth/lib/auth-subject.js","node_modules/ionic-appauth/lib/auth-service.js","node_modules/ionic-appauth/lib/auth-configuration.js","node_modules/localforage/dist/localforage.js","node_modules/@ionic/storage/dist/esm/index.js","node_modules/ionic-appauth/lib/auth-storage.js","node_modules/ionic-appauth/lib/index.js"],"sourcesContent":["export var AuthActions = /*#__PURE__*/function (AuthActions) {\n AuthActions[\"Init\"] = \"Init\";\n AuthActions[\"SignInSuccess\"] = \"Sign In Success\";\n AuthActions[\"SignInFailed\"] = \"Sign In Failed\";\n AuthActions[\"SignOutSuccess\"] = \"Sign Out Success\";\n AuthActions[\"SignOutFailed\"] = \"Sign Out Failed\";\n AuthActions[\"RefreshSuccess\"] = \"Refresh Success\";\n AuthActions[\"RefreshFailed\"] = \"Refesh Failed\";\n AuthActions[\"LoadTokenFromStorageSuccess\"] = \"Get Token From Storage Success\";\n AuthActions[\"LoadTokenFromStorageFailed\"] = \"Get Token From Storage Failed\";\n AuthActions[\"LoadUserInfoSuccess\"] = \"Load User Info Success\";\n AuthActions[\"LoadUserInfoFailed\"] = \"Load User Info Failed\";\n AuthActions[\"RevokeTokensSuccess\"] = \"Revoke Tokens Success\";\n AuthActions[\"RevokeTokensFailed\"] = \"Revoke Tokens Failed\";\n return AuthActions;\n}(AuthActions || {});\nexport class AuthActionBuilder {\n static Init() {\n return {\n action: AuthActions.Init\n };\n }\n static SignOutSuccess() {\n return {\n action: AuthActions.SignOutSuccess\n };\n }\n static SignOutFailed(error) {\n return {\n action: AuthActions.SignOutFailed,\n error: error.message\n };\n }\n static RefreshSuccess(tokenResponse) {\n return {\n action: AuthActions.RefreshSuccess,\n tokenResponse\n };\n }\n static RefreshFailed(error) {\n return {\n action: AuthActions.RefreshFailed,\n error: error.message\n };\n }\n static SignInSuccess(tokenResponse) {\n return {\n action: AuthActions.SignInSuccess,\n tokenResponse\n };\n }\n static SignInFailed(error) {\n return {\n action: AuthActions.SignInFailed,\n error: error.message\n };\n }\n static LoadTokenFromStorageSuccess(tokenResponse) {\n return {\n action: AuthActions.LoadTokenFromStorageSuccess,\n tokenResponse\n };\n }\n static LoadTokenFromStorageFailed(error) {\n return {\n action: AuthActions.LoadTokenFromStorageFailed,\n error: error.message\n };\n }\n static RevokeTokensSuccess() {\n return {\n action: AuthActions.RevokeTokensSuccess,\n tokenResponse: undefined\n };\n }\n static RevokeTokensFailed(error) {\n return {\n action: AuthActions.RevokeTokensFailed,\n error: error.message\n };\n }\n static LoadUserInfoSuccess(user) {\n return {\n action: AuthActions.LoadUserInfoSuccess,\n user\n };\n }\n static LoadUserInfoFailed(error) {\n return {\n action: AuthActions.LoadUserInfoFailed,\n error: error.message\n };\n }\n}","'use strict';\n\nexports.byteLength = byteLength;\nexports.toByteArray = toByteArray;\nexports.fromByteArray = fromByteArray;\nvar lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62;\nrevLookup['_'.charCodeAt(0)] = 63;\nfunction getLens(b64) {\n var len = b64.length;\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4');\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=');\n if (validLen === -1) validLen = len;\n var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;\n return [validLen, placeHoldersLen];\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength(b64) {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nfunction _byteLength(b64, validLen, placeHoldersLen) {\n return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nfunction toByteArray(b64) {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n var i;\n for (i = 0; i < len; i += 4) {\n tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = tmp >> 16 & 0xFF;\n arr[curByte++] = tmp >> 8 & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n if (placeHoldersLen === 2) {\n tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;\n arr[curByte++] = tmp & 0xFF;\n }\n if (placeHoldersLen === 1) {\n tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;\n arr[curByte++] = tmp >> 8 & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n return arr;\n}\nfunction tripletToBase64(num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];\n}\nfunction encodeChunk(uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);\n output.push(tripletToBase64(tmp));\n }\n return output.join('');\n}\nfunction fromByteArray(uint8) {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');\n }\n return parts.join('');\n}","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.AppAuthError = void 0;\n/**\n * Represents the AppAuthError type.\n */\nvar AppAuthError = /** @class */function () {\n function AppAuthError(message, extras) {\n this.message = message;\n this.extras = extras;\n }\n return AppAuthError;\n}();\nexports.AppAuthError = AppAuthError;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.DefaultCrypto = exports.textEncodeLite = exports.urlSafe = exports.bufferToString = void 0;\nvar base64 = require(\"base64-js\");\nvar errors_1 = require(\"./errors\");\nvar HAS_CRYPTO = typeof window !== 'undefined' && !!window.crypto;\nvar HAS_SUBTLE_CRYPTO = HAS_CRYPTO && !!window.crypto.subtle;\nvar CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\nfunction bufferToString(buffer) {\n var state = [];\n for (var i = 0; i < buffer.byteLength; i += 1) {\n var index = buffer[i] % CHARSET.length;\n state.push(CHARSET[index]);\n }\n return state.join('');\n}\nexports.bufferToString = bufferToString;\nfunction urlSafe(buffer) {\n var encoded = base64.fromByteArray(new Uint8Array(buffer));\n return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\nexports.urlSafe = urlSafe;\n// adapted from source: http://stackoverflow.com/a/11058858\n// this is used in place of TextEncode as the api is not yet\n// well supported: https://caniuse.com/#search=TextEncoder\nfunction textEncodeLite(str) {\n var buf = new ArrayBuffer(str.length);\n var bufView = new Uint8Array(buf);\n for (var i = 0; i < str.length; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return bufView;\n}\nexports.textEncodeLite = textEncodeLite;\n/**\n * The default implementation of the `Crypto` interface.\n * This uses the capabilities of the browser.\n */\nvar DefaultCrypto = /** @class */function () {\n function DefaultCrypto() {}\n DefaultCrypto.prototype.generateRandom = function (size) {\n var buffer = new Uint8Array(size);\n if (HAS_CRYPTO) {\n window.crypto.getRandomValues(buffer);\n } else {\n // fall back to Math.random() if nothing else is available\n for (var i = 0; i < size; i += 1) {\n buffer[i] = Math.random() * CHARSET.length | 0;\n }\n }\n return bufferToString(buffer);\n };\n DefaultCrypto.prototype.deriveChallenge = function (code) {\n if (code.length < 43 || code.length > 128) {\n return Promise.reject(new errors_1.AppAuthError('Invalid code length.'));\n }\n if (!HAS_SUBTLE_CRYPTO) {\n return Promise.reject(new errors_1.AppAuthError('window.crypto.subtle is unavailable.'));\n }\n return new Promise(function (resolve, reject) {\n crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(function (buffer) {\n return resolve(urlSafe(new Uint8Array(buffer)));\n }, function (error) {\n return reject(error);\n });\n });\n };\n return DefaultCrypto;\n}();\nexports.DefaultCrypto = DefaultCrypto;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.IS_PROFILE = exports.IS_LOG = void 0;\n/* Global flags that control the behavior of App Auth JS. */\n/* Logging turned on ? */\nexports.IS_LOG = true;\n/* Profiling turned on ? */\nexports.IS_PROFILE = false;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __spreadArray = this && this.__spreadArray || function (to, from) {\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i];\n return to;\n};\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.profile = exports.log = void 0;\nvar flags_1 = require(\"./flags\");\nfunction log(message) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (flags_1.IS_LOG) {\n var length_1 = args ? args.length : 0;\n if (length_1 > 0) {\n console.log.apply(console, __spreadArray([message], args));\n } else {\n console.log(message);\n }\n }\n}\nexports.log = log;\n;\n// check to see if native support for profiling is available.\nvar NATIVE_PROFILE_SUPPORT = typeof window !== 'undefined' && !!window.performance && !!console.profile;\n/**\n * A decorator that can profile a function.\n */\nfunction profile(target, propertyKey, descriptor) {\n if (flags_1.IS_PROFILE) {\n return performProfile(target, propertyKey, descriptor);\n } else {\n // return as-is\n return descriptor;\n }\n}\nexports.profile = profile;\nfunction performProfile(target, propertyKey, descriptor) {\n var originalCallable = descriptor.value;\n // name must exist\n var name = originalCallable.name;\n if (!name) {\n name = 'anonymous function';\n }\n if (NATIVE_PROFILE_SUPPORT) {\n descriptor.value = function (args) {\n console.profile(name);\n var startTime = window.performance.now();\n var result = originalCallable.call.apply(originalCallable, __spreadArray([this || window], args));\n var duration = window.performance.now() - startTime;\n console.log(name + \" took \" + duration + \" ms\");\n console.profileEnd();\n return result;\n };\n } else {\n descriptor.value = function (args) {\n log(\"Profile start \" + name);\n var start = Date.now();\n var result = originalCallable.call.apply(originalCallable, __spreadArray([this || window], args));\n var duration = Date.now() - start;\n log(\"Profile end \" + name + \" took \" + duration + \" ms.\");\n return result;\n };\n }\n return descriptor;\n}\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.AuthorizationRequest = void 0;\nvar crypto_utils_1 = require(\"./crypto_utils\");\nvar logger_1 = require(\"./logger\");\n/**\n * Generates a cryptographically random new state. Useful for CSRF protection.\n */\nvar SIZE = 10; // 10 bytes\nvar newState = function (crypto) {\n return crypto.generateRandom(SIZE);\n};\n/**\n * Represents the AuthorizationRequest.\n * For more information look at\n * https://tools.ietf.org/html/rfc6749#section-4.1.1\n */\nvar AuthorizationRequest = /** @class */function () {\n /**\n * Constructs a new AuthorizationRequest.\n * Use a `undefined` value for the `state` parameter, to generate a random\n * state for CSRF protection.\n */\n function AuthorizationRequest(request, crypto, usePkce) {\n if (crypto === void 0) {\n crypto = new crypto_utils_1.DefaultCrypto();\n }\n if (usePkce === void 0) {\n usePkce = true;\n }\n this.crypto = crypto;\n this.usePkce = usePkce;\n this.clientId = request.client_id;\n this.redirectUri = request.redirect_uri;\n this.scope = request.scope;\n this.responseType = request.response_type || AuthorizationRequest.RESPONSE_TYPE_CODE;\n this.state = request.state || newState(crypto);\n this.extras = request.extras;\n // read internal properties if available\n this.internal = request.internal;\n }\n AuthorizationRequest.prototype.setupCodeVerifier = function () {\n var _this = this;\n if (!this.usePkce) {\n return Promise.resolve();\n } else {\n var codeVerifier_1 = this.crypto.generateRandom(128);\n var challenge = this.crypto.deriveChallenge(codeVerifier_1).catch(function (error) {\n logger_1.log('Unable to generate PKCE challenge. Not using PKCE', error);\n return undefined;\n });\n return challenge.then(function (result) {\n if (result) {\n // keep track of the code used.\n _this.internal = _this.internal || {};\n _this.internal['code_verifier'] = codeVerifier_1;\n _this.extras = _this.extras || {};\n _this.extras['code_challenge'] = result;\n // We always use S256. Plain is not good enough.\n _this.extras['code_challenge_method'] = 'S256';\n }\n });\n }\n };\n /**\n * Serializes the AuthorizationRequest to a JavaScript Object.\n */\n AuthorizationRequest.prototype.toJson = function () {\n var _this = this;\n // Always make sure that the code verifier is setup when toJson() is called.\n return this.setupCodeVerifier().then(function () {\n return {\n response_type: _this.responseType,\n client_id: _this.clientId,\n redirect_uri: _this.redirectUri,\n scope: _this.scope,\n state: _this.state,\n extras: _this.extras,\n internal: _this.internal\n };\n });\n };\n AuthorizationRequest.RESPONSE_TYPE_TOKEN = 'token';\n AuthorizationRequest.RESPONSE_TYPE_CODE = 'code';\n return AuthorizationRequest;\n}();\nexports.AuthorizationRequest = AuthorizationRequest;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.AuthorizationRequestHandler = exports.BUILT_IN_PARAMETERS = exports.AuthorizationNotifier = void 0;\nvar logger_1 = require(\"./logger\");\n/**\n * Authorization Service notifier.\n * This manages the communication of the AuthorizationResponse to the 3p client.\n */\nvar AuthorizationNotifier = /** @class */function () {\n function AuthorizationNotifier() {\n this.listener = null;\n }\n AuthorizationNotifier.prototype.setAuthorizationListener = function (listener) {\n this.listener = listener;\n };\n /**\n * The authorization complete callback.\n */\n AuthorizationNotifier.prototype.onAuthorizationComplete = function (request, response, error) {\n if (this.listener) {\n // complete authorization request\n this.listener(request, response, error);\n }\n };\n return AuthorizationNotifier;\n}();\nexports.AuthorizationNotifier = AuthorizationNotifier;\n// TODO(rahulrav@): add more built in parameters.\n/* built in parameters. */\nexports.BUILT_IN_PARAMETERS = ['redirect_uri', 'client_id', 'response_type', 'state', 'scope'];\n/**\n * Defines the interface which is capable of handling an authorization request\n * using various methods (iframe / popup / different process etc.).\n */\nvar AuthorizationRequestHandler = /** @class */function () {\n function AuthorizationRequestHandler(utils, crypto) {\n this.utils = utils;\n this.crypto = crypto;\n // notifier send the response back to the client.\n this.notifier = null;\n }\n /**\n * A utility method to be able to build the authorization request URL.\n */\n AuthorizationRequestHandler.prototype.buildRequestUrl = function (configuration, request) {\n // build the query string\n // coerce to any type for convenience\n var requestMap = {\n 'redirect_uri': request.redirectUri,\n 'client_id': request.clientId,\n 'response_type': request.responseType,\n 'state': request.state,\n 'scope': request.scope\n };\n // copy over extras\n if (request.extras) {\n for (var extra in request.extras) {\n if (request.extras.hasOwnProperty(extra)) {\n // check before inserting to requestMap\n if (exports.BUILT_IN_PARAMETERS.indexOf(extra) < 0) {\n requestMap[extra] = request.extras[extra];\n }\n }\n }\n }\n var query = this.utils.stringify(requestMap);\n var baseUrl = configuration.authorizationEndpoint;\n var url = baseUrl + \"?\" + query;\n return url;\n };\n /**\n * Completes the authorization request if necessary & when possible.\n */\n AuthorizationRequestHandler.prototype.completeAuthorizationRequestIfPossible = function () {\n var _this = this;\n // call complete authorization if possible to see there might\n // be a response that needs to be delivered.\n logger_1.log(\"Checking to see if there is an authorization response to be delivered.\");\n if (!this.notifier) {\n logger_1.log(\"Notifier is not present on AuthorizationRequest handler.\\n No delivery of result will be possible\");\n }\n return this.completeAuthorizationRequest().then(function (result) {\n if (!result) {\n logger_1.log(\"No result is available yet.\");\n }\n if (result && _this.notifier) {\n _this.notifier.onAuthorizationComplete(result.request, result.response, result.error);\n }\n });\n };\n /**\n * Sets the default Authorization Service notifier.\n */\n AuthorizationRequestHandler.prototype.setAuthorizationNotifier = function (notifier) {\n this.notifier = notifier;\n return this;\n };\n ;\n return AuthorizationRequestHandler;\n}();\nexports.AuthorizationRequestHandler = AuthorizationRequestHandler;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.AuthorizationError = exports.AuthorizationResponse = void 0;\n/**\n * Represents the Authorization Response type.\n * For more information look at\n * https://tools.ietf.org/html/rfc6749#section-4.1.2\n */\nvar AuthorizationResponse = /** @class */function () {\n function AuthorizationResponse(response) {\n this.code = response.code;\n this.state = response.state;\n }\n AuthorizationResponse.prototype.toJson = function () {\n return {\n code: this.code,\n state: this.state\n };\n };\n return AuthorizationResponse;\n}();\nexports.AuthorizationResponse = AuthorizationResponse;\n/**\n * Represents the Authorization error response.\n * For more information look at:\n * https://tools.ietf.org/html/rfc6749#section-4.1.2.1\n */\nvar AuthorizationError = /** @class */function () {\n function AuthorizationError(error) {\n this.error = error.error;\n this.errorDescription = error.error_description;\n this.errorUri = error.error_uri;\n this.state = error.state;\n }\n AuthorizationError.prototype.toJson = function () {\n return {\n error: this.error,\n error_description: this.errorDescription,\n error_uri: this.errorUri,\n state: this.state\n };\n };\n return AuthorizationError;\n}();\nexports.AuthorizationError = AuthorizationError;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = this && this.__extends || function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];\n };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null) throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n}();\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.TestRequestor = exports.FetchRequestor = exports.JQueryRequestor = exports.Requestor = void 0;\nvar errors_1 = require(\"./errors\");\n/**\n * An class that abstracts away the ability to make an XMLHttpRequest.\n */\nvar Requestor = /** @class */function () {\n function Requestor() {}\n return Requestor;\n}();\nexports.Requestor = Requestor;\n/**\n * Uses $.ajax to makes the Ajax requests.\n */\nvar JQueryRequestor = /** @class */function (_super) {\n __extends(JQueryRequestor, _super);\n function JQueryRequestor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n JQueryRequestor.prototype.xhr = function (settings) {\n // NOTE: using jquery to make XHR's as whatwg-fetch requires\n // that I target ES6.\n var xhr = $.ajax(settings);\n return new Promise(function (resolve, reject) {\n xhr.then(function (data, textStatus, jqXhr) {\n resolve(data);\n }, function (jqXhr, textStatus, error) {\n reject(new errors_1.AppAuthError(error));\n });\n });\n };\n return JQueryRequestor;\n}(Requestor);\nexports.JQueryRequestor = JQueryRequestor;\n/**\n * Uses fetch API to make Ajax requests\n */\nvar FetchRequestor = /** @class */function (_super) {\n __extends(FetchRequestor, _super);\n function FetchRequestor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n FetchRequestor.prototype.xhr = function (settings) {\n if (!settings.url) {\n return Promise.reject(new errors_1.AppAuthError('A URL must be provided.'));\n }\n var url = new URL(settings.url);\n var requestInit = {};\n requestInit.method = settings.method;\n requestInit.mode = 'cors';\n if (settings.data) {\n if (settings.method && settings.method.toUpperCase() === 'POST') {\n requestInit.body = settings.data;\n } else {\n var searchParams = new URLSearchParams(settings.data);\n searchParams.forEach(function (value, key) {\n url.searchParams.append(key, value);\n });\n }\n }\n // Set the request headers\n requestInit.headers = {};\n if (settings.headers) {\n for (var i in settings.headers) {\n if (settings.headers.hasOwnProperty(i)) {\n requestInit.headers[i] = settings.headers[i];\n }\n }\n }\n var isJsonDataType = settings.dataType && settings.dataType.toLowerCase() === 'json';\n // Set 'Accept' header value for json requests (Taken from\n // https://github.com/jquery/jquery/blob/e0d941156900a6bff7c098c8ea7290528e468cf8/src/ajax.js#L644\n // )\n if (isJsonDataType) {\n requestInit.headers['Accept'] = 'application/json, text/javascript, */*; q=0.01';\n }\n return fetch(url.toString(), requestInit).then(function (response) {\n if (response.status >= 200 && response.status < 300) {\n var contentType = response.headers.get('content-type');\n if (isJsonDataType || contentType && contentType.indexOf('application/json') !== -1) {\n return response.json();\n } else {\n return response.text();\n }\n } else {\n return Promise.reject(new errors_1.AppAuthError(response.status.toString(), response.statusText));\n }\n });\n };\n return FetchRequestor;\n}(Requestor);\nexports.FetchRequestor = FetchRequestor;\n/**\n * Should be used only in the context of testing. Just uses the underlying\n * Promise to mock the behavior of the Requestor.\n */\nvar TestRequestor = /** @class */function (_super) {\n __extends(TestRequestor, _super);\n function TestRequestor(promise) {\n var _this = _super.call(this) || this;\n _this.promise = promise;\n return _this;\n }\n TestRequestor.prototype.xhr = function (settings) {\n return this.promise; // unsafe cast\n };\n return TestRequestor;\n}(Requestor);\nexports.TestRequestor = TestRequestor;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.AuthorizationServiceConfiguration = void 0;\nvar xhr_1 = require(\"./xhr\");\n/**\n * The standard base path for well-known resources on domains.\n * See https://tools.ietf.org/html/rfc5785 for more information.\n */\nvar WELL_KNOWN_PATH = '.well-known';\n/**\n * The standard resource under the well known path at which an OpenID Connect\n * discovery document can be found under an issuer's base URI.\n */\nvar OPENID_CONFIGURATION = 'openid-configuration';\n/**\n * Configuration details required to interact with an authorization service.\n *\n * More information at https://openid.net/specs/openid-connect-discovery-1_0-17.html\n */\nvar AuthorizationServiceConfiguration = /** @class */function () {\n function AuthorizationServiceConfiguration(request) {\n this.authorizationEndpoint = request.authorization_endpoint;\n this.tokenEndpoint = request.token_endpoint;\n this.revocationEndpoint = request.revocation_endpoint;\n this.userInfoEndpoint = request.userinfo_endpoint;\n this.endSessionEndpoint = request.end_session_endpoint;\n }\n AuthorizationServiceConfiguration.prototype.toJson = function () {\n return {\n authorization_endpoint: this.authorizationEndpoint,\n token_endpoint: this.tokenEndpoint,\n revocation_endpoint: this.revocationEndpoint,\n end_session_endpoint: this.endSessionEndpoint,\n userinfo_endpoint: this.userInfoEndpoint\n };\n };\n AuthorizationServiceConfiguration.fetchFromIssuer = function (openIdIssuerUrl, requestor) {\n var fullUrl = openIdIssuerUrl + \"/\" + WELL_KNOWN_PATH + \"/\" + OPENID_CONFIGURATION;\n var requestorToUse = requestor || new xhr_1.JQueryRequestor();\n return requestorToUse.xhr({\n url: fullUrl,\n dataType: 'json',\n method: 'GET'\n }).then(function (json) {\n return new AuthorizationServiceConfiguration(json);\n });\n };\n return AuthorizationServiceConfiguration;\n}();\nexports.AuthorizationServiceConfiguration = AuthorizationServiceConfiguration;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.BasicQueryStringUtils = void 0;\nvar BasicQueryStringUtils = /** @class */function () {\n function BasicQueryStringUtils() {}\n BasicQueryStringUtils.prototype.parse = function (input, useHash) {\n if (useHash) {\n return this.parseQueryString(input.hash);\n } else {\n return this.parseQueryString(input.search);\n }\n };\n BasicQueryStringUtils.prototype.parseQueryString = function (query) {\n var result = {};\n // if anything starts with ?, # or & remove it\n query = query.trim().replace(/^(\\?|#|&)/, '');\n var params = query.split('&');\n for (var i = 0; i < params.length; i += 1) {\n var param = params[i]; // looks something like a=b\n var parts = param.split('=');\n if (parts.length >= 2) {\n var key = decodeURIComponent(parts.shift());\n var value = parts.length > 0 ? parts.join('=') : null;\n if (value) {\n result[key] = decodeURIComponent(value);\n }\n }\n }\n return result;\n };\n BasicQueryStringUtils.prototype.stringify = function (input) {\n var encoded = [];\n for (var key in input) {\n if (input.hasOwnProperty(key) && input[key]) {\n encoded.push(encodeURIComponent(key) + \"=\" + encodeURIComponent(input[key]));\n }\n }\n return encoded.join('&');\n };\n return BasicQueryStringUtils;\n}();\nexports.BasicQueryStringUtils = BasicQueryStringUtils;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = this && this.__extends || function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];\n };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null) throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n}();\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.LocalStorageBackend = exports.StorageBackend = void 0;\n/**\n * Asynchronous storage APIs. All methods return a `Promise`.\n * All methods take the `DOMString`\n * IDL type (as it is the lowest common denominator).\n */\nvar StorageBackend = /** @class */function () {\n function StorageBackend() {}\n return StorageBackend;\n}();\nexports.StorageBackend = StorageBackend;\n/**\n * A `StorageBackend` backed by `localstorage`.\n */\nvar LocalStorageBackend = /** @class */function (_super) {\n __extends(LocalStorageBackend, _super);\n function LocalStorageBackend(storage) {\n var _this = _super.call(this) || this;\n _this.storage = storage || window.localStorage;\n return _this;\n }\n LocalStorageBackend.prototype.getItem = function (name) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n var value = _this.storage.getItem(name);\n if (value) {\n resolve(value);\n } else {\n resolve(null);\n }\n });\n };\n LocalStorageBackend.prototype.removeItem = function (name) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.storage.removeItem(name);\n resolve();\n });\n };\n LocalStorageBackend.prototype.clear = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.storage.clear();\n resolve();\n });\n };\n LocalStorageBackend.prototype.setItem = function (name, value) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.storage.setItem(name, value);\n resolve();\n });\n };\n return LocalStorageBackend;\n}(StorageBackend);\nexports.LocalStorageBackend = LocalStorageBackend;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = this && this.__extends || function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];\n };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null) throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n}();\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.RedirectRequestHandler = void 0;\nvar authorization_request_1 = require(\"./authorization_request\");\nvar authorization_request_handler_1 = require(\"./authorization_request_handler\");\nvar authorization_response_1 = require(\"./authorization_response\");\nvar crypto_utils_1 = require(\"./crypto_utils\");\nvar logger_1 = require(\"./logger\");\nvar query_string_utils_1 = require(\"./query_string_utils\");\nvar storage_1 = require(\"./storage\");\n/** key for authorization request. */\nvar authorizationRequestKey = function (handle) {\n return handle + \"_appauth_authorization_request\";\n};\n/** key for authorization service configuration */\nvar authorizationServiceConfigurationKey = function (handle) {\n return handle + \"_appauth_authorization_service_configuration\";\n};\n/** key in local storage which represents the current authorization request. */\nvar AUTHORIZATION_REQUEST_HANDLE_KEY = 'appauth_current_authorization_request';\n/**\n * Represents an AuthorizationRequestHandler which uses a standard\n * redirect based code flow.\n */\nvar RedirectRequestHandler = /** @class */function (_super) {\n __extends(RedirectRequestHandler, _super);\n function RedirectRequestHandler(\n // use the provided storage backend\n // or initialize local storage with the default storage backend which\n // uses window.localStorage\n storageBackend, utils, locationLike, crypto) {\n if (storageBackend === void 0) {\n storageBackend = new storage_1.LocalStorageBackend();\n }\n if (utils === void 0) {\n utils = new query_string_utils_1.BasicQueryStringUtils();\n }\n if (locationLike === void 0) {\n locationLike = window.location;\n }\n if (crypto === void 0) {\n crypto = new crypto_utils_1.DefaultCrypto();\n }\n var _this = _super.call(this, utils, crypto) || this;\n _this.storageBackend = storageBackend;\n _this.locationLike = locationLike;\n return _this;\n }\n RedirectRequestHandler.prototype.performAuthorizationRequest = function (configuration, request) {\n var _this = this;\n var handle = this.crypto.generateRandom(10);\n // before you make request, persist all request related data in local storage.\n var persisted = Promise.all([this.storageBackend.setItem(AUTHORIZATION_REQUEST_HANDLE_KEY, handle),\n // Calling toJson() adds in the code & challenge when possible\n request.toJson().then(function (result) {\n return _this.storageBackend.setItem(authorizationRequestKey(handle), JSON.stringify(result));\n }), this.storageBackend.setItem(authorizationServiceConfigurationKey(handle), JSON.stringify(configuration.toJson()))]);\n persisted.then(function () {\n // make the redirect request\n var url = _this.buildRequestUrl(configuration, request);\n logger_1.log('Making a request to ', request, url);\n _this.locationLike.assign(url);\n });\n };\n /**\n * Attempts to introspect the contents of storage backend and completes the\n * request.\n */\n RedirectRequestHandler.prototype.completeAuthorizationRequest = function () {\n var _this = this;\n // TODO(rahulrav@): handle authorization errors.\n return this.storageBackend.getItem(AUTHORIZATION_REQUEST_HANDLE_KEY).then(function (handle) {\n if (handle) {\n // we have a pending request.\n // fetch authorization request, and check state\n return _this.storageBackend.getItem(authorizationRequestKey(handle))\n // requires a corresponding instance of result\n // TODO(rahulrav@): check for inconsitent state here\n .then(function (result) {\n return JSON.parse(result);\n }).then(function (json) {\n return new authorization_request_1.AuthorizationRequest(json);\n }).then(function (request) {\n // check redirect_uri and state\n var currentUri = \"\" + _this.locationLike.origin + _this.locationLike.pathname;\n var queryParams = _this.utils.parse(_this.locationLike, true /* use hash */);\n var state = queryParams['state'];\n var code = queryParams['code'];\n var error = queryParams['error'];\n logger_1.log('Potential authorization request ', currentUri, queryParams, state, code, error);\n var shouldNotify = state === request.state;\n var authorizationResponse = null;\n var authorizationError = null;\n if (shouldNotify) {\n if (error) {\n // get additional optional info.\n var errorUri = queryParams['error_uri'];\n var errorDescription = queryParams['error_description'];\n authorizationError = new authorization_response_1.AuthorizationError({\n error: error,\n error_description: errorDescription,\n error_uri: errorUri,\n state: state\n });\n } else {\n authorizationResponse = new authorization_response_1.AuthorizationResponse({\n code: code,\n state: state\n });\n }\n // cleanup state\n return Promise.all([_this.storageBackend.removeItem(AUTHORIZATION_REQUEST_HANDLE_KEY), _this.storageBackend.removeItem(authorizationRequestKey(handle)), _this.storageBackend.removeItem(authorizationServiceConfigurationKey(handle))]).then(function () {\n logger_1.log('Delivering authorization response');\n return {\n request: request,\n response: authorizationResponse,\n error: authorizationError\n };\n });\n } else {\n logger_1.log('Mismatched request (state and request_uri) dont match.');\n return Promise.resolve(null);\n }\n });\n } else {\n return null;\n }\n });\n };\n return RedirectRequestHandler;\n}(authorization_request_handler_1.AuthorizationRequestHandler);\nexports.RedirectRequestHandler = RedirectRequestHandler;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.RevokeTokenRequest = void 0;\n/**\n * Represents a revoke token request.\n * For more information look at:\n * https://tools.ietf.org/html/rfc7009#section-2.1\n */\nvar RevokeTokenRequest = /** @class */function () {\n function RevokeTokenRequest(request) {\n this.token = request.token;\n this.tokenTypeHint = request.token_type_hint;\n this.clientId = request.client_id;\n this.clientSecret = request.client_secret;\n }\n /**\n * Serializes a TokenRequest to a JavaScript object.\n */\n RevokeTokenRequest.prototype.toJson = function () {\n var json = {\n token: this.token\n };\n if (this.tokenTypeHint) {\n json['token_type_hint'] = this.tokenTypeHint;\n }\n if (this.clientId) {\n json['client_id'] = this.clientId;\n }\n if (this.clientSecret) {\n json['client_secret'] = this.clientSecret;\n }\n return json;\n };\n RevokeTokenRequest.prototype.toStringMap = function () {\n var json = this.toJson();\n // :(\n return json;\n };\n return RevokeTokenRequest;\n}();\nexports.RevokeTokenRequest = RevokeTokenRequest;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.TokenRequest = exports.GRANT_TYPE_REFRESH_TOKEN = exports.GRANT_TYPE_AUTHORIZATION_CODE = void 0;\nexports.GRANT_TYPE_AUTHORIZATION_CODE = 'authorization_code';\nexports.GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';\n/**\n * Represents an Access Token request.\n * For more information look at:\n * https://tools.ietf.org/html/rfc6749#section-4.1.3\n */\nvar TokenRequest = /** @class */function () {\n function TokenRequest(request) {\n this.clientId = request.client_id;\n this.redirectUri = request.redirect_uri;\n this.grantType = request.grant_type;\n this.code = request.code;\n this.refreshToken = request.refresh_token;\n this.extras = request.extras;\n }\n /**\n * Serializes a TokenRequest to a JavaScript object.\n */\n TokenRequest.prototype.toJson = function () {\n return {\n grant_type: this.grantType,\n code: this.code,\n refresh_token: this.refreshToken,\n redirect_uri: this.redirectUri,\n client_id: this.clientId,\n extras: this.extras\n };\n };\n TokenRequest.prototype.toStringMap = function () {\n var map = {\n grant_type: this.grantType,\n client_id: this.clientId,\n redirect_uri: this.redirectUri\n };\n if (this.code) {\n map['code'] = this.code;\n }\n if (this.refreshToken) {\n map['refresh_token'] = this.refreshToken;\n }\n // copy over extras\n if (this.extras) {\n for (var extra in this.extras) {\n if (this.extras.hasOwnProperty(extra) && !map.hasOwnProperty(extra)) {\n // check before inserting to requestMap\n map[extra] = this.extras[extra];\n }\n }\n }\n return map;\n };\n return TokenRequest;\n}();\nexports.TokenRequest = TokenRequest;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.TokenError = exports.TokenResponse = exports.nowInSeconds = void 0;\n// constants\nvar AUTH_EXPIRY_BUFFER = 10 * 60 * -1; // 10 mins in seconds\n/**\n * Returns the instant of time in seconds.\n */\nvar nowInSeconds = function () {\n return Math.round(new Date().getTime() / 1000);\n};\nexports.nowInSeconds = nowInSeconds;\n/**\n * Represents the Token Response type.\n * For more information look at:\n * https://tools.ietf.org/html/rfc6749#section-5.1\n */\nvar TokenResponse = /** @class */function () {\n function TokenResponse(response) {\n this.accessToken = response.access_token;\n this.tokenType = response.token_type || 'bearer';\n if (response.expires_in) {\n this.expiresIn = parseInt(response.expires_in, 10);\n }\n this.refreshToken = response.refresh_token;\n this.scope = response.scope;\n this.idToken = response.id_token;\n this.issuedAt = response.issued_at || exports.nowInSeconds();\n }\n TokenResponse.prototype.toJson = function () {\n var _a;\n return {\n access_token: this.accessToken,\n id_token: this.idToken,\n refresh_token: this.refreshToken,\n scope: this.scope,\n token_type: this.tokenType,\n issued_at: this.issuedAt,\n expires_in: (_a = this.expiresIn) === null || _a === void 0 ? void 0 : _a.toString()\n };\n };\n TokenResponse.prototype.isValid = function (buffer) {\n if (buffer === void 0) {\n buffer = AUTH_EXPIRY_BUFFER;\n }\n if (this.expiresIn) {\n var now = exports.nowInSeconds();\n return now < this.issuedAt + this.expiresIn + buffer;\n } else {\n return true;\n }\n };\n return TokenResponse;\n}();\nexports.TokenResponse = TokenResponse;\n/**\n * Represents the Token Error type.\n * For more information look at:\n * https://tools.ietf.org/html/rfc6749#section-5.2\n */\nvar TokenError = /** @class */function () {\n function TokenError(tokenError) {\n this.error = tokenError.error;\n this.errorDescription = tokenError.error_description;\n this.errorUri = tokenError.error_uri;\n }\n TokenError.prototype.toJson = function () {\n return {\n error: this.error,\n error_description: this.errorDescription,\n error_uri: this.errorUri\n };\n };\n return TokenError;\n}();\nexports.TokenError = TokenError;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.BaseTokenRequestHandler = void 0;\nvar errors_1 = require(\"./errors\");\nvar query_string_utils_1 = require(\"./query_string_utils\");\nvar token_response_1 = require(\"./token_response\");\nvar xhr_1 = require(\"./xhr\");\n/**\n * The default token request handler.\n */\nvar BaseTokenRequestHandler = /** @class */function () {\n function BaseTokenRequestHandler(requestor, utils) {\n if (requestor === void 0) {\n requestor = new xhr_1.JQueryRequestor();\n }\n if (utils === void 0) {\n utils = new query_string_utils_1.BasicQueryStringUtils();\n }\n this.requestor = requestor;\n this.utils = utils;\n }\n BaseTokenRequestHandler.prototype.isTokenResponse = function (response) {\n return response.error === undefined;\n };\n BaseTokenRequestHandler.prototype.performRevokeTokenRequest = function (configuration, request) {\n var revokeTokenResponse = this.requestor.xhr({\n url: configuration.revocationEndpoint,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data: this.utils.stringify(request.toStringMap())\n });\n return revokeTokenResponse.then(function (response) {\n return true;\n });\n };\n BaseTokenRequestHandler.prototype.performTokenRequest = function (configuration, request) {\n var _this = this;\n var tokenResponse = this.requestor.xhr({\n url: configuration.tokenEndpoint,\n method: 'POST',\n dataType: 'json',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data: this.utils.stringify(request.toStringMap())\n });\n return tokenResponse.then(function (response) {\n if (_this.isTokenResponse(response)) {\n return new token_response_1.TokenResponse(response);\n } else {\n return Promise.reject(new errors_1.AppAuthError(response.error, new token_response_1.TokenError(response)));\n }\n });\n };\n return BaseTokenRequestHandler;\n}();\nexports.BaseTokenRequestHandler = BaseTokenRequestHandler;\n","\"use strict\";\n\n/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n","\"use strict\";\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\nvar __exportStar = this && this.__exportStar || function (m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n__exportStar(require(\"./authorization_request\"), exports);\n__exportStar(require(\"./authorization_request_handler\"), exports);\n__exportStar(require(\"./authorization_response\"), exports);\n__exportStar(require(\"./authorization_service_configuration\"), exports);\n__exportStar(require(\"./crypto_utils\"), exports);\n__exportStar(require(\"./errors\"), exports);\n__exportStar(require(\"./flags\"), exports);\n__exportStar(require(\"./logger\"), exports);\n__exportStar(require(\"./query_string_utils\"), exports);\n__exportStar(require(\"./redirect_based_handler\"), exports);\n__exportStar(require(\"./revoke_token_request\"), exports);\n__exportStar(require(\"./storage\"), exports);\n__exportStar(require(\"./token_request\"), exports);\n__exportStar(require(\"./token_request_handler\"), exports);\n__exportStar(require(\"./token_response\"), exports);\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./xhr\"), exports);\n","import { __awaiter } from \"tslib\";\nexport class IonicUserInfoHandler {\n constructor(requestor) {\n this.requestor = requestor;\n }\n performUserInfoRequest(configuration, token) {\n return __awaiter(this, void 0, void 0, function* () {\n let settings = {\n url: configuration.userInfoEndpoint,\n dataType: 'json',\n method: 'GET',\n headers: {\n Authorization: `${token.tokenType == 'bearer' ? 'Bearer' : token.tokenType} ${token.accessToken}`,\n 'Content-Type': 'application/json'\n }\n };\n return this.requestor.xhr(settings);\n });\n }\n}","import { __awaiter } from \"tslib\";\nimport { BasicQueryStringUtils } from '@openid/appauth';\nexport class IonicEndSessionHandler {\n constructor(browser, utils = new BasicQueryStringUtils()) {\n this.browser = browser;\n this.utils = utils;\n }\n performEndSessionRequest(configuration, request) {\n return __awaiter(this, void 0, void 0, function* () {\n let url = this.buildRequestUrl(configuration, request);\n return this.browser.showWindow(url, request.postLogoutRedirectURI);\n });\n }\n buildRequestUrl(configuration, request) {\n let requestMap = {\n id_token_hint: request.idTokenHint,\n post_logout_redirect_uri: request.postLogoutRedirectURI,\n state: request.state\n };\n let query = this.utils.stringify(requestMap);\n let baseUrl = configuration.endSessionEndpoint;\n let url = `${baseUrl}?${query}`;\n return url;\n }\n}","import { __awaiter } from \"tslib\";\nimport { AuthorizationRequestHandler, BasicQueryStringUtils, DefaultCrypto, AuthorizationRequest, AuthorizationError, AuthorizationResponse } from '@openid/appauth';\n/** key for authorization request. */\nconst authorizationRequestKey = handle => {\n return `${handle}_appauth_authorization_request`;\n};\n/** key in local storage which represents the current authorization request. */\nconst AUTHORIZATION_REQUEST_HANDLE_KEY = 'appauth_current_authorization_request';\nexport const AUTHORIZATION_RESPONSE_KEY = 'auth_response';\nexport class IonicAuthorizationRequestHandler extends AuthorizationRequestHandler {\n constructor(browser, storage, utils = new BasicQueryStringUtils(), generateRandom = new DefaultCrypto()) {\n super(utils, generateRandom);\n this.browser = browser;\n this.storage = storage;\n this.generateRandom = generateRandom;\n }\n performAuthorizationRequest(configuration, request) {\n return __awaiter(this, void 0, void 0, function* () {\n let handle = this.generateRandom.generateRandom(10);\n yield this.storage.setItem(AUTHORIZATION_REQUEST_HANDLE_KEY, handle);\n yield this.storage.setItem(authorizationRequestKey(handle), JSON.stringify(yield request.toJson()));\n let url = this.buildRequestUrl(configuration, request);\n let returnedUrl = yield this.browser.showWindow(url, request.redirectUri);\n //callback may come from showWindow or via another method\n if (returnedUrl != undefined) {\n yield this.storage.setItem(AUTHORIZATION_RESPONSE_KEY, returnedUrl);\n this.completeAuthorizationRequestIfPossible();\n }\n });\n }\n completeAuthorizationRequest() {\n return __awaiter(this, void 0, void 0, function* () {\n let handle = yield this.storage.getItem(AUTHORIZATION_REQUEST_HANDLE_KEY);\n if (!handle) {\n throw new Error('Handle Not Available');\n }\n let request = this.getAuthorizationRequest(yield this.storage.getItem(authorizationRequestKey(handle)));\n let queryParams = this.getQueryParams(yield this.storage.getItem(AUTHORIZATION_RESPONSE_KEY));\n this.removeItemsFromStorage(handle);\n let state = queryParams['state'];\n let error = queryParams['error'];\n if (state !== request.state) {\n throw new Error('State Does Not Match');\n }\n return {\n request: request,\n response: !error ? this.getAuthorizationResponse(queryParams) : undefined,\n error: error ? this.getAuthorizationError(queryParams) : undefined\n };\n });\n }\n getAuthorizationRequest(authRequest) {\n if (authRequest == null) {\n throw new Error('No Auth Request Available');\n }\n return new AuthorizationRequest(JSON.parse(authRequest));\n }\n getAuthorizationError(queryParams) {\n let authorizationErrorJSON = {\n error: queryParams['error'],\n error_description: queryParams['error_description'],\n error_uri: undefined,\n state: queryParams['state']\n };\n return new AuthorizationError(authorizationErrorJSON);\n }\n getAuthorizationResponse(queryParams) {\n let authorizationResponseJSON = {\n code: queryParams['code'],\n state: queryParams['state']\n };\n return new AuthorizationResponse(authorizationResponseJSON);\n }\n removeItemsFromStorage(handle) {\n this.storage.removeItem(AUTHORIZATION_REQUEST_HANDLE_KEY);\n this.storage.removeItem(authorizationRequestKey(handle));\n this.storage.removeItem(AUTHORIZATION_RESPONSE_KEY);\n }\n getQueryParams(authResponse) {\n if (authResponse != null) {\n let querySide = authResponse.split('#')[0];\n let parts = querySide.split('?');\n if (parts.length !== 2) throw new Error('Invalid auth response string');\n let hash = parts[1];\n return this.utils.parseQueryString(hash);\n } else {\n return {};\n }\n }\n}","export class Browser {\n constructor() {\n this.onCloseFunction = () => {};\n }\n browserCloseListener(closeBrowserEvent) {\n this.onCloseFunction = closeBrowserEvent;\n }\n}\nexport class DefaultBrowser extends Browser {\n showWindow(url) {\n const openWindow = window.open(url, '_self');\n if (openWindow) {\n openWindow.addEventListener('beforeupload', () => this.onCloseFunction());\n }\n return;\n }\n closeWindow() {\n // Invoking window.close() is not desired. It will either be ignored (most of the time),\n // or it will close the current browser tab if this site was opened via a \"_blank\" target.\n }\n}","import { DefaultCrypto } from '@openid/appauth/built/crypto_utils';\nconst BYTES_LENGTH = 10;\nconst newState = function (crypto) {\n return crypto.generateRandom(BYTES_LENGTH);\n};\nexport class EndSessionRequest {\n constructor(request, crypto = new DefaultCrypto()) {\n this.state = request.state || newState(crypto);\n this.idTokenHint = request.idTokenHint;\n this.postLogoutRedirectURI = request.postLogoutRedirectURI;\n }\n toJson() {\n let json = {\n idTokenHint: this.idTokenHint,\n postLogoutRedirectURI: this.postLogoutRedirectURI\n };\n if (this.state) {\n json['state'] = this.state;\n }\n return json;\n }\n}","\"use strict\";\n\nexports.__esModule = true;\nvar Guid = /** @class */function () {\n function Guid(guid) {\n if (!guid) {\n throw new TypeError(\"Invalid argument; `value` has no value.\");\n }\n this.value = Guid.EMPTY;\n if (guid && Guid.isGuid(guid)) {\n this.value = guid;\n }\n }\n Guid.isGuid = function (guid) {\n var value = guid.toString();\n return guid && (guid instanceof Guid || Guid.validator.test(value));\n };\n Guid.create = function () {\n return new Guid([Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join(\"-\"));\n };\n Guid.createEmpty = function () {\n return new Guid(\"emptyguid\");\n };\n Guid.parse = function (guid) {\n return new Guid(guid);\n };\n Guid.raw = function () {\n return [Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join(\"-\");\n };\n Guid.gen = function (count) {\n var out = \"\";\n for (var i = 0; i < count; i++) {\n // tslint:disable-next-line:no-bitwise\n out += ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);\n }\n return out;\n };\n Guid.prototype.equals = function (other) {\n // Comparing string `value` against provided `guid` will auto-call\n // toString on `guid` for comparison\n return Guid.isGuid(other) && this.value === other.toString();\n };\n Guid.prototype.isEmpty = function () {\n return this.value === Guid.EMPTY;\n };\n Guid.prototype.toString = function () {\n return this.value;\n };\n Guid.prototype.toJSON = function () {\n return {\n value: this.value\n };\n };\n Guid.validator = new RegExp(\"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$\", \"i\");\n Guid.EMPTY = \"00000000-0000-0000-0000-000000000000\";\n return Guid;\n}();\nexports.Guid = Guid;","export class DefaultAuthSession {\n constructor() {\n this.isAuthenticated = false;\n this.token = undefined;\n this.user = undefined;\n this.error = undefined;\n }\n}","import { AuthActions } from './auth-action';\nimport { Guid } from 'guid-typescript';\nimport { DefaultAuthSession } from './auth-session';\nexport class BaseAuthObserver {\n constructor() {\n this.id = Guid.create();\n }\n}\nexport class AuthObserver extends BaseAuthObserver {\n constructor(func) {\n super();\n this.func = func;\n }\n update(action) {\n this.func(action);\n }\n static Create(func) {\n return new AuthObserver(func);\n }\n}\nexport class TokenObserver extends BaseAuthObserver {\n update(action) {\n this.token = action.tokenResponse;\n }\n}\nexport class ActionHistoryObserver extends BaseAuthObserver {\n constructor() {\n super(...arguments);\n this.history = [];\n }\n update(action) {\n this.lastAction = action;\n this.history.push(action);\n }\n clear() {\n this.history = [];\n this.lastAction = undefined;\n }\n}\nexport class SessionObserver extends BaseAuthObserver {\n constructor() {\n super(...arguments);\n this.session = new DefaultAuthSession();\n }\n update(action) {\n switch (action.action) {\n case AuthActions.SignInFailed:\n case AuthActions.RefreshFailed:\n case AuthActions.LoadTokenFromStorageFailed:\n this.session.error = action.error;\n this.session.token = undefined;\n this.session.user = undefined;\n this.session.isAuthenticated = false;\n break;\n case AuthActions.SignInSuccess:\n case AuthActions.RefreshSuccess:\n case AuthActions.LoadTokenFromStorageSuccess:\n this.session.error = undefined;\n this.session.token = action.tokenResponse;\n this.session.isAuthenticated = true;\n break;\n case AuthActions.LoadUserInfoSuccess:\n this.session.error = undefined;\n this.session.user = action.user;\n break;\n case AuthActions.LoadUserInfoFailed:\n this.session.error = action.error;\n this.session.user = undefined;\n break;\n case AuthActions.SignOutSuccess:\n case AuthActions.Init:\n this.session = new DefaultAuthSession();\n break;\n case AuthActions.SignOutFailed:\n this.session.error = action.error;\n break;\n }\n }\n}\nexport class ConsoleLogObserver extends BaseAuthObserver {\n update(action) {\n console.log(action);\n }\n}","export class AuthSubject {\n constructor() {\n this.observers = [];\n }\n attach(observer) {\n const observerIndex = this.observers.indexOf(observer);\n if (observerIndex !== -1) {\n return console.log('Subject: Observer has been attached already.');\n }\n this.observers.push(observer);\n }\n detach(observer) {\n const observerIndex = this.observers.indexOf(observer);\n if (observerIndex === -1) {\n return console.log('Subject: Nonexistent observer.');\n }\n this.observers.splice(observerIndex, 1);\n }\n notify(action) {\n for (const observer of this.observers) {\n observer.update(action);\n }\n }\n}","import { __awaiter } from \"tslib\";\nimport { RevokeTokenRequest } from '@openid/appauth';\nimport { AuthActionBuilder, AuthActions } from './auth-action';\nimport { IonicUserInfoHandler } from './user-info-request-handler';\nimport { IonicEndSessionHandler } from './end-session-request-handler';\nimport { IonicAuthorizationRequestHandler, AUTHORIZATION_RESPONSE_KEY } from './authorization-request-handler';\nimport { DefaultBrowser } from './auth-browser';\nimport { BaseTokenRequestHandler, AuthorizationServiceConfiguration, AuthorizationNotifier, TokenResponse, AuthorizationRequest, DefaultCrypto, GRANT_TYPE_AUTHORIZATION_CODE, TokenRequest, GRANT_TYPE_REFRESH_TOKEN, LocalStorageBackend, JQueryRequestor } from '@openid/appauth';\nimport { EndSessionRequest } from './end-session-request';\nimport { BehaviorSubject } from 'rxjs';\nimport { ActionHistoryObserver, AuthObserver, SessionObserver } from './auth-observer';\nimport { AuthSubject } from './auth-subject';\nconst TOKEN_RESPONSE_KEY = 'token_response';\nconst AUTH_EXPIRY_BUFFER = 10 * 60 * -1; // 10 mins in seconds\nexport class AuthService {\n constructor(browser = new DefaultBrowser(), storage = new LocalStorageBackend(), requestor = new JQueryRequestor()) {\n this.browser = browser;\n this.storage = storage;\n this.requestor = requestor;\n this._authSubject = new AuthSubject();\n this._actionHistory = new ActionHistoryObserver();\n this._session = new SessionObserver();\n this._authSubjectV2 = new BehaviorSubject(AuthActionBuilder.Init());\n this._tokenSubject = new BehaviorSubject(undefined);\n this._userSubject = new BehaviorSubject(undefined);\n this._authenticatedSubject = new BehaviorSubject(false);\n this._initComplete = new BehaviorSubject(false);\n this.tokenHandler = new BaseTokenRequestHandler(requestor);\n this.userInfoHandler = new IonicUserInfoHandler(requestor);\n this.requestHandler = new IonicAuthorizationRequestHandler(browser, storage);\n this.endSessionHandler = new IonicEndSessionHandler(browser);\n }\n /**\n * @deprecated independant observers have been replaced by Rxjs\n * this will be removed in a future release\n * please use $ suffixed observers in future\n */\n get history() {\n return this._actionHistory.history.slice(0);\n }\n /**\n * @deprecated independant observers have been replaced by Rxjs\n * this will be removed in a future release\n * please use $ suffixed observers in future\n */\n get session() {\n return this._session.session;\n }\n get token$() {\n return this._tokenSubject.asObservable();\n }\n get isAuthenticated$() {\n return this._authenticatedSubject.asObservable();\n }\n get initComplete$() {\n return this._initComplete.asObservable();\n }\n get user$() {\n return this._userSubject.asObservable();\n }\n get events$() {\n return this._authSubjectV2.asObservable();\n }\n get authConfig() {\n if (!this._authConfig) throw new Error('AuthConfig Not Defined');\n return this._authConfig;\n }\n set authConfig(value) {\n this._authConfig = value;\n }\n get configuration() {\n if (!this._configuration) {\n return AuthorizationServiceConfiguration.fetchFromIssuer(this.authConfig.server_host, this.requestor).catch(() => {\n throw new Error('Unable To Obtain Server Configuration');\n });\n }\n if (this._configuration != undefined) {\n return Promise.resolve(this._configuration);\n } else {\n throw new Error('Unable To Obtain Server Configuration');\n }\n }\n init() {\n return __awaiter(this, void 0, void 0, function* () {\n this.setupAuthorizationNotifier();\n this.loadTokenFromStorage();\n this.addActionObserver(this._actionHistory);\n this.addActionObserver(this._session);\n });\n }\n notifyActionListers(action) {\n switch (action.action) {\n case AuthActions.RefreshFailed:\n case AuthActions.SignInFailed:\n case AuthActions.SignOutSuccess:\n case AuthActions.SignOutFailed:\n this._tokenSubject.next(undefined);\n this._userSubject.next(undefined);\n this._authenticatedSubject.next(false);\n break;\n case AuthActions.LoadTokenFromStorageFailed:\n this._tokenSubject.next(undefined);\n this._userSubject.next(undefined);\n this._authenticatedSubject.next(false);\n this._initComplete.next(true);\n break;\n case AuthActions.SignInSuccess:\n case AuthActions.RefreshSuccess:\n this._tokenSubject.next(action.tokenResponse);\n this._authenticatedSubject.next(true);\n break;\n case AuthActions.LoadTokenFromStorageSuccess:\n this._tokenSubject.next(action.tokenResponse);\n this._authenticatedSubject.next(action.tokenResponse.isValid(0));\n this._initComplete.next(true);\n break;\n case AuthActions.RevokeTokensSuccess:\n this._tokenSubject.next(undefined);\n break;\n case AuthActions.LoadUserInfoSuccess:\n this._userSubject.next(action.user);\n break;\n case AuthActions.LoadUserInfoFailed:\n this._userSubject.next(undefined);\n break;\n }\n this._authSubjectV2.next(action);\n this._authSubject.notify(action);\n }\n setupAuthorizationNotifier() {\n let notifier = new AuthorizationNotifier();\n this.requestHandler.setAuthorizationNotifier(notifier);\n notifier.setAuthorizationListener((request, response, error) => this.onAuthorizationNotification(request, response, error));\n }\n onAuthorizationNotification(request, response, error) {\n let codeVerifier = request.internal != undefined && this.authConfig.pkce ? request.internal.code_verifier : undefined;\n if (response != null) {\n this.requestAccessToken(response.code, codeVerifier);\n } else if (error != null) {\n throw new Error(error.errorDescription);\n } else {\n throw new Error('Unknown Error With Authentication');\n }\n }\n internalAuthorizationCallback(url) {\n return __awaiter(this, void 0, void 0, function* () {\n this.browser.closeWindow();\n yield this.storage.setItem(AUTHORIZATION_RESPONSE_KEY, url);\n return this.requestHandler.completeAuthorizationRequestIfPossible();\n });\n }\n internalEndSessionCallback() {\n return __awaiter(this, void 0, void 0, function* () {\n this.browser.closeWindow();\n this._actionHistory.clear();\n this.notifyActionListers(AuthActionBuilder.SignOutSuccess());\n });\n }\n performEndSessionRequest(state) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._tokenSubject.value != undefined) {\n let requestJson = {\n postLogoutRedirectURI: this.authConfig.end_session_redirect_url,\n idTokenHint: this._tokenSubject.value.idToken || '',\n state: state || undefined\n };\n let request = new EndSessionRequest(requestJson);\n let returnedUrl = yield this.endSessionHandler.performEndSessionRequest(yield this.configuration, request);\n //callback may come from showWindow or via another method\n if (returnedUrl != undefined) {\n this.endSessionCallback();\n }\n } else {\n //if user has no token they should not be logged in in the first place\n this.endSessionCallback();\n }\n });\n }\n performAuthorizationRequest(authExtras, state) {\n return __awaiter(this, void 0, void 0, function* () {\n let requestJson = {\n response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,\n client_id: this.authConfig.client_id,\n redirect_uri: this.authConfig.redirect_url,\n scope: this.authConfig.scopes,\n extras: authExtras,\n state: state || undefined\n };\n let request = new AuthorizationRequest(requestJson, new DefaultCrypto(), this.authConfig.pkce);\n if (this.authConfig.pkce) yield request.setupCodeVerifier();\n return this.requestHandler.performAuthorizationRequest(yield this.configuration, request);\n });\n }\n requestAccessToken(code, codeVerifier) {\n return __awaiter(this, void 0, void 0, function* () {\n let requestJSON = {\n grant_type: GRANT_TYPE_AUTHORIZATION_CODE,\n code: code,\n refresh_token: undefined,\n redirect_uri: this.authConfig.redirect_url,\n client_id: this.authConfig.client_id,\n extras: codeVerifier ? {\n code_verifier: codeVerifier,\n client_secret: this.authConfig.client_secret\n } : {\n client_secret: this.authConfig.client_secret\n }\n };\n let token = yield this.tokenHandler.performTokenRequest(yield this.configuration, new TokenRequest(requestJSON));\n yield this.storage.setItem(TOKEN_RESPONSE_KEY, JSON.stringify(token.toJson()));\n this.notifyActionListers(AuthActionBuilder.SignInSuccess(token));\n });\n }\n requestTokenRefresh() {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (!this._tokenSubject.value) {\n throw new Error('No Token Defined!');\n }\n let requestJSON = {\n grant_type: GRANT_TYPE_REFRESH_TOKEN,\n refresh_token: (_a = this._tokenSubject.value) === null || _a === void 0 ? void 0 : _a.refreshToken,\n redirect_uri: this.authConfig.redirect_url,\n client_id: this.authConfig.client_id\n };\n let token = yield this.tokenHandler.performTokenRequest(yield this.configuration, new TokenRequest(requestJSON));\n yield this.storage.setItem(TOKEN_RESPONSE_KEY, JSON.stringify(token.toJson()));\n this.notifyActionListers(AuthActionBuilder.RefreshSuccess(token));\n });\n }\n internalLoadTokenFromStorage() {\n return __awaiter(this, void 0, void 0, function* () {\n let token;\n let tokenResponseString = yield this.storage.getItem(TOKEN_RESPONSE_KEY);\n if (tokenResponseString != null) {\n token = new TokenResponse(JSON.parse(tokenResponseString));\n if (token) {\n return this.notifyActionListers(AuthActionBuilder.LoadTokenFromStorageSuccess(token));\n }\n }\n throw new Error('No Token In Storage');\n });\n }\n requestTokenRevoke() {\n return __awaiter(this, void 0, void 0, function* () {\n let revokeRefreshJson = {\n token: this._tokenSubject.value.refreshToken,\n token_type_hint: 'refresh_token',\n client_id: this.authConfig.client_id\n };\n let revokeAccessJson = {\n token: this._tokenSubject.value.accessToken,\n token_type_hint: 'access_token',\n client_id: this.authConfig.client_id\n };\n yield this.tokenHandler.performRevokeTokenRequest(yield this.configuration, new RevokeTokenRequest(revokeRefreshJson));\n yield this.tokenHandler.performRevokeTokenRequest(yield this.configuration, new RevokeTokenRequest(revokeAccessJson));\n yield this.storage.removeItem(TOKEN_RESPONSE_KEY);\n this.notifyActionListers(AuthActionBuilder.RevokeTokensSuccess());\n });\n }\n internalRequestUserInfo() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._tokenSubject.value) {\n let userInfo = yield this.userInfoHandler.performUserInfoRequest(yield this.configuration, this._tokenSubject.value);\n this.notifyActionListers(AuthActionBuilder.LoadUserInfoSuccess(userInfo));\n } else {\n throw new Error('No Token Available');\n }\n });\n }\n loadTokenFromStorage() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.internalLoadTokenFromStorage().catch(response => {\n this.notifyActionListers(AuthActionBuilder.LoadTokenFromStorageFailed(response));\n });\n });\n }\n signIn(authExtras, state) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.performAuthorizationRequest(authExtras, state).catch(response => {\n this.notifyActionListers(AuthActionBuilder.SignInFailed(response));\n });\n });\n }\n signOut(state, revokeTokens) {\n return __awaiter(this, void 0, void 0, function* () {\n if (revokeTokens) {\n yield this.revokeTokens();\n }\n yield this.storage.removeItem(TOKEN_RESPONSE_KEY);\n if ((yield this.configuration).endSessionEndpoint) {\n yield this.performEndSessionRequest(state).catch(response => {\n this.notifyActionListers(AuthActionBuilder.SignOutFailed(response));\n });\n }\n });\n }\n revokeTokens() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.requestTokenRevoke().catch(response => {\n this.storage.removeItem(TOKEN_RESPONSE_KEY);\n this.notifyActionListers(AuthActionBuilder.RevokeTokensFailed(response));\n });\n });\n }\n refreshToken() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.requestTokenRefresh().catch(response => {\n this.storage.removeItem(TOKEN_RESPONSE_KEY);\n this.notifyActionListers(AuthActionBuilder.RefreshFailed(response));\n });\n });\n }\n loadUserInfo() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.internalRequestUserInfo().catch(response => {\n this.notifyActionListers(AuthActionBuilder.LoadUserInfoFailed(response));\n });\n });\n }\n authorizationCallback(callbackUrl) {\n this.internalAuthorizationCallback(callbackUrl).catch(response => {\n this.notifyActionListers(AuthActionBuilder.SignInFailed(response));\n });\n }\n endSessionCallback() {\n this.internalEndSessionCallback().catch(response => {\n this.notifyActionListers(AuthActionBuilder.SignOutFailed(response));\n });\n }\n getValidToken(buffer = AUTH_EXPIRY_BUFFER) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._tokenSubject.value) {\n if (!this._tokenSubject.value.isValid(buffer)) {\n yield this.refreshToken();\n if (this._tokenSubject.value) {\n return this._tokenSubject.value;\n }\n } else {\n return this._tokenSubject.value;\n }\n }\n throw new Error('Unable To Obtain Valid Token');\n });\n }\n /**\n * @deprecated independant observers have been replaced by Rxjs\n * this will be removed in a future release\n * please use $ suffixed observers in future\n */\n addActionListener(func) {\n let observer = AuthObserver.Create(func);\n this.addActionObserver(observer);\n return observer;\n }\n /**\n * @deprecated independant observers have been replaced by Rxjs\n * this will be removed in a future release\n * please use $ suffixed observers in future\n */\n addActionObserver(observer) {\n if (this._actionHistory.lastAction) {\n observer.update(this._actionHistory.lastAction);\n }\n this._authSubject.attach(observer);\n }\n /**\n * @deprecated independant observers have been replaced by Rxjs\n * this will be removed in a future release\n * please use $ suffixed observers in future\n */\n removeActionObserver(observer) {\n this._authSubject.detach(observer);\n }\n}","export var AuthenticationType = /*#__PURE__*/function (AuthenticationType) {\n AuthenticationType[\"Token\"] = \"token\";\n AuthenticationType[\"AuthorizationCode\"] = \"code\";\n AuthenticationType[\"IdToken\"] = \"id_token\";\n return AuthenticationType;\n}(AuthenticationType || {});","/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function (f) {\n if (typeof exports === \"object\" && typeof module !== \"undefined\") {\n module.exports = f();\n } else if (typeof define === \"function\" && define.amd) {\n define([], f);\n } else {\n var g;\n if (typeof window !== \"undefined\") {\n g = window;\n } else if (typeof global !== \"undefined\") {\n g = global;\n } else if (typeof self !== \"undefined\") {\n g = self;\n } else {\n g = this;\n }\n g.localforage = f();\n }\n})(function () {\n var define, module, exports;\n return function e(t, n, r) {\n function s(o, u) {\n if (!n[o]) {\n if (!t[o]) {\n var a = typeof require == \"function\" && require;\n if (!u && a) return a(o, !0);\n if (i) return i(o, !0);\n var f = new Error(\"Cannot find module '\" + o + \"'\");\n throw f.code = \"MODULE_NOT_FOUND\", f;\n }\n var l = n[o] = {\n exports: {}\n };\n t[o][0].call(l.exports, function (e) {\n var n = t[o][1][e];\n return s(n ? n : e);\n }, l, l.exports, e, t, n, r);\n }\n return n[o].exports;\n }\n var i = typeof require == \"function\" && require;\n for (var o = 0; o < r.length; o++) s(r[o]);\n return s;\n }({\n 1: [function (_dereq_, module, exports) {\n (function (global) {\n 'use strict';\n\n var Mutation = global.MutationObserver || global.WebKitMutationObserver;\n var scheduleDrain;\n {\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = called = ++called % 2;\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n // Create a