{"version":3,"sources":["webpack:///firebase-messaging.js","webpack:///./src/messaging/models/errors.ts","webpack:///./src/messaging/controllers/controller-interface.ts","webpack:///./src/messaging/models/fcm-details.ts","webpack:///./src/messaging/models/notification-permission.ts","webpack:///./src/messaging/models/worker-page-message.ts","webpack:///./src/messaging/controllers/sw-controller.ts","webpack:///./src/messaging/controllers/window-controller.ts","webpack:///./src/messaging.ts","webpack:///./src/messaging/helpers/array-buffer-to-base64.ts","webpack:///./src/messaging/models/default-sw.ts","webpack:///./src/messaging/models/token-manager.ts"],"names":["webpackJsonpFirebase","module","exports","__webpack_require__","_defineProperty","obj","key","value","Object","defineProperty","enumerable","configurable","writable","_ERROR_MAP","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","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","ERROR_MAP","default","codes","map","_interopRequireDefault","__esModule","_classCallCheck","instance","Constructor","TypeError","_createClass","defineProperties","target","props","i","length","descriptor","protoProps","staticProps","prototype","_errors","_errors2","_errors3","_tokenManager","_tokenManager2","_notificationPermission","_notificationPermission2","SENDER_ID_OPTION_NAME","ControllerInterface","app","_this","this","errorFactory_","ErrorFactory","options","create","messagingSenderId_","tokenManager_","INTERNAL","delete","_this2","currentPermission","getNotificationPermission_","granted","denied","Promise","reject","resolve","getSWRegistration_","then","registration","getSavedToken","token","createToken","_this3","deleteToken","pushManager","getSubscription","subscription","unsubscribe","closeDatabase","Notification","permission","FCM_APPLICATION_SERVER_KEY","SUBSCRIPTION_DETAILS","userVisibleOnly","applicationServerKey","Uint8Array","ENDPOINT","APPLICATION_SERVER_KEY","SUBSCRIPTION_OPTIONS","PARAMS","TYPE_OF_MSG","DATA","msgType","PUSH_MSG_RECEIVED","NOTIFICATION_CLICKED","createNewMsg","msgData","_message","TYPES_OF_MSG","_possibleConstructorReturn","self","call","ReferenceError","_inherits","subClass","superClass","constructor","setPrototypeOf","__proto__","_typeof","Symbol","iterator","_controllerInterface","_controllerInterface2","_workerPageMessage","_workerPageMessage2","_fcmDetails","_fcmDetails2","SWController","_ControllerInterface","getPrototypeOf","addEventListener","e","onPush_","onSubChange_","onNotificationClick_","bgMessageHandler_","event","msgPayload","data","json","err","handleMsgPromise","hasVisibleClients_","hasVisibleClients","notification","sendMessageToWindowClients_","notificationDetails","getNotificationData_","notificationTitle","title","showNotification","waitUntil","promiseChain","getToken","tokenDetails","tokenManager","getTokenManager","getTokenDetailsFromToken","details","subscribe","newSubscription","subscribeToFCM","fcmSenderId","fcmPushSet","catch","fcmToken","message","_this4","stopImmediatePropagation","close","clickAction","getWindowClient_","windowClient","clients","openWindow","internalMsg","attemptToMessageClient_","notificationInformation","assign","callback","url","parsedURL","URL","href","matchAll","type","includeUncontrolled","clientList","suitableClient","focus","client","_this5","postMessage","some","visibilityState","_this6","all","_get","get","object","property","receiver","Function","desc","getOwnPropertyDescriptor","undefined","parent","getter","_defaultSw","_defaultSw2","_subscribe","WindowController","registrationToUse_","manifestCheckPromise_","messageObserver_","onMessage_","createSubscribe","observer","tokenRefreshObserver_","onTokenRefresh_","setupSWMessageListener_","isSupported_","manifestCheck_","manifestTag","document","querySelector","fetch","response","manifestContent","managePermissionResult","result","permissionPromise","requestPermission","ServiceWorkerRegistration","nextOrObserver","optError","optCompleted","serviceWorker","installing","waiting","active","state","stateChangeListener","removeEventListener","waitForRegistrationToActivate_","navigator","register","path","scope","browserErrorMessage","update","_this7","workerPageMessage","pushMessage","next","window","hasOwnProperty","PushSubscription","registerMessaging","registerService","_swController2","_windowController2","Messaging","_windowController","_swController","toBase64","arrayBuffer","uint8Version","btoa","String","fromCharCode","apply","replace","_arrayBufferToBase","_arrayBufferToBase2","FCM_TOKEN_OBJ_STORE","TokenManager","openDbPromise_","request","indexedDB","open","onerror","error","onsuccess","onupgradeneeded","db","objectStore","createObjectStore","keyPath","createIndex","unique","openDatabase_","transaction","index","swScope","scopeRequest","senderId","senderIdTokens","cursorRequest","openCursor","cursor","push","continue","pushSet","p256dh","auth","fcmSubscribeBody","endpoint","headers","Headers","append","subscribeOptions","method","body","fcmTokenResponse","masterTokenDetails","swRegistration","put","getAllTokenDetailsForSenderId_","allTokenDetails","findIndex","isSameSubscription_","fcmTokenDetails","sub","saveTokenDetails_","Error"],"mappings":"AAAA,IACUA,sBAAsB,IACzB,CACA,CACA,CACA,CACA,CAED,SAAUC,EAAQC,EAASC,GAEjC,YAwBA,SAASC,GAAgBC,EAAKC,EAAKC,GAAiK,MAApJD,KAAOD,GAAOG,OAAOC,eAAeJ,EAAKC,GAAOC,MAAOA,EAAOG,YAAY,EAAMC,cAAc,EAAMC,UAAU,IAAkBP,EAAIC,GAAOC,EAAgBF,EAN3MG,OAAOC,eAAeP,EAAS,cAC3BK,OAAO,GAGX,IAAIM,GCfOC,GACUC,oBAA4B,2BAChCC,gBAAwB,uBACpBC,oBAAuB,sBAC7BC,cAAiB,gBACPC,wBAA2B,0BAChCC,mBAAsB,qBACtBC,mBAAsB,qBACrBC,oBAAuB,sBACrBC,sBAA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kF,GACR,IAAUA,EACX,KAAUiC,GAAcpI,cAAOG,OAAOb,EAAArB,QAAMC,MAC9ChB,uBAEM,OAAAkL,GAAsBoG,gBACvBvN,KAAG,SAAAiN,GACA,UAAYrN,SAAC,SAAQE,EAAQD,GACjC,GAAiB2N,GAAKP,EAAYO,aAAsBjB,GACvC,aACAW,EAAcM,EAAYN,YAAsBX,GACpDG,EAAcQ,EAAO5N,OAAQ4F,EAAa,QAChDwH,GAAQG,QAAQ,SAAAjJ,GACf/D,EAAoB+D,EAAQjG,OACpCmP,QACOJ,EAAUK,UAAQ,SAAAnJ,GACpB,GAA0C,IAAtBA,EAAQjG,OAAO+L,OAGtC,WAFQ7J,GAAKsH,EAAcpI,cAAOG,OAAOb,EAAArB,QAAMC,MAA0BV,wBAIlEuD,GACToF,cX4zCCsH,IAGXvS,GAAQ+C,QAAUwP,EAClBxS,EAAOC,QAAUA,EAAiB,WAG/B,KACS,MAAM6S,GACN,KAAM,IAAI2C,OACR","file":"firebase-messaging.js","sourcesContent":["try {\n webpackJsonpFirebase([1],[\n/* 0 */,\n/* 1 */,\n/* 2 */,\n/* 3 */,\n/* 4 */,\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _ERROR_MAP;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\nvar ERROR_MAP = (_ERROR_MAP = {}, _defineProperty(_ERROR_MAP, CODES.AVAILABLE_IN_WINDOW, 'This method is available in a Window context.'), _defineProperty(_ERROR_MAP, CODES.AVAILABLE_IN_SW, 'This method is available in a service worker ' + 'context.'), _defineProperty(_ERROR_MAP, CODES.SHOULD_BE_INHERITED, 'This method should be overriden by ' + 'extended classes.'), _defineProperty(_ERROR_MAP, CODES.BAD_SENDER_ID, 'Please ensure that \\'messagingSenderId\\' is set ' + 'correctly in the options passed into firebase.initializeApp().'), _defineProperty(_ERROR_MAP, CODES.PERMISSION_DEFAULT, 'The required permissions were not granted and ' + 'dismissed instead.'), _defineProperty(_ERROR_MAP, CODES.PERMISSION_BLOCKED, 'The required permissions were not granted and ' + 'blocked instead.'), _defineProperty(_ERROR_MAP, CODES.UNSUPPORTED_BROWSER, 'This browser doesn\\'t support the API\\'s ' + 'required to use the firebase SDK.'), _defineProperty(_ERROR_MAP, CODES.NOTIFICATIONS_BLOCKED, 'Notifications have been blocked.'), _defineProperty(_ERROR_MAP, CODES.FAILED_DEFAULT_REGISTRATION, 'We are unable to register the ' + 'default service worker. {$browserErrorMessage}'), _defineProperty(_ERROR_MAP, CODES.SW_REGISTRATION_EXPECTED, 'A service worker registration was the ' + 'expected input.'), _defineProperty(_ERROR_MAP, CODES.GET_SUBSCRIPTION_FAILED, 'There was an error when trying to get ' + 'any existing Push Subscriptions.'), _defineProperty(_ERROR_MAP, CODES.INVALID_SAVED_TOKEN, 'Unable to access details of the saved token.'), _defineProperty(_ERROR_MAP, CODES.SW_REG_REDUNDANT, 'The service worker being used for push was made ' + 'redundant.'), _defineProperty(_ERROR_MAP, CODES.TOKEN_SUBSCRIBE_FAILED, 'A problem occured while subscribing the ' + 'user to FCM: {$message}'), _defineProperty(_ERROR_MAP, CODES.TOKEN_SUBSCRIBE_NO_TOKEN, 'FCM returned no token when subscribing ' + 'the user to push.'), _defineProperty(_ERROR_MAP, CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET, 'FCM returned an invalid response ' + 'when getting an FCM token.'), _defineProperty(_ERROR_MAP, CODES.USE_SW_BEFORE_GET_TOKEN, 'You must call useServiceWorker() before ' + 'calling getToken() to ensure your service worker is used.'), _defineProperty(_ERROR_MAP, CODES.INVALID_DELETE_TOKEN, 'You must pass a valid token into ' + 'deleteToken(), i.e. the token from getToken().'), _defineProperty(_ERROR_MAP, CODES.DELETE_TOKEN_NOT_FOUND, 'The deletion attempt for token could not ' + 'be performed as the token was not found.'), _defineProperty(_ERROR_MAP, CODES.DELETE_SCOPE_NOT_FOUND, 'The deletion attempt for service worker ' + 'scope could not be performed as the scope was not found.'), _defineProperty(_ERROR_MAP, CODES.BG_HANDLER_FUNCTION_EXPECTED, 'The input to ' + 'setBackgroundMessageHandler() must be a function.'), _defineProperty(_ERROR_MAP, CODES.NO_WINDOW_CLIENT_TO_MSG, 'An attempt was made to message a ' + 'non-existant window client.'), _defineProperty(_ERROR_MAP, CODES.UNABLE_TO_RESUBSCRIBE, 'There was an error while re-subscribing ' + 'the FCM token for push messaging. Will have to resubscribe the ' + 'user on next visit. {$message}'), _defineProperty(_ERROR_MAP, CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE, 'Could not find an FCM token ' + 'and as a result, unable to resubscribe. Will have to resubscribe the ' + 'user on next visit.'), _defineProperty(_ERROR_MAP, CODES.FAILED_TO_DELETE_TOKEN, 'Unable to delete the currently saved token.'), _defineProperty(_ERROR_MAP, CODES.NO_SW_IN_REG, 'Even though the service worker registration was ' + 'successful, there was a problem accessing the service worker itself.'), _defineProperty(_ERROR_MAP, CODES.INCORRECT_GCM_SENDER_ID, 'Please change your web app manifest\\'s ' + '\\'gcm_sender_id\\' value to \\'103953800507\\' to use Firebase messaging.'), _defineProperty(_ERROR_MAP, CODES.BAD_SCOPE, 'The service worker scope must be a string with at ' + 'least one character.'), _defineProperty(_ERROR_MAP, CODES.BAD_VAPID_KEY, 'The public VAPID key must be a string with at ' + 'least one character.'), _defineProperty(_ERROR_MAP, CODES.BAD_SUBSCRIPTION, 'The subscription must be a valid ' + 'PushSubscription.'), _defineProperty(_ERROR_MAP, CODES.BAD_TOKEN, 'The FCM Token used for storage / lookup was not ' + 'a valid token string.'), _defineProperty(_ERROR_MAP, CODES.BAD_PUSH_SET, 'The FCM push set used for storage / lookup was not ' + 'not a valid push set string.'), _defineProperty(_ERROR_MAP, CODES.FAILED_DELETE_VAPID_KEY, 'The VAPID key could not be deleted.'), _ERROR_MAP);\nexports.default = {\n codes: CODES,\n map: ERROR_MAP\n};\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 6 */,\n/* 7 */,\n/* 8 */,\n/* 9 */,\n/* 10 */,\n/* 11 */,\n/* 12 */,\n/* 13 */,\n/* 14 */,\n/* 15 */,\n/* 16 */,\n/* 17 */,\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _errors = __webpack_require__(9);\n\nvar _errors2 = __webpack_require__(5);\n\nvar _errors3 = _interopRequireDefault(_errors2);\n\nvar _tokenManager = __webpack_require__(36);\n\nvar _tokenManager2 = _interopRequireDefault(_tokenManager);\n\nvar _notificationPermission = __webpack_require__(20);\n\nvar _notificationPermission2 = _interopRequireDefault(_notificationPermission);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\n\nvar ControllerInterface = function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n\n _classCallCheck(this, ControllerInterface);\n\n this.errorFactory_ = new _errors.ErrorFactory('messaging', 'Messaging', _errors3.default.map);\n if (!app.options[SENDER_ID_OPTION_NAME] || typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(_errors3.default.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new _tokenManager2.default();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () {\n return _this.delete;\n };\n }\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n\n\n _createClass(ControllerInterface, [{\n key: 'getToken',\n value: function getToken() {\n var _this2 = this;\n\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== _notificationPermission2.default.granted) {\n if (currentPermission === _notificationPermission2.default.denied) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this2.tokenManager_.getSavedToken(_this2.messagingSenderId_, registration).then(function (token) {\n if (token) {\n return token;\n }\n return _this2.tokenManager_.createToken(_this2.messagingSenderId_, registration);\n });\n });\n }\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n\n }, {\n key: 'deleteToken',\n value: function deleteToken(token) {\n var _this3 = this;\n\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this3.getSWRegistration_().then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n }).then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n }\n }, {\n key: 'getSWRegistration_',\n value: function getSWRegistration_() {\n throw this.errorFactory_.create(_errors3.default.codes.SHOULD_BE_INHERITED);\n }\n //\n // The following methods should only be available in the window.\n //\n\n }, {\n key: 'requestPermission',\n value: function requestPermission() {\n throw this.errorFactory_.create(_errors3.default.codes.AVAILABLE_IN_WINDOW);\n }\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n\n }, {\n key: 'useServiceWorker',\n value: function useServiceWorker() {\n throw this.errorFactory_.create(_errors3.default.codes.AVAILABLE_IN_WINDOW);\n }\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n\n }, {\n key: 'onMessage',\n value: function onMessage() {\n throw this.errorFactory_.create(_errors3.default.codes.AVAILABLE_IN_WINDOW);\n }\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n\n }, {\n key: 'onTokenRefresh',\n value: function onTokenRefresh() {\n throw this.errorFactory_.create(_errors3.default.codes.AVAILABLE_IN_WINDOW);\n }\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n\n }, {\n key: 'setBackgroundMessageHandler',\n value: function setBackgroundMessageHandler() {\n throw this.errorFactory_.create(_errors3.default.codes.AVAILABLE_IN_SW);\n }\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n\n }, {\n key: 'delete',\n value: function _delete() {\n this.tokenManager_.closeDatabase();\n }\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n\n }, {\n key: 'getNotificationPermission_',\n value: function getNotificationPermission_() {\n return Notification.permission;\n }\n /**\n * @protected\n * @returns {TokenManager}\n */\n\n }, {\n key: 'getTokenManager',\n value: function getTokenManager() {\n return this.tokenManager_;\n }\n }]);\n\n return ControllerInterface;\n}();\n\nexports.default = ControllerInterface;\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar FCM_APPLICATION_SERVER_KEY = [0x04, 0x33, 0x94, 0xF7, 0xDF, 0xA1, 0xEB, 0xB1, 0xDC, 0x03, 0xA2, 0x5E, 0x15, 0x71, 0xDB, 0x48, 0xD3, 0x2E, 0xED, 0xED, 0xB2, 0x34, 0xDB, 0xB7, 0x47, 0x3A, 0x0C, 0x8F, 0xC4, 0xCC, 0xE1, 0x6F, 0x3C, 0x8C, 0x84, 0xDF, 0xAB, 0xB6, 0x66, 0x3E, 0xF2, 0x0C, 0xD4, 0x8B, 0xFE, 0xE3, 0xF9, 0x76, 0x2F, 0x14, 0x1C, 0x63, 0x08, 0x6A, 0x6F, 0x2D, 0xB1, 0x1A, 0x95, 0xB0, 0xCE, 0x37, 0xC0, 0x9C, 0x6E];\nvar SUBSCRIPTION_DETAILS = {\n 'userVisibleOnly': true,\n 'applicationServerKey': new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\nexports.default = {\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n};\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = {\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n};\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var _message;\n\n var message = (_message = {}, _defineProperty(_message, PARAMS.TYPE_OF_MSG, msgType), _defineProperty(_message, PARAMS.DATA, msgData), _message);\n return message;\n};\nexports.default = {\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n};\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 22 */,\n/* 23 */,\n/* 24 */,\n/* 25 */,\n/* 26 */,\n/* 27 */,\n/* 28 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _controllerInterface = __webpack_require__(18);\n\nvar _controllerInterface2 = _interopRequireDefault(_controllerInterface);\n\nvar _errors = __webpack_require__(5);\n\nvar _errors2 = _interopRequireDefault(_errors);\n\nvar _workerPageMessage = __webpack_require__(21);\n\nvar _workerPageMessage2 = _interopRequireDefault(_workerPageMessage);\n\nvar _fcmDetails = __webpack_require__(19);\n\nvar _fcmDetails2 = _interopRequireDefault(_fcmDetails);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar FCM_MSG = 'FCM_MSG';\n\nvar SWController = function (_ControllerInterface) {\n _inherits(SWController, _ControllerInterface);\n\n function SWController(app) {\n _classCallCheck(this, SWController);\n\n var _this = _possibleConstructorReturn(this, (SWController.__proto__ || Object.getPrototypeOf(SWController)).call(this, app));\n\n self.addEventListener('push', function (e) {\n return _this.onPush_(e);\n }, false);\n self.addEventListener('pushsubscriptionchange', function (e) {\n return _this.onSubChange_(e);\n }, false);\n self.addEventListener('notificationclick', function (e) {\n return _this.onNotificationClick_(e);\n }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n\n\n _createClass(SWController, [{\n key: 'onPush_',\n value: function onPush_(event) {\n var _this2 = this;\n\n var msgPayload = void 0;\n try {\n msgPayload = event.data.json();\n } catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this2.bgMessageHandler_) {\n // Send to page\n return _this2.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this2.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n } else if (_this2.bgMessageHandler_) {\n return _this2.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n }\n /**\n * @private\n */\n\n }, {\n key: 'onSubChange_',\n value: function onSubChange_(event) {\n var _this3 = this;\n\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this3.errorFactory_.create(_errors2.default.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this3.getTokenManager();\n return tokenManager.getTokenDetailsFromToken(token).then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this3.errorFactory_.create(_errors2.default.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(_fcmDetails2.default.SUBSCRIPTION_OPTIONS);\n }).then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n }).catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this3.errorFactory_.create(_errors2.default.codes.UNABLE_TO_RESUBSCRIBE, {\n 'message': err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n }\n /**\n * @private\n */\n\n }, {\n key: 'onNotificationClick_',\n value: function onNotificationClick_(event) {\n var _this4 = this;\n\n if (!(event.notification && event.notification.data && event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction).then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n }).then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n msgPayload['notification'];\n\n delete msgPayload['notification'];\n var internalMsg = _workerPageMessage2.default.createNewMsg(_workerPageMessage2.default.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this4.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n }\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n\n }, {\n key: 'getNotificationData_',\n value: function getNotificationData_(msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (_typeof(msgPayload.notification) !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = _defineProperty({}, FCM_MSG, msgPayload);\n return notificationInformation;\n }\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n\n }, {\n key: 'setBackgroundMessageHandler',\n value: function setBackgroundMessageHandler(callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(_errors2.default.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n }\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n\n }, {\n key: 'getWindowClient_',\n value: function getWindowClient_(url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n }\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n\n }, {\n key: 'attemptToMessageClient_',\n value: function attemptToMessageClient_(client, message) {\n var _this5 = this;\n\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this5.errorFactory_.create(_errors2.default.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n }\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n\n }, {\n key: 'hasVisibleClients_',\n value: function hasVisibleClients_() {\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n return clientList.some(function (client) {\n return client.visibilityState === 'visible';\n });\n });\n }\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n\n }, {\n key: 'sendMessageToWindowClients_',\n value: function sendMessageToWindowClients_(msgPayload) {\n var _this6 = this;\n\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n var internalMsg = _workerPageMessage2.default.createNewMsg(_workerPageMessage2.default.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this6.attemptToMessageClient_(client, internalMsg);\n }));\n });\n }\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n\n }, {\n key: 'getSWRegistration_',\n value: function getSWRegistration_() {\n return Promise.resolve(self.registration);\n }\n }]);\n\n return SWController;\n}(_controllerInterface2.default);\n\nexports.default = SWController;\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 29 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if (\"value\" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };\n\nvar _controllerInterface = __webpack_require__(18);\n\nvar _controllerInterface2 = _interopRequireDefault(_controllerInterface);\n\nvar _errors = __webpack_require__(5);\n\nvar _errors2 = _interopRequireDefault(_errors);\n\nvar _workerPageMessage = __webpack_require__(21);\n\nvar _workerPageMessage2 = _interopRequireDefault(_workerPageMessage);\n\nvar _defaultSw = __webpack_require__(35);\n\nvar _defaultSw2 = _interopRequireDefault(_defaultSw);\n\nvar _notificationPermission = __webpack_require__(20);\n\nvar _notificationPermission2 = _interopRequireDefault(_notificationPermission);\n\nvar _subscribe = __webpack_require__(17);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar WindowController = function (_ControllerInterface) {\n _inherits(WindowController, _ControllerInterface);\n\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n _classCallCheck(this, WindowController);\n\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n var _this = _possibleConstructorReturn(this, (WindowController.__proto__ || Object.getPrototypeOf(WindowController)).call(this, app));\n\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = (0, _subscribe.createSubscribe)(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = (0, _subscribe.createSubscribe)(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n\n\n _createClass(WindowController, [{\n key: 'getToken',\n value: function getToken() {\n var _this2 = this;\n\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(_errors2.default.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _get(WindowController.prototype.__proto__ || Object.getPrototypeOf(WindowController.prototype), 'getToken', _this2).call(_this2);\n });\n }\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n\n }, {\n key: 'manifestCheck_',\n value: function manifestCheck_() {\n var _this3 = this;\n\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n } else {\n this.manifestCheckPromise_ = fetch(manifestTag.href).then(function (response) {\n return response.json();\n }).catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n }).then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this3.errorFactory_.create(_errors2.default.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n }\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n\n }, {\n key: 'requestPermission',\n value: function requestPermission() {\n var _this4 = this;\n\n if (Notification.permission === _notificationPermission2.default.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === _notificationPermission2.default.granted) {\n return resolve();\n } else if (result === _notificationPermission2.default.denied) {\n return reject(_this4.errorFactory_.create(_errors2.default.codes.PERMISSION_BLOCKED));\n } else {\n return reject(_this4.errorFactory_.create(_errors2.default.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n }\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n\n }, {\n key: 'useServiceWorker',\n value: function useServiceWorker(registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(_errors2.default.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(_errors2.default.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n }\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n\n }, {\n key: 'onMessage',\n value: function onMessage(nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n }\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n\n }, {\n key: 'onTokenRefresh',\n value: function onTokenRefresh(nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n }\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n\n }, {\n key: 'waitForRegistrationToActivate_',\n value: function waitForRegistrationToActivate_(registration) {\n var _this5 = this;\n\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this5.errorFactory_.create(_errors2.default.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this5.errorFactory_.create(_errors2.default.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n } else if (serviceWorker.state === 'redundant') {\n reject(_this5.errorFactory_.create(_errors2.default.codes.SW_REG_REDUNDANT));\n } else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n }\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n\n }, {\n key: 'getSWRegistration_',\n value: function getSWRegistration_() {\n var _this6 = this;\n\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker.register(_defaultSw2.default.path, {\n scope: _defaultSw2.default.scope\n }).catch(function (err) {\n throw _this6.errorFactory_.create(_errors2.default.codes.FAILED_DEFAULT_REGISTRATION, {\n 'browserErrorMessage': err.message\n });\n }).then(function (registration) {\n return _this6.waitForRegistrationToActivate_(registration).then(function () {\n _this6.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n }\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n\n }, {\n key: 'setupSWMessageListener_',\n value: function setupSWMessageListener_() {\n var _this7 = this;\n\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[_workerPageMessage2.default.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[_workerPageMessage2.default.PARAMS.TYPE_OF_MSG]) {\n case _workerPageMessage2.default.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case _workerPageMessage2.default.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[_workerPageMessage2.default.PARAMS.DATA];\n _this7.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n }\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n\n }, {\n key: 'isSupported_',\n value: function isSupported_() {\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window && ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') && PushSubscription.prototype.hasOwnProperty('getKey');\n }\n }]);\n\n return WindowController;\n}(_controllerInterface2.default);\n\nexports.default = WindowController;\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 30 */,\n/* 31 */,\n/* 32 */,\n/* 33 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.registerMessaging = registerMessaging;\n\nvar _windowController = __webpack_require__(29);\n\nvar _windowController2 = _interopRequireDefault(_windowController);\n\nvar _swController = __webpack_require__(28);\n\nvar _swController2 = _interopRequireDefault(_swController);\n\nvar _app = __webpack_require__(4);\n\nvar _app2 = _interopRequireDefault(_app);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction registerMessaging(instance) {\n instance.INTERNAL.registerService('messaging', function factoryMethod(app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new _swController2.default(app);\n }\n // Assume we are in the window context.\n return new _windowController2.default(app);\n }, {\n // no-inline\n 'Messaging': _windowController2.default\n });\n}\nregisterMessaging(_app2.default);\n\n/***/ }),\n/* 34 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\nfunction toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n\nexports.default = function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n};\n\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 35 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\nmodule.exports = exports['default'];\n\n/***/ }),\n/* 36 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _errors = __webpack_require__(9);\n\nvar _errors2 = __webpack_require__(5);\n\nvar _errors3 = _interopRequireDefault(_errors2);\n\nvar _arrayBufferToBase = __webpack_require__(34);\n\nvar _arrayBufferToBase2 = _interopRequireDefault(_arrayBufferToBase);\n\nvar _fcmDetails = __webpack_require__(19);\n\nvar _fcmDetails2 = _interopRequireDefault(_fcmDetails);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar FCM_TOKEN_DETAILS_DB = 'fcm_token_details_db';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar FCM_TOKEN_DETAILS_DB_VERSION = 1;\n\nvar TokenManager = function () {\n function TokenManager() {\n _classCallCheck(this, TokenManager);\n\n this.errorFactory_ = new _errors.ErrorFactory('messaging', 'Messaging', _errors3.default.map);\n this.openDbPromise_ = null;\n }\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n\n\n _createClass(TokenManager, [{\n key: 'openDatabase_',\n value: function openDatabase_() {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(FCM_TOKEN_DETAILS_DB, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n }\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n\n }, {\n key: 'closeDatabase',\n value: function closeDatabase() {\n var _this = this;\n\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n }\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n\n }, {\n key: 'getTokenDetailsFromToken',\n value: function getTokenDetailsFromToken(fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n }\n }, {\n key: 'getTokenDetailsFromSWScope_',\n value: function getTokenDetailsFromSWScope_(swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n }\n }, {\n key: 'getAllTokenDetailsForSenderId_',\n value: function getAllTokenDetailsForSenderId_(senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n } else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n }\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n\n }, {\n key: 'subscribeToFCM',\n value: function subscribeToFCM(senderId, subscription, pushSet) {\n var _this2 = this;\n\n var p256dh = (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh'));\n var auth = (0, _arrayBufferToBase2.default)(subscription['getKey']('auth'));\n var fcmSubscribeBody = 'authorized_entity=' + senderId + '&' + ('endpoint=' + subscription.endpoint + '&') + ('encryption_key=' + p256dh + '&') + ('encryption_auth=' + auth);\n if (pushSet) {\n fcmSubscribeBody += '&pushSet=' + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(_fcmDetails2.default.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions).then(function (response) {\n return response.json();\n }).then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_FAILED, { 'message': message });\n }\n if (!fcmTokenResponse['token']) {\n throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n 'token': fcmTokenResponse['token'],\n 'pushSet': fcmTokenResponse['pushSet']\n };\n });\n }\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n\n }, {\n key: 'isSameSubscription_',\n value: function isSameSubscription_(subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return subscription.endpoint === masterTokenDetails['endpoint'] && (0, _arrayBufferToBase2.default)(subscription['getKey']('auth')) === masterTokenDetails['auth'] && (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh')) === masterTokenDetails['p256dh'];\n }\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n\n }, {\n key: 'saveTokenDetails_',\n value: function saveTokenDetails_(senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n 'swScope': swRegistration.scope,\n 'endpoint': subscription.endpoint,\n 'auth': (0, _arrayBufferToBase2.default)(subscription['getKey']('auth')),\n 'p256dh': (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh')),\n 'fcmToken': fcmToken,\n 'fcmPushSet': fcmPushSet,\n 'fcmSenderId': senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function () {\n resolve();\n };\n });\n });\n }\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n\n }, {\n key: 'getSavedToken',\n value: function getSavedToken(senderId, swRegistration) {\n var _this3 = this;\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId).then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return swRegistration.scope === tokenDetails['swScope'] && senderId === tokenDetails['fcmSenderId'];\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n }).then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager.getSubscription().catch(function () {\n throw _this3.errorFactory_.create(_errors3.default.codes.GET_SUBSCRIPTION_FAILED);\n }).then(function (subscription) {\n if (subscription && _this3.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n }\n /**\n * Creates a new FCM token.\n */\n\n }, {\n key: 'createToken',\n value: function createToken(senderId, swRegistration) {\n var _this4 = this;\n\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription = void 0;\n var fcmTokenDetails = void 0;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(_fcmDetails2.default.SUBSCRIPTION_OPTIONS);\n }).then(function (sub) {\n subscription = sub;\n return _this4.subscribeToFCM(senderId, subscription);\n }).then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this4.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n }).then(function () {\n return fcmTokenDetails['token'];\n });\n }\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n\n }, {\n key: 'deleteToken',\n value: function deleteToken(token) {\n var _this5 = this;\n\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(_errors3.default.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this5.errorFactory_.create(_errors3.default.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this5.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this5.errorFactory_.create(_errors3.default.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n }\n }]);\n\n return TokenManager;\n}();\n\nexports.default = TokenManager;\nmodule.exports = exports['default'];\n\n/***/ })\n],[33]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nconst CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\n\nconst ERROR_MAP = {\n [CODES.AVAILABLE_IN_WINDOW]: 'This method is available in a Window context.',\n [CODES.AVAILABLE_IN_SW]: 'This method is available in a service worker ' +\n 'context.',\n [CODES.SHOULD_BE_INHERITED]: 'This method should be overriden by ' +\n 'extended classes.',\n [CODES.BAD_SENDER_ID]: 'Please ensure that \\'messagingSenderId\\' is set ' +\n 'correctly in the options passed into firebase.initializeApp().',\n [CODES.PERMISSION_DEFAULT]: 'The required permissions were not granted and ' +\n 'dismissed instead.',\n [CODES.PERMISSION_BLOCKED]: 'The required permissions were not granted and ' +\n 'blocked instead.',\n [CODES.UNSUPPORTED_BROWSER]: 'This browser doesn\\'t support the API\\'s ' +\n 'required to use the firebase SDK.',\n [CODES.NOTIFICATIONS_BLOCKED]: 'Notifications have been blocked.',\n [CODES.FAILED_DEFAULT_REGISTRATION]: 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n [CODES.SW_REGISTRATION_EXPECTED]: 'A service worker registration was the ' +\n 'expected input.',\n [CODES.GET_SUBSCRIPTION_FAILED]: 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n [CODES.INVALID_SAVED_TOKEN]: 'Unable to access details of the saved token.',\n [CODES.SW_REG_REDUNDANT]: 'The service worker being used for push was made ' +\n 'redundant.',\n [CODES.TOKEN_SUBSCRIBE_FAILED]: 'A problem occured while subscribing the ' +\n 'user to FCM: {$message}',\n [CODES.TOKEN_SUBSCRIBE_NO_TOKEN]: 'FCM returned no token when subscribing ' +\n 'the user to push.',\n [CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET]: 'FCM returned an invalid response ' +\n 'when getting an FCM token.',\n [CODES.USE_SW_BEFORE_GET_TOKEN]: 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n [CODES.INVALID_DELETE_TOKEN]: 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n [CODES.DELETE_TOKEN_NOT_FOUND]: 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n [CODES.DELETE_SCOPE_NOT_FOUND]: 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n [CODES.BG_HANDLER_FUNCTION_EXPECTED]: 'The input to ' +\n 'setBackgroundMessageHandler() must be a function.',\n [CODES.NO_WINDOW_CLIENT_TO_MSG]: 'An attempt was made to message a ' +\n 'non-existant window client.',\n [CODES.UNABLE_TO_RESUBSCRIBE]: 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n [CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE]: 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n [CODES.FAILED_TO_DELETE_TOKEN]: 'Unable to delete the currently saved token.',\n [CODES.NO_SW_IN_REG]: 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n [CODES.INCORRECT_GCM_SENDER_ID]: 'Please change your web app manifest\\'s ' +\n '\\'gcm_sender_id\\' value to \\'103953800507\\' to use Firebase messaging.',\n [CODES.BAD_SCOPE]: 'The service worker scope must be a string with at ' +\n 'least one character.',\n [CODES.BAD_VAPID_KEY]: 'The public VAPID key must be a string with at ' +\n 'least one character.',\n [CODES.BAD_SUBSCRIPTION]: 'The subscription must be a valid ' +\n 'PushSubscription.',\n [CODES.BAD_TOKEN]: 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n [CODES.BAD_PUSH_SET]: 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n [CODES.FAILED_DELETE_VAPID_KEY]: 'The VAPID key could not be deleted.'\n};\n\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/errors.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nimport {ErrorFactory} from '../../app/errors';\nimport Errors from '../models/errors';\nimport TokenManager from '../models/token-manager';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n\nexport default class ControllerInterface {\n\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenManager_: TokenManager;\n\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n constructor(app) {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenManager_ = new TokenManager();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete;\n }\n\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n getToken() {\n // Check with permissions\n const currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED)\n );\n }\n\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n\n return this.getSWRegistration_()\n .then(registration => {\n return this.tokenManager_.getSavedToken(\n this.messagingSenderId_, registration)\n .then(token => {\n if (token) {\n return token;\n }\n\n return this.tokenManager_.createToken(this.messagingSenderId_,\n registration);\n });\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n deleteToken(token) {\n return this.tokenManager_.deleteToken(token)\n .then(() => {\n return this.getSWRegistration_()\n .then((registration) => {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(subscription => {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n }\n\n getSWRegistration_(): Promise {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n //\n // The following methods should only be available in the window.\n //\n\n requestPermission() {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n useServiceWorker(registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n onMessage(nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onTokenRefresh(nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n //\n // The following methods are used by the service worker only.\n //\n\n /**\n * @export\n * @param {function(Object)} callback\n */\n setBackgroundMessageHandler(callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n }\n\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n delete() {\n this.tokenManager_.closeDatabase();\n }\n\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n getNotificationPermission_() {\n return (Notification as any).permission;\n }\n\n /**\n * @protected\n * @returns {TokenManager}\n */\n getTokenManager() {\n return this.tokenManager_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/controller-interface.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nconst FCM_APPLICATION_SERVER_KEY = [0x04, 0x33, 0x94, 0xF7, 0xDF,\n 0xA1, 0xEB, 0xB1, 0xDC, 0x03, 0xA2, 0x5E, 0x15, 0x71, 0xDB, 0x48,\n 0xD3, 0x2E, 0xED, 0xED, 0xB2, 0x34, 0xDB, 0xB7, 0x47, 0x3A, 0x0C,\n 0x8F, 0xC4, 0xCC, 0xE1, 0x6F, 0x3C, 0x8C, 0x84, 0xDF, 0xAB, 0xB6,\n 0x66, 0x3E, 0xF2, 0x0C, 0xD4, 0x8B, 0xFE, 0xE3, 0xF9, 0x76, 0x2F,\n 0x14, 0x1C, 0x63, 0x08, 0x6A, 0x6F, 0x2D, 0xB1, 0x1A, 0x95, 0xB0,\n 0xCE, 0x37, 0xC0, 0x9C, 0x6E];\n\nconst SUBSCRIPTION_DETAILS = {\n 'userVisibleOnly': true,\n 'applicationServerKey': new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\n\nexport default {\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n};\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/fcm-details.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nexport default {\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/notification-permission.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nconst PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nconst msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\n\nconst createNewMsg = (msgType, msgData) => {\n const message = {\n [PARAMS.TYPE_OF_MSG]: msgType,\n [PARAMS.DATA]: msgData\n };\n return message;\n};\n\nexport default {\n PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg\n};\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/worker-page-message.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport FCMDetails from '../models/fcm-details';\n\nconst FCM_MSG = 'FCM_MSG';\n\nexport default class SWController extends ControllerInterface {\n\n private bgMessageHandler_: (input: Object) => Promise;\n\n constructor(app) {\n super(app);\n\n self.addEventListener('push', e => this.onPush_(e), false);\n self.addEventListener(\n 'pushsubscriptionchange', e => this.onSubChange_(e), false);\n self.addEventListener(\n 'notificationclick', e => this.onNotificationClick_(e), false);\n\n /**\n * @private\n * @type {function(Object)|null}\n */\n this.bgMessageHandler_ = null;\n }\n\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n onPush_(event) {\n let msgPayload;\n try {\n msgPayload = event.data.json();\n } catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n\n const handleMsgPromise = this.hasVisibleClients_()\n .then(hasVisibleClients => {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || this.bgMessageHandler_) {\n // Send to page\n return this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n\n const notificationDetails = this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n const notificationTitle = notificationDetails.title || '';\n return (self as any).registration\n .showNotification(notificationTitle, notificationDetails);\n } else if (this.bgMessageHandler_) {\n return this.bgMessageHandler_(msgPayload);\n }\n });\n\n event.waitUntil(handleMsgPromise);\n }\n\n /**\n * @private\n */\n onSubChange_(event) {\n const promiseChain = this.getToken()\n .then(token => {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw this.errorFactory_.create(\n Errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n\n let tokenDetails = null;\n const tokenManager = this.getTokenManager();\n return tokenManager.getTokenDetailsFromToken(token)\n .then(details => {\n tokenDetails = details;\n if (!tokenDetails) {\n throw this.errorFactory_.create(Errors.codes.INVALID_SAVED_TOKEN);\n }\n\n // Attempt to get a new subscription\n return (self as any).registration.pushManager.subscribe(FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(newSubscription => {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(\n tokenDetails.fcmSenderId,\n newSubscription,\n tokenDetails.fcmPushSet\n );\n })\n .catch(err => {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken)\n .then(() => {\n throw this.errorFactory_.create(\n Errors.codes.UNABLE_TO_RESUBSCRIBE, {\n 'message': err\n }\n );\n });\n });\n });\n\n event.waitUntil(promiseChain);\n }\n\n /**\n * @private\n */\n onNotificationClick_(event) {\n if (!(event.notification && event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n\n event.notification.close();\n\n const msgPayload = event.notification.data[FCM_MSG];\n const clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n\n const promiseChain = this.getWindowClient_(clickAction)\n .then(windowClient => {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return (self as any).clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(windowClient => {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n\n // Delete notification data from payload before sending to the page.\n const notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n\n const internalMsg = WorkerPageMessage.createNewMsg(\n WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED,\n msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return this.attemptToMessageClient_(windowClient, internalMsg);\n });\n\n event.waitUntil(promiseChain);\n }\n\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n getNotificationData_(msgPayload) {\n if (!msgPayload) {\n return;\n }\n\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n\n const notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = {\n [FCM_MSG]: msgPayload\n };\n\n return notificationInformation;\n }\n\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n setBackgroundMessageHandler(callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(\n Errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n\n this.bgMessageHandler_ = callback;\n }\n\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n getWindowClient_(url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n const parsedURL = new URL(url).href;\n\n return (self as any).clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n let suitableClient = null;\n for (let i = 0; i < clientList.length; i++) {\n const parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n }\n\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n attemptToMessageClient_(client, message) {\n return new Promise((resolve, reject) => {\n if (!client) {\n return reject(this.errorFactory_.create(\n Errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n\n client.postMessage(message);\n resolve();\n });\n }\n\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n hasVisibleClients_() {\n return (self as any).clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n return clientList.some(client => client.visibilityState === 'visible');\n });\n }\n\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n sendMessageToWindowClients_(msgPayload) {\n return (self as any).clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n const internalMsg = WorkerPageMessage.createNewMsg(\n WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED,\n msgPayload);\n\n return Promise.all(\n clientList.map(client => {\n return this.attemptToMessageClient_(client, internalMsg);\n })\n );\n });\n }\n\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n getSWRegistration_() {\n return Promise.resolve((self as any).registration);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/sw-controller.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport {createSubscribe} from '../../app/subscribe';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface {\n\n private registrationToUse_;\n private manifestCheckPromise_;\n private messageObserver_;\n private onMessage_;\n private tokenRefreshObserver_;\n private onTokenRefresh_;\n\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n constructor(app) {\n super(app);\n\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n this.registrationToUse_;\n\n /**\n * @private\n * @type {Promise}\n */\n this.manifestCheckPromise_;\n\n /**\n * @private\n * @type {firebase.Observer}\n */\n this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n this.onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n\n /**\n * @private\n * @type {firebase.Observer}\n */\n this.tokenRefreshObserver_ = null;\n this.onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\n\n this.setupSWMessageListener_();\n }\n\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n getToken() {\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER)\n );\n }\n\n return this.manifestCheck_()\n .then(() => {\n return super.getToken();\n });\n }\n\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n manifestCheck_() {\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n\n const manifestTag = ( document.querySelector('link[rel=\"manifest\"]'));\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n } else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(response => {\n return response.json();\n })\n .catch(() => {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(manifestContent => {\n if (!manifestContent) {\n return;\n }\n\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw this.errorFactory_.create(\n Errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n\n return this.manifestCheckPromise_;\n }\n\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return Promise.resolve();\n }\n\n return new Promise((resolve, reject) => {\n const managePermissionResult = result => {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n } else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(this.errorFactory_.create(\n Errors.codes.PERMISSION_BLOCKED));\n } else {\n return reject(this.errorFactory_.create(\n Errors.codes.PERMISSION_DEFAULT));\n }\n };\n\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n const permissionPromise = Notification.requestPermission(result => {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n\n managePermissionResult(result);\n });\n\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n }\n\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n useServiceWorker(registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n\n this.registrationToUse_ = registration;\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onMessage(nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onTokenRefresh(nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n }\n\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker = registration.installing || registration.waiting ||\n registration.active;\n\n return new Promise((resolve, reject) => {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n\n if (serviceWorker.state === 'redundant') {\n reject(this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n\n let stateChangeListener = () => {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n } else if (serviceWorker.state === 'redundant') {\n reject(this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n } else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n }\n\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n getSWRegistration_() {\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n\n return navigator.serviceWorker.register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION, {\n 'browserErrorMessage': err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration)\n .then(() => {\n this.registrationToUse_ = registration;\n\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n\n return registration;\n });\n });\n }\n\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n setupSWMessageListener_() {\n if (!('serviceWorker' in navigator)) {\n return;\n }\n\n navigator.serviceWorker.addEventListener('message', event => {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n\n const workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n const pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n }\n\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n isSupported_() {\n return 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n ServiceWorkerRegistration.prototype\n .hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey');\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/window-controller.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nimport WindowController from './messaging/controllers/window-controller';\nimport SWController from './messaging/controllers/sw-controller';\nimport firebase from './app';\n\nexport function registerMessaging(instance) {\n const messagingName = 'messaging';\n const factoryMethod = app => {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n\n // Assume we are in the window context.\n return new WindowController(app);\n };\n\n const namespaceExports = {\n // no-inline\n 'Messaging': WindowController\n };\n\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\n\nregisterMessaging(firebase);\n\n\n// WEBPACK FOOTER //\n// ./src/messaging.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\nfunction toBase64(arrayBuffer) {\n const uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n\nexport default (arrayBuffer) => {\n const base64String = toBase64(arrayBuffer);\n return base64String.replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/helpers/array-buffer-to-base64.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/default-sw.ts","/**\n* Copyright 2017 Google Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n'use strict';\n\nimport {ErrorFactory} from '../../app/errors';\n\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\n\nconst FCM_TOKEN_DETAILS_DB = 'fcm_token_details_db';\nconst FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nconst FCM_TOKEN_DETAILS_DB_VERSION = 1;\n\nexport default class TokenManager {\n\n private errorFactory_: ErrorFactory;\n private openDbPromise_: Promise;\n\n constructor() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.openDbPromise_ = null;\n }\n\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n openDatabase_() {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n\n this.openDbPromise_ = new Promise((resolve, reject) => {\n const request = indexedDB.open(FCM_TOKEN_DETAILS_DB,\n FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = event => {\n reject(( event.target).error);\n };\n request.onsuccess = event => {\n resolve(( event.target).result);\n };\n request.onupgradeneeded = event => {\n var db = ( event.target).result;\n\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n\n return this.openDbPromise_;\n }\n\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n closeDatabase() {\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(db => {\n db.close();\n this.openDbPromise_ = null;\n });\n }\n\n return Promise.resolve();\n }\n\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n getTokenDetailsFromToken(fcmToken) {\n return this.openDatabase_()\n .then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const index = objectStore.index('fcmToken');\n const request = index.get(fcmToken);\n request.onerror = function(event) {\n reject(( event.target).error);\n };\n request.onsuccess = function(event) {\n resolve(( event.target).result);\n };\n });\n });\n }\n\n getTokenDetailsFromSWScope_(swScope) {\n return this.openDatabase_()\n .then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = event => {\n reject(( event.target).error);\n };\n\n scopeRequest.onsuccess = event => {\n resolve(( event.target).result);\n };\n });\n });\n }\n\n getAllTokenDetailsForSenderId_(senderId): Promise> {\n return this.openDatabase_()\n .then(db => {\n return new Promise>((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n\n const senderIdTokens = [];\n\n const cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = event => {\n reject(( event.target).error);\n };\n\n cursorRequest.onsuccess = event => {\n const cursor = ( event.target).result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n } else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n }\n\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n subscribeToFCM(senderId, subscription, pushSet?): Promise {\n const p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n const auth = arrayBufferToBase64(subscription['getKey']('auth'));\n\n let fcmSubscribeBody = `authorized_entity=${senderId}&` +\n `endpoint=${subscription.endpoint}&` +\n `encryption_key=${p256dh}&` +\n `encryption_auth=${auth}`;\n\n if (pushSet) {\n fcmSubscribeBody += `&pushSet=${pushSet}`;\n }\n\n const headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n\n const subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe',\n subscribeOptions)\n .then(response => response.json())\n .then(response => {\n const fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n const message = fcmTokenResponse['error']['message'];\n throw this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED,\n {'message': message});\n }\n\n if (!fcmTokenResponse['token']) {\n throw this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n\n if (!fcmTokenResponse['pushSet']) {\n throw this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n\n return {\n 'token': fcmTokenResponse['token'],\n 'pushSet': fcmTokenResponse['pushSet']\n };\n });\n }\n\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n isSameSubscription_(subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (subscription.endpoint === masterTokenDetails['endpoint'] &&\n arrayBufferToBase64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n arrayBufferToBase64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']);\n }\n\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n saveTokenDetails_(senderId, swRegistration,\n subscription, fcmToken, fcmPushSet) {\n const details = {\n 'swScope': swRegistration.scope,\n 'endpoint': subscription.endpoint,\n 'auth': arrayBufferToBase64(subscription['getKey']('auth')),\n 'p256dh': arrayBufferToBase64(subscription['getKey']('p256dh')),\n 'fcmToken': fcmToken,\n 'fcmPushSet': fcmPushSet,\n 'fcmSenderId': senderId\n };\n\n return this.openDatabase_()\n .then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const request = objectStore.put(details);\n request.onerror = event => {\n reject(( event.target).error);\n };\n request.onsuccess = event => {\n resolve();\n };\n });\n });\n }\n\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n getSavedToken(senderId, swRegistration) {\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(\n Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(\n Errors.codes.BAD_SENDER_ID));\n }\n\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(allTokenDetails => {\n if (allTokenDetails.length === 0) {\n return;\n }\n\n const index = allTokenDetails.findIndex(tokenDetails => {\n return (swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']);\n });\n\n if (index === -1) {\n return;\n }\n\n return allTokenDetails[index];\n })\n .then(tokenDetails => {\n if (!tokenDetails) {\n return;\n }\n\n return swRegistration.pushManager.getSubscription()\n .catch(err => {\n throw this.errorFactory_.create(Errors.codes.GET_SUBSCRIPTION_FAILED);\n })\n .then(subscription => {\n if (subscription &&\n this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n }\n\n /**\n * Creates a new FCM token.\n */\n createToken(senderId, swRegistration): Promise {\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(\n Errors.codes.BAD_SENDER_ID));\n }\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(\n Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n\n // Check for existing subscription first\n let subscription;\n let fcmTokenDetails;\n return swRegistration.pushManager.getSubscription()\n .then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe(\n FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(sub => {\n subscription = sub;\n return this.subscribeToFCM(senderId, subscription)\n })\n .then(tokenDetails => {\n fcmTokenDetails = tokenDetails;\n return this.saveTokenDetails_(senderId, swRegistration, subscription,\n fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n })\n .then(() => fcmTokenDetails['token']);\n }\n\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n deleteToken(token) {\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN));\n }\n\n return this.getTokenDetailsFromToken(token)\n .then(details => {\n if (!details) {\n throw this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n\n return this.openDatabase_()\n .then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE],\n 'readwrite');\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const request = objectStore.delete(details['swScope']);\n request.onerror = event => {\n reject(( event.target).error);\n };\n request.onsuccess = event => {\n if (( event.target).result === 0) {\n reject(this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n\n resolve(details);\n };\n });\n });\n });\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/token-manager.ts"],"sourceRoot":""}