{"version":3,"file":"firebase-messaging.js","sources":["../../node_modules/tslib/tslib.es6.js","../util/dist/index.esm.js","../messaging/dist/index.esm.js"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","import { __extends } from 'tslib';\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nvar CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n * @param {*} assertion The assertion to be tested for falsiness\r\n * @param {!string} message The message to display if the check fails\r\n */\r\nvar assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n * @param {string} message\r\n * @return {!Error}\r\n */\r\nvar assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar stringToByteArray = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n var out = [], p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) == 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param {Array} bytes Array of numbers representing characters.\r\n * @return {string} Stringification of the array.\r\n */\r\nvar byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n var out = [], pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n var c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n var c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n var c2 = bytes[pos++];\r\n var c3 = bytes[pos++];\r\n var c4 = bytes[pos++];\r\n var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n var c2 = bytes[pos++];\r\n var c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// Static lookup maps, lazily populated by init_()\r\nvar base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n * @type {Object}\r\n * @private\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n * @type {Object}\r\n * @private\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @type {Object}\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @type {Object}\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n * @type {string}\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n * @type {string}\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n * @type {string}\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n * @type {boolean}\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param {Array|Uint8Array} input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param {boolean=} opt_webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return {string} The base64 encoded string.\r\n */\r\n encodeByteArray: function (input, opt_webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n var byteToCharMap = opt_webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n var output = [];\r\n for (var i = 0; i < input.length; i += 3) {\r\n var byte1 = input[i];\r\n var haveByte2 = i + 1 < input.length;\r\n var byte2 = haveByte2 ? input[i + 1] : 0;\r\n var haveByte3 = i + 2 < input.length;\r\n var byte3 = haveByte3 ? input[i + 2] : 0;\r\n var outByte1 = byte1 >> 2;\r\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n var outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param {string} input A string to encode.\r\n * @param {boolean=} opt_webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return {string} The base64 encoded string.\r\n */\r\n encodeString: function (input, opt_webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray(input), opt_webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param {string} input to decode.\r\n * @param {boolean=} opt_webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return {string} string representing the decoded value.\r\n */\r\n decodeString: function (input, opt_webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param {string} input Input to decode.\r\n * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet.\r\n * @return {!Array} bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray: function (input, opt_webSafe) {\r\n this.init_();\r\n var charToByteMap = opt_webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n var output = [];\r\n for (var i = 0; i < input.length;) {\r\n var byte1 = charToByteMap[input.charAt(i++)];\r\n var haveByte2 = i < input.length;\r\n var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n var haveByte3 = i < input.length;\r\n var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n var haveByte4 = i < input.length;\r\n var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw Error();\r\n }\r\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 != 64) {\r\n var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 != 64) {\r\n var outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_: function () {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (var i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * URL-safe base64 encoding\r\n * @param {!string} str\r\n * @return {!string}\r\n */\r\nvar base64Encode = function (str) {\r\n var utf8Bytes = stringToByteArray(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param {string} str To be decoded\r\n * @return {?string} Decoded result, if possible\r\n */\r\nvar base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n var dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (var prop in source) {\r\n if (!source.hasOwnProperty(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\n// TODO: Really needed (for JSCompiler type checking)?\r\nfunction patchProperty(obj, prop, value) {\r\n obj[prop] = value;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Deferred = /** @class */ (function () {\r\n function Deferred() {\r\n var _this = this;\r\n this.promise = new Promise(function (resolve, reject) {\r\n _this.resolve = resolve;\r\n _this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} callback\r\n * @return {!function(?(Error), ?=)}\r\n */\r\n Deferred.prototype.wrapCallback = function (callback) {\r\n var _this = this;\r\n return function (error, value) {\r\n if (error) {\r\n _this.reject(error);\r\n }\r\n else {\r\n _this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n _this.promise.catch(function () { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n };\r\n return Deferred;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return {string} user agent string\r\n */\r\nvar getUA = function () {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n};\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor\r\n * Cordova `onDeviceReady`, which would normally wait for a callback.\r\n *\r\n * @return {boolean} isMobileCordova\r\n */\r\nvar isMobileCordova = function () {\r\n return (typeof window !== 'undefined' &&\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n};\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return {boolean} True if ReactNative environment is detected.\r\n */\r\nvar isReactNative = function () {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n};\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return {boolean} True if Node.js environment is detected.\r\n */\r\nvar isNodeSdk = function () {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n};\n\nvar ERROR_NAME = 'FirebaseError';\r\nvar captureStackTrace = Error\r\n .captureStackTrace;\r\n// Export for faking in tests\r\nfunction patchCapture(captureFake) {\r\n var result = captureStackTrace;\r\n captureStackTrace = captureFake;\r\n return result;\r\n}\r\nvar FirebaseError = /** @class */ (function () {\r\n function FirebaseError(code, message) {\r\n this.code = code;\r\n this.message = message;\r\n // We want the stack value, if implemented by Error\r\n if (captureStackTrace) {\r\n // Patches this.stack, omitted calls above ErrorFactory#create\r\n captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n else {\r\n var err_1 = Error.apply(this, arguments);\r\n this.name = ERROR_NAME;\r\n // Make non-enumerable getter for the property.\r\n Object.defineProperty(this, 'stack', {\r\n get: function () {\r\n return err_1.stack;\r\n }\r\n });\r\n }\r\n }\r\n return FirebaseError;\r\n}());\r\n// Back-door inheritance\r\nFirebaseError.prototype = Object.create(Error.prototype);\r\nFirebaseError.prototype.constructor = FirebaseError;\r\nFirebaseError.prototype.name = ERROR_NAME;\r\nvar ErrorFactory = /** @class */ (function () {\r\n function ErrorFactory(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n // Matches {$name}, by default.\r\n this.pattern = /\\{\\$([^}]+)}/g;\r\n // empty\r\n }\r\n ErrorFactory.prototype.create = function (code, data) {\r\n if (data === undefined) {\r\n data = {};\r\n }\r\n var template = this.errors[code];\r\n var fullCode = this.service + '/' + code;\r\n var message;\r\n if (template === undefined) {\r\n message = 'Error';\r\n }\r\n else {\r\n message = template.replace(this.pattern, function (match, key) {\r\n var value = data[key];\r\n return value !== undefined ? value.toString() : '<' + key + '?>';\r\n });\r\n }\r\n // Service: Error message (service/code).\r\n message = this.serviceName + ': ' + message + ' (' + fullCode + ').';\r\n var err = new FirebaseError(fullCode, message);\r\n // Populate the Error object with message parts for programmatic\r\n // accesses (e.g., e.file).\r\n for (var prop in data) {\r\n if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') {\r\n continue;\r\n }\r\n err[prop] = data[prop];\r\n }\r\n return err;\r\n };\r\n return ErrorFactory;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n *\r\n * @param {?string} token\r\n * @return {{header: *, claims: *, data: *, signature: string}}\r\n */\r\nvar decode = function (token) {\r\n var header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n var parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header: header,\r\n claims: claims,\r\n data: data,\r\n signature: signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n *\r\n * @param {?string} token\r\n * @return {boolean}\r\n */\r\nvar isValidTimestamp = function (token) {\r\n var claims = decode(token).claims, now = Math.floor(new Date().getTime() / 1000), validSince, validUntil;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (now && validSince && validUntil && now >= validSince && now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n *\r\n * @param {?string} token\r\n * @return {?number}\r\n */\r\nvar issuedAtTime = function (token) {\r\n var claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time and non-empty\r\n * signature.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n *\r\n * @param {?string} token\r\n * @return {boolean}\r\n */\r\nvar isValidFormat = function (token) {\r\n var decoded = decode(token), claims = decoded.claims;\r\n return (!!decoded.signature &&\r\n !!claims &&\r\n typeof claims === 'object' &&\r\n claims.hasOwnProperty('iat'));\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n *\r\n * @param {?string} token\r\n * @return {boolean}\r\n */\r\nvar isAdmin = function (token) {\r\n var claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/\r\nvar contains = function (obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n};\r\nvar safeGet = function (obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key))\r\n return obj[key];\r\n // else return undefined.\r\n};\r\n/**\r\n * Enumerates the keys/values in an object, excluding keys defined on the prototype.\r\n *\r\n * @param {?Object.} obj Object to enumerate.\r\n * @param {!function(K, V)} fn Function to call for each key and value.\r\n * @template K,V\r\n */\r\nvar forEach = function (obj, fn) {\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n fn(key, obj[key]);\r\n }\r\n }\r\n};\r\n/**\r\n * Copies all the (own) properties from one object to another.\r\n * @param {!Object} objTo\r\n * @param {!Object} objFrom\r\n * @return {!Object} objTo\r\n */\r\nvar extend = function (objTo, objFrom) {\r\n forEach(objFrom, function (key, value) {\r\n objTo[key] = value;\r\n });\r\n return objTo;\r\n};\r\n/**\r\n * Returns a clone of the specified object.\r\n * @param {!Object} obj\r\n * @return {!Object} cloned obj.\r\n */\r\nvar clone = function (obj) {\r\n return extend({}, obj);\r\n};\r\n/**\r\n * Returns true if obj has typeof \"object\" and is not null. Unlike goog.isObject(), does not return true\r\n * for functions.\r\n *\r\n * @param obj {*} A potential object.\r\n * @returns {boolean} True if it's an object.\r\n */\r\nvar isNonNullObject = function (obj) {\r\n return typeof obj === 'object' && obj !== null;\r\n};\r\nvar isEmpty = function (obj) {\r\n for (var key in obj) {\r\n return false;\r\n }\r\n return true;\r\n};\r\nvar getCount = function (obj) {\r\n var rv = 0;\r\n for (var key in obj) {\r\n rv++;\r\n }\r\n return rv;\r\n};\r\nvar map = function (obj, f, opt_obj) {\r\n var res = {};\r\n for (var key in obj) {\r\n res[key] = f.call(opt_obj, obj[key], key, obj);\r\n }\r\n return res;\r\n};\r\nvar findKey = function (obj, fn, opt_this) {\r\n for (var key in obj) {\r\n if (fn.call(opt_this, obj[key], key, obj)) {\r\n return key;\r\n }\r\n }\r\n return undefined;\r\n};\r\nvar findValue = function (obj, fn, opt_this) {\r\n var key = findKey(obj, fn, opt_this);\r\n return key && obj[key];\r\n};\r\nvar getAnyKey = function (obj) {\r\n for (var key in obj) {\r\n return key;\r\n }\r\n};\r\nvar getValues = function (obj) {\r\n var res = [];\r\n var i = 0;\r\n for (var key in obj) {\r\n res[i++] = obj[key];\r\n }\r\n return res;\r\n};\r\n/**\r\n * Tests whether every key/value pair in an object pass the test implemented\r\n * by the provided function\r\n *\r\n * @param {?Object.} obj Object to test.\r\n * @param {!function(K, V)} fn Function to call for each key and value.\r\n * @template K,V\r\n */\r\nvar every = function (obj, fn) {\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n if (!fn(key, obj[key])) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params\r\n * object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n *\r\n * @param {!Object} querystringParams\r\n * @return {string}\r\n */\r\nvar querystring = function (querystringParams) {\r\n var params = [];\r\n forEach(querystringParams, function (key, value) {\r\n if (Array.isArray(value)) {\r\n value.forEach(function (arrayVal) {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n });\r\n return params.length ? '&' + params.join('&') : '';\r\n};\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'})\r\n *\r\n * @param {string} querystring\r\n * @return {!Object}\r\n */\r\nvar querystringDecode = function (querystring) {\r\n var obj = {};\r\n var tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(function (token) {\r\n if (token) {\r\n var key = token.split('=');\r\n obj[key[0]] = key[1];\r\n }\r\n });\r\n return obj;\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Copyright 2011 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n/**\r\n * @fileoverview Abstract cryptographic hash interface.\r\n *\r\n * See Sha1 and Md5 for sample implementations.\r\n *\r\n */\r\n/**\r\n * Create a cryptographic hash instance.\r\n *\r\n * @constructor\r\n * @struct\r\n */\r\nvar Hash = /** @class */ (function () {\r\n function Hash() {\r\n /**\r\n * The block size for the hasher.\r\n * @type {number}\r\n */\r\n this.blockSize = -1;\r\n }\r\n return Hash;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @extends {Hash}\r\n * @final\r\n * @struct\r\n */\r\nvar Sha1 = /** @class */ (function (_super) {\r\n __extends(Sha1, _super);\r\n function Sha1() {\r\n var _this = _super.call(this) || this;\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @type {!Array}\r\n * @private\r\n */\r\n _this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @type {!Array}\r\n * @private\r\n */\r\n _this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @type {!Array}\r\n * @private\r\n */\r\n _this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @type {!Array}\r\n * @private\r\n */\r\n _this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n _this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n _this.total_ = 0;\r\n _this.blockSize = 512 / 8;\r\n _this.pad_[0] = 128;\r\n for (var i = 1; i < _this.blockSize; ++i) {\r\n _this.pad_[i] = 0;\r\n }\r\n _this.reset();\r\n return _this;\r\n }\r\n Sha1.prototype.reset = function () {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n };\r\n /**\r\n * Internal compress helper function.\r\n * @param {!Array|!Uint8Array|string} buf Block to compress.\r\n * @param {number=} opt_offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n Sha1.prototype.compress_ = function (buf, opt_offset) {\r\n if (!opt_offset) {\r\n opt_offset = 0;\r\n }\r\n var W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (var i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(opt_offset) << 24) |\r\n (buf.charCodeAt(opt_offset + 1) << 16) |\r\n (buf.charCodeAt(opt_offset + 2) << 8) |\r\n buf.charCodeAt(opt_offset + 3);\r\n opt_offset += 4;\r\n }\r\n }\r\n else {\r\n for (var i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[opt_offset] << 24) |\r\n (buf[opt_offset + 1] << 16) |\r\n (buf[opt_offset + 2] << 8) |\r\n buf[opt_offset + 3];\r\n opt_offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (var i = 16; i < 80; i++) {\r\n var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n var a = this.chain_[0];\r\n var b = this.chain_[1];\r\n var c = this.chain_[2];\r\n var d = this.chain_[3];\r\n var e = this.chain_[4];\r\n var f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (var i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n };\r\n Sha1.prototype.update = function (bytes, opt_length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (opt_length === undefined) {\r\n opt_length = bytes.length;\r\n }\r\n var lengthMinusBlock = opt_length - this.blockSize;\r\n var n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n var buf = this.buf_;\r\n var inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < opt_length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf == 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < opt_length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf == this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < opt_length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf == this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += opt_length;\r\n };\r\n /** @override */\r\n Sha1.prototype.digest = function () {\r\n var digest = [];\r\n var totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (var i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n var n = 0;\r\n for (var i = 0; i < 5; i++) {\r\n for (var j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n };\r\n return Sha1;\r\n}(Hash));\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n var proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nvar ObserverProxy = /** @class */ (function () {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n function ObserverProxy(executor, onNoObservers) {\r\n var _this = this;\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(function () {\r\n executor(_this);\r\n })\r\n .catch(function (e) {\r\n _this.error(e);\r\n });\r\n }\r\n ObserverProxy.prototype.next = function (value) {\r\n this.forEachObserver(function (observer) {\r\n observer.next(value);\r\n });\r\n };\r\n ObserverProxy.prototype.error = function (error) {\r\n this.forEachObserver(function (observer) {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n };\r\n ObserverProxy.prototype.complete = function () {\r\n this.forEachObserver(function (observer) {\r\n observer.complete();\r\n });\r\n this.close();\r\n };\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) {\r\n var _this = this;\r\n var observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error: error,\r\n complete: complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n var unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n this.task.then(function () {\r\n try {\r\n if (_this.finalError) {\r\n observer.error(_this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n };\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n ObserverProxy.prototype.unsubscribeOne = function (i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n };\r\n ObserverProxy.prototype.forEachObserver = function (fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (var i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n };\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n ObserverProxy.prototype.sendOne = function (i, fn) {\r\n var _this = this;\r\n // Execute the callback asynchronously\r\n this.task.then(function () {\r\n if (_this.observers !== undefined && _this.observers[i] !== undefined) {\r\n try {\r\n fn(_this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n };\r\n ObserverProxy.prototype.close = function (err) {\r\n var _this = this;\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n this.task.then(function () {\r\n _this.observers = undefined;\r\n _this.onNoObservers = undefined;\r\n });\r\n };\r\n return ObserverProxy;\r\n}());\r\n/** Turn synchronous function into one called asynchronously. */\r\nfunction async(fn, onError) {\r\n return function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n Promise.resolve(true)\r\n .then(function () {\r\n fn.apply(void 0, args);\r\n })\r\n .catch(function (error) {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\r\n var method = methods_1[_i];\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param {!string} fnName The function name\r\n * @param {!number} minCount The minimum number of arguments to allow for the function call\r\n * @param {!number} maxCount The maximum number of argument to allow for the function call\r\n * @param {!number} argCount The actual number of arguments provided.\r\n */\r\nvar validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n var argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n var error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param {!string} fnName The function name\r\n * @param {!number} argumentNumber The index of the argument\r\n * @param {boolean} optional Whether or not the argument is optional\r\n * @return {!string} The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argumentNumber, optional) {\r\n var argName = '';\r\n switch (argumentNumber) {\r\n case 1:\r\n argName = optional ? 'first' : 'First';\r\n break;\r\n case 2:\r\n argName = optional ? 'second' : 'Second';\r\n break;\r\n case 3:\r\n argName = optional ? 'third' : 'Third';\r\n break;\r\n case 4:\r\n argName = optional ? 'fourth' : 'Fourth';\r\n break;\r\n default:\r\n throw new Error('errorPrefix called with argumentNumber > 4. Need to update it?');\r\n }\r\n var error = fnName + ' failed: ';\r\n error += argName + ' argument ';\r\n return error;\r\n}\r\n/**\r\n * @param {!string} fnName\r\n * @param {!number} argumentNumber\r\n * @param {!string} namespace\r\n * @param {boolean} optional\r\n */\r\nfunction validateNamespace(fnName, argumentNumber, namespace, optional) {\r\n if (optional && !namespace)\r\n return;\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, argumentNumber, optional) +\r\n 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentNumber, callback, optional) {\r\n if (optional && !callback)\r\n return;\r\n if (typeof callback !== 'function')\r\n throw new Error(errorPrefix(fnName, argumentNumber, optional) +\r\n 'must be a valid function.');\r\n}\r\nfunction validateContextObject(fnName, argumentNumber, context, optional) {\r\n if (optional && !context)\r\n return;\r\n if (typeof context !== 'object' || context === null)\r\n throw new Error(errorPrefix(fnName, argumentNumber, optional) +\r\n 'must be a valid context object.');\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nvar stringToByteArray$1 = function (str) {\r\n var out = [], p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n var high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nvar stringLength = function (str) {\r\n var p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nexport { assert, assertionError, base64, base64Decode, base64Encode, CONSTANTS, deepCopy, deepExtend, patchProperty, Deferred, getUA, isMobileCordova, isNodeSdk, isReactNative, ErrorFactory, FirebaseError, patchCapture, jsonEval, stringify, decode, isAdmin, issuedAtTime, isValidFormat, isValidTimestamp, clone, contains, every, extend, findKey, findValue, forEach, getAnyKey, getCount, getValues, isEmpty, isNonNullObject, map, safeGet, querystring, querystringDecode, Sha1, async, createSubscribe, errorPrefix, validateArgCount, validateCallback, validateContextObject, validateNamespace, stringLength, stringToByteArray$1 as stringToByteArray };\n","import { ErrorFactory, createSubscribe } from '@firebase/util';\nimport { __extends, __awaiter, __generator, __assign } from 'tslib';\nimport firebase from '@firebase/app';\n\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar ERROR_CODES = {\r\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\r\n AVAILABLE_IN_SW: 'only-available-in-sw',\r\n SHOULD_BE_INHERITED: 'should-be-overriden',\r\n BAD_SENDER_ID: 'bad-sender-id',\r\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\r\n PERMISSION_DEFAULT: 'permission-default',\r\n PERMISSION_BLOCKED: 'permission-blocked',\r\n UNSUPPORTED_BROWSER: 'unsupported-browser',\r\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\r\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\r\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\r\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\r\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\r\n SW_REG_REDUNDANT: 'sw-reg-redundant',\r\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\r\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\r\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\r\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\r\n TOKEN_UPDATE_FAILED: 'token-update-failed',\r\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\r\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\r\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\r\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\r\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\r\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\r\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\r\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\r\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\r\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\r\n NO_SW_IN_REG: 'no-sw-in-reg',\r\n BAD_SCOPE: 'bad-scope',\r\n BAD_VAPID_KEY: 'bad-vapid-key',\r\n BAD_SUBSCRIPTION: 'bad-subscription',\r\n BAD_TOKEN: 'bad-token',\r\n BAD_PUSH_SET: 'bad-push-set',\r\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\r\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\r\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\r\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\r\n};\r\nvar ERROR_MAP = (_a = {}, _a[ERROR_CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.', _a[ERROR_CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.', _a[ERROR_CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.', _a[ERROR_CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\r\n 'correctly in the options passed into firebase.initializeApp().', _a[ERROR_CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.', _a[ERROR_CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.', _a[ERROR_CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\r\n 'required to use the firebase SDK.', _a[ERROR_CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.', _a[ERROR_CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\r\n 'default service worker. {$browserErrorMessage}', _a[ERROR_CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.', _a[ERROR_CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\r\n 'any existing Push Subscriptions.', _a[ERROR_CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.', _a[ERROR_CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.', _a[ERROR_CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}', _a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.', _a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.', _a[ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}', _a[ERROR_CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}', _a[ERROR_CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.', _a[ERROR_CODES.USE_SW_BEFORE_GET_TOKEN] = 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.', _a[ERROR_CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\r\n 'deleteToken(), i.e. the token from getToken().', _a[ERROR_CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\r\n 'be performed as the token was not found.', _a[ERROR_CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\r\n 'scope could not be performed as the scope was not found.', _a[ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.', _a[ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.', _a[ERROR_CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\r\n 'the FCM token for push messaging. Will have to resubscribe the ' +\r\n 'user on next visit. {$message}', _a[ERROR_CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\r\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\r\n 'user on next visit.', _a[ERROR_CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.', _a[ERROR_CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\r\n 'successful, there was a problem accessing the service worker itself.', _a[ERROR_CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\r\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\", _a[ERROR_CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\r\n 'least one character.', _a[ERROR_CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.', _a[ERROR_CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.', _a[ERROR_CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\r\n 'a valid token string.', _a[ERROR_CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\r\n 'not a valid push set string.', _a[ERROR_CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.', _a[ERROR_CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.', _a[ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.', _a);\r\nvar errorFactory = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\r\nvar _a;\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\r\n 0x04,\r\n 0x33,\r\n 0x94,\r\n 0xf7,\r\n 0xdf,\r\n 0xa1,\r\n 0xeb,\r\n 0xb1,\r\n 0xdc,\r\n 0x03,\r\n 0xa2,\r\n 0x5e,\r\n 0x15,\r\n 0x71,\r\n 0xdb,\r\n 0x48,\r\n 0xd3,\r\n 0x2e,\r\n 0xed,\r\n 0xed,\r\n 0xb2,\r\n 0x34,\r\n 0xdb,\r\n 0xb7,\r\n 0x47,\r\n 0x3a,\r\n 0x0c,\r\n 0x8f,\r\n 0xc4,\r\n 0xcc,\r\n 0xe1,\r\n 0x6f,\r\n 0x3c,\r\n 0x8c,\r\n 0x84,\r\n 0xdf,\r\n 0xab,\r\n 0xb6,\r\n 0x66,\r\n 0x3e,\r\n 0xf2,\r\n 0x0c,\r\n 0xd4,\r\n 0x8b,\r\n 0xfe,\r\n 0xe3,\r\n 0xf9,\r\n 0x76,\r\n 0x2f,\r\n 0x14,\r\n 0x1c,\r\n 0x63,\r\n 0x08,\r\n 0x6a,\r\n 0x6f,\r\n 0x2d,\r\n 0xb1,\r\n 0x1a,\r\n 0x95,\r\n 0xb0,\r\n 0xce,\r\n 0x37,\r\n 0xc0,\r\n 0x9c,\r\n 0x6e\r\n]);\r\nvar ENDPOINT = 'https://fcm.googleapis.com';\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MessageParameter;\r\n(function (MessageParameter) {\r\n MessageParameter[\"TYPE_OF_MSG\"] = \"firebase-messaging-msg-type\";\r\n MessageParameter[\"DATA\"] = \"firebase-messaging-msg-data\";\r\n})(MessageParameter || (MessageParameter = {}));\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_MSG_RECEIVED\"] = \"push-msg-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isArrayBufferEqual(a, b) {\r\n if (a == null || b == null) {\r\n return false;\r\n }\r\n if (a === b) {\r\n return true;\r\n }\r\n if (a.byteLength !== b.byteLength) {\r\n return false;\r\n }\r\n var viewA = new DataView(a);\r\n var viewB = new DataView(b);\r\n for (var i = 0; i < a.byteLength; i++) {\r\n if (viewA.getUint8(i) !== viewB.getUint8(i)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction toBase64(arrayBuffer) {\r\n var uint8Version = new Uint8Array(arrayBuffer);\r\n return btoa(String.fromCharCode.apply(null, uint8Version));\r\n}\r\nfunction arrayBufferToBase64(arrayBuffer) {\r\n var base64String = toBase64(arrayBuffer);\r\n return base64String\r\n .replace(/=/g, '')\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_');\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar IIDModel = /** @class */ (function () {\r\n function IIDModel() {\r\n }\r\n IIDModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var p256dh, auth, fcmSubscribeBody, applicationPubKey, headers, subscribeOptions, responseData, response, err_1, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\r\n auth = arrayBufferToBase64(subscription.getKey('auth'));\r\n fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\r\n (\"endpoint=\" + subscription.endpoint + \"&\") +\r\n (\"encryption_key=\" + p256dh + \"&\") +\r\n (\"encryption_auth=\" + auth);\r\n if (publicVapidKey !== DEFAULT_PUBLIC_VAPID_KEY) {\r\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\r\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\r\n }\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n subscribeOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmSubscribeBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_1 = _a.sent();\r\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED);\r\n case 5:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED, {\r\n message: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN);\r\n }\r\n if (!responseData.pushSet) {\r\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET);\r\n }\r\n return [2 /*return*/, {\r\n token: responseData.token,\r\n pushSet: responseData.pushSet\r\n }];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Update the underlying token details for fcmToken.\r\n */\r\n IIDModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var p256dh, auth, fcmUpdateBody, applicationPubKey, headers, updateOptions, responseData, response, err_2, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\r\n auth = arrayBufferToBase64(subscription.getKey('auth'));\r\n fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\r\n (\"token=\" + fcmToken + \"&\") +\r\n (\"authorized_entity=\" + senderId + \"&\") +\r\n (\"endpoint=\" + subscription.endpoint + \"&\") +\r\n (\"encryption_key=\" + p256dh + \"&\") +\r\n (\"encryption_auth=\" + auth);\r\n if (publicVapidKey !== DEFAULT_PUBLIC_VAPID_KEY) {\r\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\r\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\r\n }\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n updateOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmUpdateBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/subscribe', updateOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_2 = _a.sent();\r\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED);\r\n case 5:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED, {\r\n message: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_NO_TOKEN);\r\n }\r\n return [2 /*return*/, responseData.token];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\r\n */\r\n IIDModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var fcmUnsubscribeBody, headers, unsubscribeOptions, response, responseData, message, err_3;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\r\n (\"token=\" + fcmToken + \"&\") +\r\n (\"pushSet=\" + fcmPushSet);\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n unsubscribeOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmUnsubscribeBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED, {\r\n message: message\r\n });\r\n }\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_3 = _a.sent();\r\n throw errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED);\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n return IIDModel;\r\n}());\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction base64ToArrayBuffer(base64String) {\r\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\r\n var base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n var rawData = atob(base64);\r\n var outputArray = new Uint8Array(rawData.length);\r\n for (var i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar OLD_DB_NAME = 'undefined';\r\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nfunction handleDb(db) {\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // We found a database with the name 'undefined', but our expected object\r\n // store isn't defined.\r\n return;\r\n }\r\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\r\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n var iidModel = new IIDModel();\r\n var openCursorRequest = objectStore.openCursor();\r\n openCursorRequest.onerror = function (event) {\r\n // NOOP - Nothing we can do.\r\n console.warn('Unable to cleanup old IDB.', event);\r\n };\r\n openCursorRequest.onsuccess = function () {\r\n var cursor = openCursorRequest.result;\r\n if (cursor) {\r\n // cursor.value contains the current record being iterated through\r\n // this is where you'd do something with the result\r\n var tokenDetails = cursor.value;\r\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\r\n cursor.continue();\r\n }\r\n else {\r\n db.close();\r\n indexedDB.deleteDatabase(OLD_DB_NAME);\r\n }\r\n };\r\n}\r\nfunction cleanV1() {\r\n var request = indexedDB.open(OLD_DB_NAME);\r\n request.onerror = function (event) {\r\n // NOOP - Nothing we can do.\r\n };\r\n request.onsuccess = function (event) {\r\n var db = request.result;\r\n handleDb(db);\r\n };\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DBInterface = /** @class */ (function () {\r\n function DBInterface() {\r\n this.dbPromise = null;\r\n }\r\n /** Gets record(s) from the objectStore that match the given key. */\r\n DBInterface.prototype.get = function (key) {\r\n return this.createTransaction(function (objectStore) { return objectStore.get(key); });\r\n };\r\n /** Gets record(s) from the objectStore that match the given index. */\r\n DBInterface.prototype.getIndex = function (index, key) {\r\n function runRequest(objectStore) {\r\n var idbIndex = objectStore.index(index);\r\n return idbIndex.get(key);\r\n }\r\n return this.createTransaction(runRequest);\r\n };\r\n /** Assigns or overwrites the record for the given value. */\r\n // tslint:disable-next-line:no-any IndexedDB values are of type \"any\"\r\n DBInterface.prototype.put = function (value) {\r\n return this.createTransaction(function (objectStore) { return objectStore.put(value); }, 'readwrite');\r\n };\r\n /** Deletes record(s) from the objectStore that match the given key. */\r\n DBInterface.prototype.delete = function (key) {\r\n return this.createTransaction(function (objectStore) { return objectStore.delete(key); }, 'readwrite');\r\n };\r\n /**\r\n * Close the currently open database.\r\n */\r\n DBInterface.prototype.closeDatabase = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var db;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.dbPromise) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.dbPromise];\r\n case 1:\r\n db = _a.sent();\r\n db.close();\r\n this.dbPromise = null;\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Creates an IndexedDB Transaction and passes its objectStore to the\r\n * runRequest function, which runs the database request.\r\n *\r\n * @return Promise that resolves with the result of the runRequest function\r\n */\r\n DBInterface.prototype.createTransaction = function (runRequest, mode) {\r\n if (mode === void 0) { mode = 'readonly'; }\r\n return __awaiter(this, void 0, void 0, function () {\r\n var db, transaction, request, result;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getDb()];\r\n case 1:\r\n db = _a.sent();\r\n transaction = db.transaction(this.objectStoreName, mode);\r\n request = transaction.objectStore(this.objectStoreName);\r\n return [4 /*yield*/, promisify(runRequest(request))];\r\n case 2:\r\n result = _a.sent();\r\n return [2 /*return*/, new Promise(function (resolve, reject) {\r\n transaction.oncomplete = function () {\r\n resolve(result);\r\n };\r\n transaction.onerror = function () {\r\n reject(transaction.error);\r\n };\r\n })];\r\n }\r\n });\r\n });\r\n };\r\n /** Gets the cached db connection or opens a new one. */\r\n DBInterface.prototype.getDb = function () {\r\n var _this = this;\r\n if (!this.dbPromise) {\r\n this.dbPromise = new Promise(function (resolve, reject) {\r\n var request = indexedDB.open(_this.dbName, _this.dbVersion);\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n _this.dbPromise = null;\r\n reject(request.error);\r\n };\r\n request.onupgradeneeded = function (event) { return _this.onDbUpgrade(request, event); };\r\n });\r\n }\r\n return this.dbPromise;\r\n };\r\n return DBInterface;\r\n}());\r\n/** Promisifies an IDBRequest. Resolves with the IDBRequest's result. */\r\nfunction promisify(request) {\r\n return new Promise(function (resolve, reject) {\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n reject(request.error);\r\n };\r\n });\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar TokenDetailsModel = /** @class */ (function (_super) {\r\n __extends(TokenDetailsModel, _super);\r\n function TokenDetailsModel() {\r\n var _this = _super !== null && _super.apply(this, arguments) || this;\r\n _this.dbName = 'fcm_token_details_db';\r\n _this.dbVersion = 3;\r\n _this.objectStoreName = 'fcm_token_object_Store';\r\n return _this;\r\n }\r\n TokenDetailsModel.prototype.onDbUpgrade = function (request, event) {\r\n var db = request.result;\r\n // Lack of 'break' statements is intentional.\r\n switch (event.oldVersion) {\r\n case 0: {\r\n // New IDB instance\r\n var objectStore = db.createObjectStore(this.objectStoreName, {\r\n keyPath: 'swScope'\r\n });\r\n // Make sure the sender ID can be searched\r\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\r\n unique: false\r\n });\r\n objectStore.createIndex('fcmToken', 'fcmToken', { unique: true });\r\n }\r\n case 1: {\r\n // Prior to version 2, we were using either 'fcm_token_details_db'\r\n // or 'undefined' as the database name due to bug in the SDK\r\n // So remove the old tokens and databases.\r\n cleanV1();\r\n }\r\n case 2: {\r\n var objectStore = request.transaction.objectStore(this.objectStoreName);\r\n var cursorRequest_1 = objectStore.openCursor();\r\n cursorRequest_1.onsuccess = function () {\r\n var cursor = cursorRequest_1.result;\r\n if (cursor) {\r\n var value = cursor.value;\r\n var newValue = __assign({}, value);\r\n if (!value.createTime) {\r\n newValue.createTime = Date.now();\r\n }\r\n if (typeof value.vapidKey === 'string') {\r\n newValue.vapidKey = base64ToArrayBuffer(value.vapidKey);\r\n }\r\n if (typeof value.auth === 'string') {\r\n newValue.auth = base64ToArrayBuffer(value.auth).buffer;\r\n }\r\n if (typeof value.auth === 'string') {\r\n newValue.p256dh = base64ToArrayBuffer(value.p256dh).buffer;\r\n }\r\n cursor.update(newValue);\r\n cursor.continue();\r\n }\r\n };\r\n }\r\n }\r\n };\r\n /**\r\n * Given a token, this method will look up the details in indexedDB.\r\n */\r\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!fcmToken) {\r\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\r\n }\r\n validateInputs({ fcmToken: fcmToken });\r\n return [2 /*return*/, this.getIndex('fcmToken', fcmToken)];\r\n });\r\n });\r\n };\r\n /**\r\n * Given a service worker scope, this method will look up the details in\r\n * indexedDB.\r\n * @return The details associated with that token.\r\n */\r\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!swScope) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\r\n }\r\n validateInputs({ swScope: swScope });\r\n return [2 /*return*/, this.get(swScope)];\r\n });\r\n });\r\n };\r\n /**\r\n * Save the details for the fcm token for re-use at a later date.\r\n * @param input A plain js object containing args to save.\r\n */\r\n TokenDetailsModel.prototype.saveTokenDetails = function (tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!tokenDetails.swScope) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\r\n }\r\n if (!tokenDetails.vapidKey) {\r\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\r\n }\r\n if (!tokenDetails.endpoint || !tokenDetails.auth || !tokenDetails.p256dh) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\r\n }\r\n if (!tokenDetails.fcmSenderId) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\r\n }\r\n if (!tokenDetails.fcmToken) {\r\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\r\n }\r\n if (!tokenDetails.fcmPushSet) {\r\n throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET);\r\n }\r\n validateInputs(tokenDetails);\r\n return [2 /*return*/, this.put(tokenDetails)];\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes details of the current FCM token.\r\n * It's returning a promise in case we need to move to an async\r\n * method for deleting at a later date.\r\n *\r\n * @return Resolves once the FCM token details have been deleted and returns\r\n * the deleted details.\r\n */\r\n TokenDetailsModel.prototype.deleteToken = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (typeof token !== 'string' || token.length === 0) {\r\n return [2 /*return*/, Promise.reject(errorFactory.create(ERROR_CODES.INVALID_DELETE_TOKEN))];\r\n }\r\n return [4 /*yield*/, this.getTokenDetailsFromToken(token)];\r\n case 1:\r\n details = _a.sent();\r\n if (!details) {\r\n throw errorFactory.create(ERROR_CODES.DELETE_TOKEN_NOT_FOUND);\r\n }\r\n return [4 /*yield*/, this.delete(details.swScope)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, details];\r\n }\r\n });\r\n });\r\n };\r\n return TokenDetailsModel;\r\n}(DBInterface));\r\n/**\r\n * This method takes an object and will check for known arguments and\r\n * validate the input.\r\n * @return Promise that resolves if input is valid, rejects otherwise.\r\n */\r\nfunction validateInputs(input) {\r\n if (input.fcmToken) {\r\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\r\n }\r\n }\r\n if (input.swScope) {\r\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\r\n }\r\n }\r\n if (input.vapidKey) {\r\n if (!(input.vapidKey instanceof Uint8Array) ||\r\n input.vapidKey.length !== 65) {\r\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\r\n }\r\n }\r\n if (input.endpoint) {\r\n if (typeof input.endpoint !== 'string' || input.endpoint.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\r\n }\r\n }\r\n if (input.auth) {\r\n if (!(input.auth instanceof ArrayBuffer)) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\r\n }\r\n }\r\n if (input.p256dh) {\r\n if (!(input.p256dh instanceof ArrayBuffer)) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\r\n }\r\n }\r\n if (input.fcmSenderId) {\r\n if (typeof input.fcmSenderId !== 'string' ||\r\n input.fcmSenderId.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\r\n }\r\n }\r\n if (input.fcmPushSet) {\r\n if (typeof input.fcmPushSet !== 'string' || input.fcmPushSet.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET);\r\n }\r\n }\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\r\nvar VapidDetailsModel = /** @class */ (function (_super) {\r\n __extends(VapidDetailsModel, _super);\r\n function VapidDetailsModel() {\r\n var _this = _super !== null && _super.apply(this, arguments) || this;\r\n _this.dbName = 'fcm_vapid_details_db';\r\n _this.dbVersion = 1;\r\n _this.objectStoreName = 'fcm_vapid_object_Store';\r\n return _this;\r\n }\r\n VapidDetailsModel.prototype.onDbUpgrade = function (request) {\r\n var db = request.result;\r\n db.createObjectStore(this.objectStoreName, { keyPath: 'swScope' });\r\n };\r\n /**\r\n * Given a service worker scope, this method will look up the vapid key\r\n * in indexedDB.\r\n */\r\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var result;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (typeof swScope !== 'string' || swScope.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\r\n }\r\n return [4 /*yield*/, this.get(swScope)];\r\n case 1:\r\n result = _a.sent();\r\n return [2 /*return*/, result ? result.vapidKey : undefined];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Save a vapid key against a swScope for later date.\r\n */\r\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n if (typeof swScope !== 'string' || swScope.length === 0) {\r\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\r\n }\r\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\r\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\r\n }\r\n details = {\r\n swScope: swScope,\r\n vapidKey: vapidKey\r\n };\r\n return [2 /*return*/, this.put(details)];\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes details of the current FCM VAPID key for a SW scope.\r\n * Resolves once the scope/vapid details have been deleted and returns the\r\n * deleted vapid key.\r\n */\r\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var vapidKey;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getVapidFromSWScope(swScope)];\r\n case 1:\r\n vapidKey = _a.sent();\r\n if (!vapidKey) {\r\n throw errorFactory.create(ERROR_CODES.DELETE_SCOPE_NOT_FOUND);\r\n }\r\n return [4 /*yield*/, this.delete(swScope)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, vapidKey];\r\n }\r\n });\r\n });\r\n };\r\n return VapidDetailsModel;\r\n}(DBInterface));\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\r\n// Database cache should be invalidated once a week.\r\nvar TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nvar ControllerInterface = /** @class */ (function () {\r\n /**\r\n * An interface of the Messaging Service API\r\n */\r\n function ControllerInterface(app) {\r\n var _this = this;\r\n if (!app.options[SENDER_ID_OPTION_NAME] ||\r\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\r\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\r\n }\r\n this.messagingSenderId = app.options[SENDER_ID_OPTION_NAME];\r\n this.tokenDetailsModel = new TokenDetailsModel();\r\n this.vapidDetailsModel = new VapidDetailsModel();\r\n this.iidModel = new IIDModel();\r\n this.app = app;\r\n this.INTERNAL = {\r\n delete: function () { return _this.delete(); }\r\n };\r\n }\r\n /**\r\n * @export\r\n */\r\n ControllerInterface.prototype.getToken = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var currentPermission, swReg, publicVapidKey, pushSubscription, tokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n currentPermission = this.getNotificationPermission_();\r\n if (currentPermission !== 'granted') {\r\n if (currentPermission === 'denied') {\r\n return [2 /*return*/, Promise.reject(errorFactory.create(ERROR_CODES.NOTIFICATIONS_BLOCKED))];\r\n }\r\n // We must wait for permission to be granted\r\n return [2 /*return*/, Promise.resolve(null)];\r\n }\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n swReg = _a.sent();\r\n return [4 /*yield*/, this.getPublicVapidKey_()];\r\n case 2:\r\n publicVapidKey = _a.sent();\r\n return [4 /*yield*/, this.getPushSubscription(swReg, publicVapidKey)];\r\n case 3:\r\n pushSubscription = _a.sent();\r\n return [4 /*yield*/, this.tokenDetailsModel.getTokenDetailsFromSWScope(swReg.scope)];\r\n case 4:\r\n tokenDetails = _a.sent();\r\n if (tokenDetails) {\r\n return [2 /*return*/, this.manageExistingToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\r\n }\r\n return [2 /*return*/, this.getNewToken(swReg, pushSubscription, publicVapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * manageExistingToken is triggered if there's an existing FCM token in the\r\n * database and it can take 3 different actions:\r\n * 1) Retrieve the existing FCM token from the database.\r\n * 2) If VAPID details have changed: Delete the existing token and create a\r\n * new one with the new VAPID key.\r\n * 3) If the database cache is invalidated: Send a request to FCM to update\r\n * the token, and to check if the token is still valid on FCM-side.\r\n */\r\n ControllerInterface.prototype.manageExistingToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var isTokenValid, now;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n isTokenValid = isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails);\r\n if (isTokenValid) {\r\n now = Date.now();\r\n if (now < tokenDetails.createTime + TOKEN_EXPIRATION_MILLIS) {\r\n return [2 /*return*/, tokenDetails.fcmToken];\r\n }\r\n else {\r\n return [2 /*return*/, this.updateToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\r\n }\r\n }\r\n // If the token is no longer valid (for example if the VAPID details\r\n // have changed), delete the existing token from the FCM client and server\r\n // database. No need to unsubscribe from the Service Worker as we have a\r\n // good push subscription that we'd like to use in getNewToken.\r\n return [4 /*yield*/, this.deleteTokenFromDB(tokenDetails.fcmToken)];\r\n case 1:\r\n // If the token is no longer valid (for example if the VAPID details\r\n // have changed), delete the existing token from the FCM client and server\r\n // database. No need to unsubscribe from the Service Worker as we have a\r\n // good push subscription that we'd like to use in getNewToken.\r\n _a.sent();\r\n return [2 /*return*/, this.getNewToken(swReg, pushSubscription, publicVapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n ControllerInterface.prototype.updateToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var updatedToken, allDetails, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 4, , 6]);\r\n return [4 /*yield*/, this.iidModel.updateToken(this.messagingSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet, pushSubscription, publicVapidKey)];\r\n case 1:\r\n updatedToken = _a.sent();\r\n allDetails = {\r\n swScope: swReg.scope,\r\n vapidKey: publicVapidKey,\r\n fcmSenderId: this.messagingSenderId,\r\n fcmToken: updatedToken,\r\n fcmPushSet: tokenDetails.fcmPushSet,\r\n createTime: Date.now(),\r\n endpoint: pushSubscription.endpoint,\r\n auth: pushSubscription.getKey('auth'),\r\n p256dh: pushSubscription.getKey('p256dh')\r\n };\r\n return [4 /*yield*/, this.tokenDetailsModel.saveTokenDetails(allDetails)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, updatedToken];\r\n case 4:\r\n e_1 = _a.sent();\r\n return [4 /*yield*/, this.deleteToken(tokenDetails.fcmToken)];\r\n case 5:\r\n _a.sent();\r\n throw e_1;\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n ControllerInterface.prototype.getNewToken = function (swReg, pushSubscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenDetails, allDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.iidModel.getToken(this.messagingSenderId, pushSubscription, publicVapidKey)];\r\n case 1:\r\n tokenDetails = _a.sent();\r\n allDetails = {\r\n swScope: swReg.scope,\r\n vapidKey: publicVapidKey,\r\n fcmSenderId: this.messagingSenderId,\r\n fcmToken: tokenDetails.token,\r\n fcmPushSet: tokenDetails.pushSet,\r\n createTime: Date.now(),\r\n endpoint: pushSubscription.endpoint,\r\n auth: pushSubscription.getKey('auth'),\r\n p256dh: pushSubscription.getKey('p256dh')\r\n };\r\n return [4 /*yield*/, this.tokenDetailsModel.saveTokenDetails(allDetails)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, tokenDetails.token];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes tokens that the token manager looks after,\r\n * unsubscribes the token from FCM and then unregisters the push\r\n * subscription if it exists. It returns a promise that indicates\r\n * whether or not the unsubscribe request was processed successfully.\r\n * @export\r\n */\r\n ControllerInterface.prototype.deleteToken = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registration, pushSubscription;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: \r\n // Delete the token details from the database.\r\n return [4 /*yield*/, this.deleteTokenFromDB(token)];\r\n case 1:\r\n // Delete the token details from the database.\r\n _a.sent();\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 2:\r\n registration = _a.sent();\r\n if (!registration) return [3 /*break*/, 4];\r\n return [4 /*yield*/, registration.pushManager.getSubscription()];\r\n case 3:\r\n pushSubscription = _a.sent();\r\n if (pushSubscription) {\r\n return [2 /*return*/, pushSubscription.unsubscribe()];\r\n }\r\n _a.label = 4;\r\n case 4: \r\n // If there's no SW, consider it a success.\r\n return [2 /*return*/, true];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This method will delete the token from the client database, and make a\r\n * call to FCM to remove it from the server DB. Does not temper with the\r\n * push subscription.\r\n */\r\n ControllerInterface.prototype.deleteTokenFromDB = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.tokenDetailsModel.deleteToken(token)];\r\n case 1:\r\n details = _a.sent();\r\n return [4 /*yield*/, this.iidModel.deleteToken(details.fcmSenderId, details.fcmToken, details.fcmPushSet)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Gets a PushSubscription for the current user.\r\n */\r\n ControllerInterface.prototype.getPushSubscription = function (swRegistration, publicVapidKey) {\r\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n applicationServerKey: publicVapidKey\r\n });\r\n });\r\n };\r\n //\r\n // The following methods should only be available in the window.\r\n //\r\n ControllerInterface.prototype.requestPermission = function () {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\r\n };\r\n ControllerInterface.prototype.useServiceWorker = function (registration) {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\r\n };\r\n ControllerInterface.prototype.usePublicVapidKey = function (b64PublicKey) {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\r\n };\r\n ControllerInterface.prototype.onMessage = function (nextOrObserver, error, completed) {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\r\n };\r\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\r\n };\r\n //\r\n // The following methods are used by the service worker only.\r\n //\r\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\r\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_SW);\r\n };\r\n //\r\n // The following methods are used by the service themselves and not exposed\r\n // publicly or not expected to be used by developers.\r\n //\r\n /**\r\n * This method is required to adhere to the Firebase interface.\r\n * It closes any currently open indexdb database connections.\r\n */\r\n ControllerInterface.prototype.delete = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, Promise.all([\r\n this.tokenDetailsModel.closeDatabase(),\r\n this.vapidDetailsModel.closeDatabase()\r\n ])];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Returns the current Notification Permission state.\r\n */\r\n ControllerInterface.prototype.getNotificationPermission_ = function () {\r\n // TODO: Remove the cast when this issue is fixed:\r\n // https://github.com/Microsoft/TypeScript/issues/14701\r\n // tslint:disable-next-line no-any\r\n return Notification.permission;\r\n };\r\n ControllerInterface.prototype.getTokenDetailsModel = function () {\r\n return this.tokenDetailsModel;\r\n };\r\n ControllerInterface.prototype.getVapidDetailsModel = function () {\r\n return this.vapidDetailsModel;\r\n };\r\n // Visible for testing\r\n // TODO: make protected\r\n ControllerInterface.prototype.getIIDModel = function () {\r\n return this.iidModel;\r\n };\r\n return ControllerInterface;\r\n}());\r\n/**\r\n * Checks if the tokenDetails match the details provided in the clients.\r\n */\r\nfunction isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails) {\r\n if (!isArrayBufferEqual(publicVapidKey.buffer, tokenDetails.vapidKey.buffer)) {\r\n return false;\r\n }\r\n var isEndpointEqual = pushSubscription.endpoint === tokenDetails.endpoint;\r\n var isAuthEqual = isArrayBufferEqual(pushSubscription.getKey('auth'), tokenDetails.auth);\r\n var isP256dhEqual = isArrayBufferEqual(pushSubscription.getKey('p256dh'), tokenDetails.p256dh);\r\n return isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar FCM_MSG = 'FCM_MSG';\r\nvar SWController = /** @class */ (function (_super) {\r\n __extends(SWController, _super);\r\n function SWController(app) {\r\n var _this = _super.call(this, app) || this;\r\n _this.bgMessageHandler = null;\r\n self.addEventListener('push', function (e) {\r\n _this.onPush(e);\r\n });\r\n self.addEventListener('pushsubscriptionchange', function (e) {\r\n _this.onSubChange(e);\r\n });\r\n self.addEventListener('notificationclick', function (e) {\r\n _this.onNotificationClick(e);\r\n });\r\n return _this;\r\n }\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.onPush = function (event) {\r\n event.waitUntil(this.onPush_(event));\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.onSubChange = function (event) {\r\n event.waitUntil(this.onSubChange_(event));\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.onNotificationClick = function (event) {\r\n event.waitUntil(this.onNotificationClick_(event));\r\n };\r\n /**\r\n * A handler for push events that shows notifications based on the content of\r\n * the payload.\r\n *\r\n * The payload must be a JSON-encoded Object with a `notification` key. The\r\n * value of the `notification` property will be used as the NotificationOptions\r\n * object passed to showNotification. Additionally, the `title` property of the\r\n * notification object will be used as the title.\r\n *\r\n * If there is no notification data in the payload then no notification will be\r\n * shown.\r\n */\r\n SWController.prototype.onPush_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var msgPayload, hasVisibleClients, notificationDetails, notificationTitle, reg, actions, maxActions;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!event.data) {\r\n return [2 /*return*/];\r\n }\r\n try {\r\n msgPayload = event.data.json();\r\n }\r\n catch (err) {\r\n // Not JSON so not an FCM message\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, this.hasVisibleClients_()];\r\n case 1:\r\n hasVisibleClients = _a.sent();\r\n if (hasVisibleClients) {\r\n // App in foreground. Send to page.\r\n return [2 /*return*/, this.sendMessageToWindowClients_(msgPayload)];\r\n }\r\n notificationDetails = this.getNotificationData_(msgPayload);\r\n if (!notificationDetails) return [3 /*break*/, 3];\r\n notificationTitle = notificationDetails.title || '';\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 2:\r\n reg = _a.sent();\r\n actions = notificationDetails.actions;\r\n maxActions = Notification.maxActions;\r\n // tslint:enable no-any\r\n if (actions && maxActions && actions.length > maxActions) {\r\n console.warn(\"This browser only supports \" + maxActions + \" actions.\" +\r\n \"The remaining actions will not be displayed.\");\r\n }\r\n return [2 /*return*/, reg.showNotification(notificationTitle, notificationDetails)];\r\n case 3:\r\n if (!this.bgMessageHandler) return [3 /*break*/, 5];\r\n return [4 /*yield*/, this.bgMessageHandler(msgPayload)];\r\n case 4:\r\n _a.sent();\r\n return [2 /*return*/];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SWController.prototype.onSubChange_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registration, err_1, err_2, tokenDetailsModel, tokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 2, , 3]);\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n registration = _a.sent();\r\n return [3 /*break*/, 3];\r\n case 2:\r\n err_1 = _a.sent();\r\n throw errorFactory.create(ERROR_CODES.UNABLE_TO_RESUBSCRIBE, {\r\n message: err_1\r\n });\r\n case 3:\r\n _a.trys.push([3, 5, , 8]);\r\n return [4 /*yield*/, registration.pushManager.getSubscription()];\r\n case 4:\r\n _a.sent();\r\n return [3 /*break*/, 8];\r\n case 5:\r\n err_2 = _a.sent();\r\n tokenDetailsModel = this.getTokenDetailsModel();\r\n return [4 /*yield*/, tokenDetailsModel.getTokenDetailsFromSWScope(registration.scope)];\r\n case 6:\r\n tokenDetails = _a.sent();\r\n if (!tokenDetails) {\r\n // This should rarely occure, but could if indexedDB\r\n // is corrupted or wiped\r\n throw err_2;\r\n }\r\n // Attempt to delete the token if we know it's bad\r\n return [4 /*yield*/, this.deleteToken(tokenDetails.fcmToken)];\r\n case 7:\r\n // Attempt to delete the token if we know it's bad\r\n _a.sent();\r\n throw err_2;\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SWController.prototype.onNotificationClick_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var msgPayload, clickAction, windowClient, internalMsg;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!event.notification ||\r\n !event.notification.data ||\r\n !event.notification.data[FCM_MSG]) {\r\n // Not an FCM notification, do nothing.\r\n return [2 /*return*/];\r\n }\r\n else if (event.action) {\r\n // User clicked on an action button.\r\n // This will allow devs to act on action button clicks by using a custom\r\n // onNotificationClick listener that they define.\r\n return [2 /*return*/];\r\n }\r\n // Prevent other listeners from receiving the event\r\n event.stopImmediatePropagation();\r\n event.notification.close();\r\n msgPayload = event.notification.data[FCM_MSG];\r\n if (!msgPayload.notification) {\r\n // Nothing to do.\r\n return [2 /*return*/];\r\n }\r\n clickAction = msgPayload.notification.click_action;\r\n if (!clickAction) {\r\n // Nothing to do.\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, this.getWindowClient_(clickAction)];\r\n case 1:\r\n windowClient = _a.sent();\r\n if (!!windowClient) return [3 /*break*/, 3];\r\n return [4 /*yield*/, self.clients.openWindow(clickAction)];\r\n case 2:\r\n // Unable to find window client so need to open one.\r\n windowClient = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 3: return [4 /*yield*/, windowClient.focus()];\r\n case 4:\r\n windowClient = _a.sent();\r\n _a.label = 5;\r\n case 5:\r\n if (!windowClient) {\r\n // Window Client will not be returned if it's for a third party origin.\r\n return [2 /*return*/];\r\n }\r\n // Delete notification data from payload before sending to the page.\r\n delete msgPayload.notification;\r\n internalMsg = createNewMsg(MessageType.NOTIFICATION_CLICKED, msgPayload);\r\n // Attempt to send a message to the client to handle the data\r\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\r\n return [2 /*return*/, this.attemptToMessageClient_(windowClient, internalMsg)];\r\n }\r\n });\r\n });\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.getNotificationData_ = function (msgPayload) {\r\n if (!msgPayload) {\r\n return;\r\n }\r\n if (typeof msgPayload.notification !== 'object') {\r\n return;\r\n }\r\n var notificationInformation = __assign({}, msgPayload.notification);\r\n // Put the message payload under FCM_MSG name so we can identify the\r\n // notification as being an FCM notification vs a notification from\r\n // somewhere else (i.e. normal web push or developer generated\r\n // notification).\r\n notificationInformation.data = __assign({}, msgPayload.notification.data, (_a = {}, _a[FCM_MSG] = msgPayload, _a));\r\n return notificationInformation;\r\n var _a;\r\n };\r\n /**\r\n * Calling setBackgroundMessageHandler will opt in to some specific\r\n * behaviours.\r\n * 1.) If a notification doesn't need to be shown due to a window already\r\n * being visible, then push messages will be sent to the page.\r\n * 2.) If a notification needs to be shown, and the message contains no\r\n * notification data this method will be called\r\n * and the promise it returns will be passed to event.waitUntil.\r\n * If you do not set this callback then all push messages will let and the\r\n * developer can handle them in a their own 'push' event callback\r\n *\r\n * @param callback The callback to be called when a push message is received\r\n * and a notification must be shown. The callback will be given the data from\r\n * the push message.\r\n */\r\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\r\n if (!callback || typeof callback !== 'function') {\r\n throw errorFactory.create(ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED);\r\n }\r\n this.bgMessageHandler = callback;\r\n };\r\n /**\r\n * @param url The URL to look for when focusing a client.\r\n * @return Returns an existing window client or a newly opened WindowClient.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.getWindowClient_ = function (url) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var parsedURL, clientList, suitableClient, i, parsedClientUrl;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n parsedURL = new URL(url, self.location.href).href;\r\n return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n suitableClient = null;\r\n for (i = 0; i < clientList.length; i++) {\r\n parsedClientUrl = new URL(clientList[i].url, self.location.href)\r\n .href;\r\n if (parsedClientUrl === parsedURL) {\r\n suitableClient = clientList[i];\r\n break;\r\n }\r\n }\r\n return [2 /*return*/, suitableClient];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This message will attempt to send the message to a window client.\r\n * @param client The WindowClient to send the message to.\r\n * @param message The message to send to the client.\r\n * @returns Returns a promise that resolves after sending the message. This\r\n * does not guarantee that the message was successfully received.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // NOTE: This returns a promise in case this API is abstracted later on to\r\n // do additional work\r\n if (!client) {\r\n throw errorFactory.create(ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG);\r\n }\r\n client.postMessage(message);\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * @returns If there is currently a visible WindowClient, this method will\r\n * resolve to true, otherwise false.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.hasVisibleClients_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var clientList;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n return [2 /*return*/, clientList.some(function (client) { return client.visibilityState === 'visible'; })];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * @param msgPayload The data from the push event that should be sent to all\r\n * available pages.\r\n * @returns Returns a promise that resolves once the message has been sent to\r\n * all WindowClients.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n var clientList, internalMsg;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n internalMsg = createNewMsg(MessageType.PUSH_MSG_RECEIVED, msgPayload);\r\n return [4 /*yield*/, Promise.all(clientList.map(function (client) {\r\n return _this.attemptToMessageClient_(client, internalMsg);\r\n }))];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This will register the default service worker and return the registration.\r\n * @return he service worker registration to be used for the push service.\r\n */\r\n SWController.prototype.getSWRegistration_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n return [2 /*return*/, self.registration];\r\n });\r\n });\r\n };\r\n /**\r\n * This will return the default VAPID key or the uint8array version of the\r\n * public VAPID key provided by the developer.\r\n */\r\n SWController.prototype.getPublicVapidKey_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var swReg, vapidKeyFromDatabase;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n swReg = _a.sent();\r\n if (!swReg) {\r\n throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);\r\n }\r\n return [4 /*yield*/, this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope)];\r\n case 2:\r\n vapidKeyFromDatabase = _a.sent();\r\n if (vapidKeyFromDatabase == null) {\r\n return [2 /*return*/, DEFAULT_PUBLIC_VAPID_KEY];\r\n }\r\n return [2 /*return*/, vapidKeyFromDatabase];\r\n }\r\n });\r\n });\r\n };\r\n return SWController;\r\n}(ControllerInterface));\r\nfunction getClientList() {\r\n return self.clients.matchAll({\r\n type: 'window',\r\n includeUncontrolled: true\r\n // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\r\n });\r\n}\r\nfunction createNewMsg(msgType, msgData) {\r\n return _a = {}, _a[MessageParameter.TYPE_OF_MSG] = msgType, _a[MessageParameter.DATA] = msgData, _a;\r\n var _a;\r\n}\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nvar DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar WindowController = /** @class */ (function (_super) {\r\n __extends(WindowController, _super);\r\n /**\r\n * A service that provides a MessagingService instance.\r\n */\r\n function WindowController(app) {\r\n var _this = _super.call(this, app) || this;\r\n _this.registrationToUse = null;\r\n _this.publicVapidKeyToUse = null;\r\n _this.manifestCheckPromise = null;\r\n _this.messageObserver = null;\r\n // @ts-ignore: Unused variable error, this is not implemented yet.\r\n _this.tokenRefreshObserver = null;\r\n _this.onMessageInternal = createSubscribe(function (observer) {\r\n _this.messageObserver = observer;\r\n });\r\n _this.onTokenRefreshInternal = createSubscribe(function (observer) {\r\n _this.tokenRefreshObserver = observer;\r\n });\r\n _this.setupSWMessageListener_();\r\n return _this;\r\n }\r\n /**\r\n * This method returns an FCM token if it can be generated.\r\n * The return promise will reject if the browser doesn't support\r\n * FCM, if permission is denied for notifications or it's not\r\n * possible to generate a token.\r\n *\r\n * @return Returns a promise that resolves to an FCM token or null if\r\n * permission isn't granted.\r\n */\r\n WindowController.prototype.getToken = function () {\r\n var _this = this;\r\n return this.manifestCheck_().then(function () {\r\n return _super.prototype.getToken.call(_this);\r\n });\r\n };\r\n /**\r\n * The method checks that a manifest is defined and has the correct GCM\r\n * sender ID.\r\n * @return Returns a promise that resolves if the manifest matches\r\n * our required sender ID\r\n */\r\n // Visible for testing\r\n // TODO: make private\r\n WindowController.prototype.manifestCheck_ = function () {\r\n if (this.manifestCheckPromise) {\r\n return this.manifestCheckPromise;\r\n }\r\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\r\n if (!manifestTag) {\r\n this.manifestCheckPromise = Promise.resolve();\r\n }\r\n else {\r\n this.manifestCheckPromise = fetch(manifestTag.href)\r\n .then(function (response) {\r\n return response.json();\r\n })\r\n .catch(function () {\r\n // If the download or parsing fails allow check.\r\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\r\n })\r\n .then(function (manifestContent) {\r\n if (!manifestContent) {\r\n return;\r\n }\r\n if (!manifestContent['gcm_sender_id']) {\r\n return;\r\n }\r\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\r\n throw errorFactory.create(ERROR_CODES.INCORRECT_GCM_SENDER_ID);\r\n }\r\n });\r\n }\r\n return this.manifestCheckPromise;\r\n };\r\n /**\r\n * Request permission if it is not currently granted\r\n *\r\n * @return Resolves if the permission was granted, otherwise rejects\r\n */\r\n WindowController.prototype.requestPermission = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (\r\n // TODO: Remove the cast when this issue is fixed:\r\n // https://github.com/Microsoft/TypeScript/issues/14701\r\n // tslint:disable-next-line no-any\r\n Notification.permission === 'granted') {\r\n return [2 /*return*/];\r\n }\r\n return [2 /*return*/, new Promise(function (resolve, reject) {\r\n var managePermissionResult = function (result) {\r\n if (result === 'granted') {\r\n return resolve();\r\n }\r\n else if (result === 'denied') {\r\n return reject(errorFactory.create(ERROR_CODES.PERMISSION_BLOCKED));\r\n }\r\n else {\r\n return reject(errorFactory.create(ERROR_CODES.PERMISSION_DEFAULT));\r\n }\r\n };\r\n // The Notification.requestPermission API was changed to\r\n // return a promise so now have to handle both in case\r\n // browsers stop support callbacks for promised version\r\n var permissionPromise = Notification.requestPermission(managePermissionResult);\r\n if (permissionPromise) {\r\n // Prefer the promise version as it's the future API.\r\n permissionPromise.then(managePermissionResult);\r\n }\r\n })];\r\n });\r\n });\r\n };\r\n /**\r\n * This method allows a developer to override the default service worker and\r\n * instead use a custom service worker.\r\n *\r\n * @param registration The service worker registration that should be used to\r\n * receive the push messages.\r\n */\r\n WindowController.prototype.useServiceWorker = function (registration) {\r\n if (!(registration instanceof ServiceWorkerRegistration)) {\r\n throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);\r\n }\r\n if (this.registrationToUse != null) {\r\n throw errorFactory.create(ERROR_CODES.USE_SW_BEFORE_GET_TOKEN);\r\n }\r\n this.registrationToUse = registration;\r\n };\r\n /**\r\n * This method allows a developer to override the default vapid key\r\n * and instead use a custom VAPID public key.\r\n *\r\n * @param publicKey A URL safe base64 encoded string.\r\n */\r\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\r\n if (typeof publicKey !== 'string') {\r\n throw errorFactory.create(ERROR_CODES.INVALID_PUBLIC_VAPID_KEY);\r\n }\r\n if (this.publicVapidKeyToUse != null) {\r\n throw errorFactory.create(ERROR_CODES.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\r\n }\r\n var parsedKey = base64ToArrayBuffer(publicKey);\r\n if (parsedKey.length !== 65) {\r\n throw errorFactory.create(ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED);\r\n }\r\n this.publicVapidKeyToUse = parsedKey;\r\n };\r\n /**\r\n * @export\r\n * @param nextOrObserver An observer object or a function triggered on\r\n * message.\r\n * @param error A function triggered on message error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\r\n WindowController.prototype.onMessage = function (nextOrObserver, error, completed) {\r\n if (typeof nextOrObserver === 'function') {\r\n return this.onMessageInternal(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return this.onMessageInternal(nextOrObserver);\r\n }\r\n };\r\n /**\r\n * @param nextOrObserver An observer object or a function triggered on token\r\n * refresh.\r\n * @param error A function triggered on token refresh error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\r\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\r\n if (typeof nextOrObserver === 'function') {\r\n return this.onTokenRefreshInternal(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return this.onTokenRefreshInternal(nextOrObserver);\r\n }\r\n };\r\n /**\r\n * Given a registration, wait for the service worker it relates to\r\n * become activer\r\n * @param registration Registration to wait for service worker to become active\r\n * @return Wait for service worker registration to become active\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\r\n var serviceWorker = registration.installing || registration.waiting || registration.active;\r\n return new Promise(function (resolve, reject) {\r\n if (!serviceWorker) {\r\n // This is a rare scenario but has occured in firefox\r\n reject(errorFactory.create(ERROR_CODES.NO_SW_IN_REG));\r\n return;\r\n }\r\n // Because the Promise function is called on next tick there is a\r\n // small chance that the worker became active or redundant already.\r\n if (serviceWorker.state === 'activated') {\r\n resolve(registration);\r\n return;\r\n }\r\n if (serviceWorker.state === 'redundant') {\r\n reject(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT));\r\n return;\r\n }\r\n var stateChangeListener = function () {\r\n if (serviceWorker.state === 'activated') {\r\n resolve(registration);\r\n }\r\n else if (serviceWorker.state === 'redundant') {\r\n reject(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT));\r\n }\r\n else {\r\n // Return early and wait to next state change\r\n return;\r\n }\r\n serviceWorker.removeEventListener('statechange', stateChangeListener);\r\n };\r\n serviceWorker.addEventListener('statechange', stateChangeListener);\r\n });\r\n };\r\n /**\r\n * This will register the default service worker and return the registration\r\n * @return The service worker registration to be used for the push service.\r\n */\r\n WindowController.prototype.getSWRegistration_ = function () {\r\n var _this = this;\r\n if (this.registrationToUse) {\r\n return this.waitForRegistrationToActivate_(this.registrationToUse);\r\n }\r\n // Make the registration null so we know useServiceWorker will not\r\n // use a new service worker as registrationToUse is no longer undefined\r\n this.registrationToUse = null;\r\n return navigator.serviceWorker\r\n .register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n })\r\n .catch(function (err) {\r\n throw errorFactory.create(ERROR_CODES.FAILED_DEFAULT_REGISTRATION, {\r\n browserErrorMessage: err.message\r\n });\r\n })\r\n .then(function (registration) {\r\n return _this.waitForRegistrationToActivate_(registration).then(function () {\r\n _this.registrationToUse = registration;\r\n // We update after activation due to an issue with Firefox v49 where\r\n // a race condition occassionally causes the service work to not\r\n // install\r\n registration.update();\r\n return registration;\r\n });\r\n });\r\n };\r\n /**\r\n * This will return the default VAPID key or the uint8array version of the public VAPID key\r\n * provided by the developer.\r\n */\r\n WindowController.prototype.getPublicVapidKey_ = function () {\r\n if (this.publicVapidKeyToUse) {\r\n return Promise.resolve(this.publicVapidKeyToUse);\r\n }\r\n return Promise.resolve(DEFAULT_PUBLIC_VAPID_KEY);\r\n };\r\n /**\r\n * This method will set up a message listener to handle\r\n * events from the service worker that should trigger\r\n * events in the page.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n WindowController.prototype.setupSWMessageListener_ = function () {\r\n var _this = this;\r\n navigator.serviceWorker.addEventListener('message', function (event) {\r\n if (!event.data || !event.data[MessageParameter.TYPE_OF_MSG]) {\r\n // Not a message from FCM\r\n return;\r\n }\r\n var workerPageMessage = event.data;\r\n switch (workerPageMessage[MessageParameter.TYPE_OF_MSG]) {\r\n case MessageType.PUSH_MSG_RECEIVED:\r\n case MessageType.NOTIFICATION_CLICKED:\r\n var pushMessage = workerPageMessage[MessageParameter.DATA];\r\n if (_this.messageObserver) {\r\n _this.messageObserver.next(pushMessage);\r\n }\r\n break;\r\n default:\r\n // Noop.\r\n break;\r\n }\r\n }, false);\r\n };\r\n return WindowController;\r\n}(ControllerInterface));\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerMessaging(instance) {\r\n var messagingName = 'messaging';\r\n var factoryMethod = function (app) {\r\n if (!isSupported()) {\r\n throw errorFactory.create(ERROR_CODES.UNSUPPORTED_BROWSER);\r\n }\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return new SWController(app);\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return new WindowController(app);\r\n }\r\n };\r\n factoryMethod.isSupported = isSupported;\r\n var namespaceExports = {\r\n // no-inline\r\n Messaging: WindowController\r\n };\r\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\r\n}\r\nregisterMessaging(firebase);\r\nfunction isSupported() {\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return isSWControllerSupported();\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return isWindowControllerSupported();\r\n }\r\n}\r\n/**\r\n * Checks to see if the required APIs exist.\r\n */\r\nfunction isWindowControllerSupported() {\r\n return ('serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\r\n/**\r\n * Checks to see if the required APIs exist within SW Context.\r\n */\r\nfunction isSWControllerSupported() {\r\n return ('PushManager' in self &&\r\n 'Notification' in self &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\nexport { registerMessaging, isSupported };\n"],"names":["extendStatics","Object","setPrototypeOf","__proto__","Array","d","b","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","__assign","assign","t","s","i","n","arguments","length","call","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","v","op","TypeError","pop","push","ERROR_NAME","captureStackTrace","Error","FirebaseError","code","message","ErrorFactory","err_1","name","defineProperty","get","stack","service","serviceName","errors","pattern","data","undefined","template","fullCode","replace","match","key","toString","err","prop","slice","_super","Sha1","_this","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","opt_offset","W","charCodeAt","k","a","c","update","bytes","opt_length","lengthMinusBlock","inbuf","digest","totalBits","j","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","subscribe","bind","observers","unsubscribes","observerCount","task","finalized","catch","error","forEachObserver","observer","close","complete","nextOrObserver","obj","methods","_i","methods_1","method","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","fn","sendOne","console","_a","MessageParameter","MessageType","ERROR_CODES","AVAILABLE_IN_WINDOW","AVAILABLE_IN_SW","SHOULD_BE_INHERITED","BAD_SENDER_ID","INCORRECT_GCM_SENDER_ID","PERMISSION_DEFAULT","PERMISSION_BLOCKED","UNSUPPORTED_BROWSER","NOTIFICATIONS_BLOCKED","FAILED_DEFAULT_REGISTRATION","SW_REGISTRATION_EXPECTED","GET_SUBSCRIPTION_FAILED","INVALID_SAVED_TOKEN","SW_REG_REDUNDANT","TOKEN_SUBSCRIBE_FAILED","TOKEN_SUBSCRIBE_NO_TOKEN","TOKEN_SUBSCRIBE_NO_PUSH_SET","TOKEN_UNSUBSCRIBE_FAILED","TOKEN_UPDATE_FAILED","TOKEN_UPDATE_NO_TOKEN","USE_SW_BEFORE_GET_TOKEN","INVALID_DELETE_TOKEN","DELETE_TOKEN_NOT_FOUND","DELETE_SCOPE_NOT_FOUND","BG_HANDLER_FUNCTION_EXPECTED","NO_WINDOW_CLIENT_TO_MSG","UNABLE_TO_RESUBSCRIBE","NO_FCM_TOKEN_FOR_RESUBSCRIBE","FAILED_TO_DELETE_TOKEN","NO_SW_IN_REG","BAD_SCOPE","BAD_VAPID_KEY","BAD_SUBSCRIPTION","BAD_TOKEN","BAD_PUSH_SET","FAILED_DELETE_VAPID_KEY","INVALID_PUBLIC_VAPID_KEY","USE_PUBLIC_KEY_BEFORE_GET_TOKEN","PUBLIC_KEY_DECRYPTION_FAILED","ERROR_MAP","errorFactory","DEFAULT_PUBLIC_VAPID_KEY","Uint8Array","ENDPOINT","isArrayBufferEqual","byteLength","viewA","DataView","viewB","getUint8","arrayBufferToBase64","arrayBuffer","uint8Version","btoa","String","fromCharCode","toBase64","IIDModel","getToken","senderId","subscription","publicVapidKey","p256dh","auth","fcmSubscribeBody","applicationPubKey","headers","subscribeOptions","responseData","getKey","endpoint","Headers","append","fetch","json","token","pushSet","updateToken","fcmToken","fcmPushSet","fcmUpdateBody","updateOptions","deleteToken","fcmUnsubscribeBody","unsubscribeOptions","base64ToArrayBuffer","base64String","base64","repeat","rawData","atob","outputArray","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","cleanV1","request","indexedDB","open","onerror","event","onsuccess","db","objectStoreNames","contains","objectStore","transaction","iidModel","openCursorRequest","openCursor","warn","cursor","tokenDetails","fcmSenderId","continue","deleteDatabase","handleDb","DBInterface","dbPromise","createTransaction","getIndex","index","put","delete","closeDatabase","runRequest","mode","getDb","objectStoreName","promisify","oncomplete","dbName","dbVersion","onupgradeneeded","onDbUpgrade","TokenDetailsModel","oldVersion","createObjectStore","keyPath","createIndex","unique","cursorRequest_1","newValue","createTime","Date","now","vapidKey","buffer","getTokenDetailsFromToken","validateInputs","getTokenDetailsFromSWScope","swScope","saveTokenDetails","details","input","ArrayBuffer","VapidDetailsModel","getVapidFromSWScope","saveVapidDetails","deleteVapidDetails","SENDER_ID_OPTION_NAME","ControllerInterface","app","options","messagingSenderId","tokenDetailsModel","vapidDetailsModel","INTERNAL","currentPermission","swReg","pushSubscription","getNotificationPermission_","getSWRegistration_","getPublicVapidKey_","getPushSubscription","scope","manageExistingToken","getNewToken","isEndpointEqual","isAuthEqual","isP256dhEqual","isTokenStillValid","deleteTokenFromDB","updatedToken","allDetails","e_1","registration","pushManager","getSubscription","unsubscribe","swRegistration","userVisibleOnly","applicationServerKey","requestPermission","useServiceWorker","usePublicVapidKey","b64PublicKey","onMessage","completed","onTokenRefresh","setBackgroundMessageHandler","callback","all","Notification","permission","getTokenDetailsModel","getVapidDetailsModel","getIIDModel","SWController","bgMessageHandler","self","addEventListener","onPush","onSubChange","onNotificationClick","waitUntil","onPush_","onSubChange_","onNotificationClick_","msgPayload","notificationDetails","notificationTitle","reg","actions","maxActions","hasVisibleClients_","sendMessageToWindowClients_","getNotificationData_","title","showNotification","err_2","clickAction","windowClient","internalMsg","notification","action","stopImmediatePropagation","click_action","getWindowClient_","clients","openWindow","focus","createNewMsg","NOTIFICATION_CLICKED","attemptToMessageClient_","notificationInformation","url","parsedURL","clientList","suitableClient","URL","location","href","getClientList","client","postMessage","some","visibilityState","PUSH_MSG_RECEIVED","map","vapidKeyFromDatabase","matchAll","type","includeUncontrolled","msgType","msgData","TYPE_OF_MSG","DATA","WindowController","registrationToUse","publicVapidKeyToUse","manifestCheckPromise","messageObserver","tokenRefreshObserver","onMessageInternal","onTokenRefreshInternal","setupSWMessageListener_","manifestCheck_","manifestTag","document","querySelector","response","manifestContent","managePermissionResult","permissionPromise","ServiceWorkerRegistration","publicKey","parsedKey","waitForRegistrationToActivate_","serviceWorker","installing","waiting","active","state","stateChangeListener","removeEventListener","navigator","register","browserErrorMessage","workerPageMessage","pushMessage","isSupported","PushSubscription","window","instance","factoryMethod","namespaceExports","Messaging","registerService","registerMessaging","firebase"],"mappings":"6EAgBA,IAAIA,EAAgBC,OAAOC,iBACpBC,wBAA2BC,OAAS,SAAUC,EAAGC,GAAKD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