Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

@firebase/messaging

Package Overview
Dependencies
Maintainers
3
Versions
3665
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@firebase/messaging - npm Package Compare versions

Comparing version
0.2.2-canary.9d00c6f
to
0.2.2-canary.ab0faeb
+4
-1
dist/cjs/src/controllers/controller-interface.d.ts

@@ -46,4 +46,7 @@ import TokenDetailsModel from '../models/token-details-model';

requestPermission(): void;
getPushSubscription_(registration: any, publicVapidKey: any): Promise<PushSubscription>;
/**
* Gets a PushSubscription for the current user.
*/
getPushSubscription(swRegistration: ServiceWorkerRegistration, publicVapidKey: Uint8Array): Promise<PushSubscription>;
/**
* @export

@@ -50,0 +53,0 @@ * @param {!ServiceWorkerRegistration} registration

+15
-4

@@ -125,3 +125,3 @@ /**

publicVapidKey = publicKey;
return _this.getPushSubscription_(swReg, publicVapidKey);
return _this.getPushSubscription(swReg, publicVapidKey);
})

@@ -164,3 +164,3 @@ .then(function (pushSubscription) {

publicVapidKey = publicKey;
return _this.getPushSubscription_(swReg, publicVapidKey);
return _this.getPushSubscription(swReg, publicVapidKey);
})

@@ -230,4 +230,15 @@ .then(function (pushSubscription) {

};
ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {
throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_WINDOW);
/**
* Gets a PushSubscription for the current user.
*/
ControllerInterface.prototype.getPushSubscription = function (swRegistration, publicVapidKey) {
return swRegistration.pushManager.getSubscription().then(function (subscription) {
if (subscription) {
return subscription;
}
return swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicVapidKey
});
});
};

@@ -234,0 +245,0 @@ /**

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/controllers/controller-interface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;;AAEb,uCAA8C;AAC9C,2CAAsC;AAC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**\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 '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport default class ControllerInterface {\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenDetailsModel_: TokenDetailsModel;\n private vapidDetailsModel_: VapidDetailsModel;\n private iidModel_: IIDModel;\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 (\n !app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'\n ) {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete();\n }\n\n /**\n * @export\n */\n getToken(): Promise<string | null> {\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 let swReg: ServiceWorkerRegistration;\n return this.getSWRegistration_()\n .then(reg => {\n swReg = reg;\n return this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(tokenDetails => {\n if (tokenDetails) {\n return this.manageExistingToken(tokenDetails, swReg);\n }\n return this.getNewToken(swReg);\n });\n }\n\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n private manageExistingToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n return this.isTokenStillValid(tokenDetails).then(isValid => {\n if (isValid) {\n const now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n } else {\n return this.updateToken(tokenDetails, swReg);\n }\n } else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n return this.getNewToken(swReg);\n });\n }\n });\n }\n\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n private isTokenStillValid(tokenDetails: Object): Promise<Boolean> {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(publicKey => {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n }\n\n private updateToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n let publicVapidKey: Uint8Array;\n let updatedToken: string;\n let subscription: PushSubscription;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.updateToken(\n this.messagingSenderId_,\n tokenDetails['fcmToken'],\n tokenDetails['fcmPushSet'],\n subscription,\n publicVapidKey\n );\n })\n .catch(err => {\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n throw err;\n });\n })\n .then(token => {\n updatedToken = token;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return updatedToken;\n });\n }\n\n private getNewToken(swReg: ServiceWorkerRegistration): Promise<string> {\n let publicVapidKey: Uint8Array;\n let subscription: PushSubscription;\n let tokenDetails: Object;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.getToken(\n this.messagingSenderId_,\n subscription,\n publicVapidKey\n );\n })\n .then(iidTokenDetails => {\n tokenDetails = iidTokenDetails;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return tokenDetails['token'];\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n deleteToken(token: string): Promise<Boolean> {\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(details => {\n return this.iidModel_.deleteToken(\n details['fcmSenderId'],\n details['fcmToken'],\n details['fcmPushSet']\n );\n })\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<ServiceWorkerRegistration> {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n getPublicVapidKey_(): Promise<Uint8Array> {\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 getPushSubscription_(\n registration,\n publicVapidKey\n ): Promise<PushSubscription> {\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 {!string} b64PublicKey\n */\n usePublicVapidKey(b64PublicKey) {\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 return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\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 getTokenDetailsModel(): TokenDetailsModel {\n return this.tokenDetailsModel_;\n }\n\n getVapidDetailsModel(): VapidDetailsModel {\n return this.vapidDetailsModel_;\n }\n\n /**\n * @protected\n * @returns {IIDModel}\n */\n getIIDModel() {\n return this.iidModel_;\n }\n}\n"]}
{"version":3,"sources":["../src/controllers/controller-interface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;;AAEb,uCAA8C;AAC9C,2CAAsC;AACtC,qEAA8D;AAC9D,qEAA8D;AAC9D,6EAAwE;AACxE,iDAA2C;AAC3C,4EAAoE;AAEpE,IAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAClD,oDAAoD;AACvC,QAAA,uBAAuB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;AAEzE;IASE;;;OAGG;IACH,6BAAY,GAAG;QAAf,iBAmBC;QAlBC,IAAI,CAAC,aAAa,GAAG,IAAI,mBAAY,CAAC,WAAW,EAAE,WAAW,EAAE,gBAAM,CAAC,GAAG,CAAC,CAAC;QAE5E,EAAE,CA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C,MAAM,CAAC,gBAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACpE,CAAC;IAED;;;;;;;;;OASG;IACH,4CAAc,GAAd,UAAe,cAAc,EAAE,QAAQ,EAAE,YAAY;QACnD,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,gBAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACpE,CAAC;IAED,EAAE;IACF,6DAA6D;IAC7D,EAAE;IAEF;;;OAGG;IACH,yDAA2B,GAA3B,UAA4B,QAAQ;QAClC,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,gBAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAChE,CAAC;IAED,EAAE;IACF,2EAA2E;IAC3E,qDAAqD;IACrD,EAAE;IAEF;;;OAGG;IACH,oCAAM,GAAN;QACE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;YACjB,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;YACvC,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;SACxC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,wDAA0B,GAA1B;QACE,MAAM,CAAE,YAAoB,CAAC,UAAU,CAAC;IAC1C,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,yCAAW,GAAX;QACE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IACH,0BAAC;AAAD,CAtWA,AAsWC,IAAA","file":"controller-interface.js","sourcesContent":["/**\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 '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport default class ControllerInterface {\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenDetailsModel_: TokenDetailsModel;\n private vapidDetailsModel_: VapidDetailsModel;\n private iidModel_: IIDModel;\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 (\n !app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'\n ) {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete();\n }\n\n /**\n * @export\n */\n getToken(): Promise<string | null> {\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 let swReg: ServiceWorkerRegistration;\n return this.getSWRegistration_()\n .then(reg => {\n swReg = reg;\n return this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(tokenDetails => {\n if (tokenDetails) {\n return this.manageExistingToken(tokenDetails, swReg);\n }\n return this.getNewToken(swReg);\n });\n }\n\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n private manageExistingToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n return this.isTokenStillValid(tokenDetails).then(isValid => {\n if (isValid) {\n const now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n } else {\n return this.updateToken(tokenDetails, swReg);\n }\n } else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n return this.getNewToken(swReg);\n });\n }\n });\n }\n\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n private isTokenStillValid(tokenDetails: Object): Promise<Boolean> {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(publicKey => {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n }\n\n private updateToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n let publicVapidKey: Uint8Array;\n let updatedToken: string;\n let subscription: PushSubscription;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.updateToken(\n this.messagingSenderId_,\n tokenDetails['fcmToken'],\n tokenDetails['fcmPushSet'],\n subscription,\n publicVapidKey\n );\n })\n .catch(err => {\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n throw err;\n });\n })\n .then(token => {\n updatedToken = token;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return updatedToken;\n });\n }\n\n private getNewToken(swReg: ServiceWorkerRegistration): Promise<string> {\n let publicVapidKey: Uint8Array;\n let subscription: PushSubscription;\n let tokenDetails: Object;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.getToken(\n this.messagingSenderId_,\n subscription,\n publicVapidKey\n );\n })\n .then(iidTokenDetails => {\n tokenDetails = iidTokenDetails;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return tokenDetails['token'];\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n deleteToken(token: string): Promise<Boolean> {\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(details => {\n return this.iidModel_.deleteToken(\n details['fcmSenderId'],\n details['fcmToken'],\n details['fcmPushSet']\n );\n })\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<ServiceWorkerRegistration> {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n getPublicVapidKey_(): Promise<Uint8Array> {\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 * Gets a PushSubscription for the current user.\n */\n getPushSubscription(\n swRegistration: ServiceWorkerRegistration,\n publicVapidKey: Uint8Array\n ): Promise<PushSubscription> {\n return swRegistration.pushManager.getSubscription().then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\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 {!string} b64PublicKey\n */\n usePublicVapidKey(b64PublicKey) {\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 return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\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 getTokenDetailsModel(): TokenDetailsModel {\n return this.tokenDetailsModel_;\n }\n\n getVapidDetailsModel(): VapidDetailsModel {\n return this.vapidDetailsModel_;\n }\n\n /**\n * @protected\n * @returns {IIDModel}\n */\n getIIDModel() {\n return this.iidModel_;\n }\n}\n"]}

@@ -102,9 +102,2 @@ import { FirebaseMessaging } from '@firebase/messaging-types';

/**
* Gets a PushSubscription for the current user.
* @private
* @param {ServiceWorkerRegistration} registration
* @return {Promise<PushSubscription>}
*/
getPushSubscription_(swRegistration: any, publicVapidKey: any): any;
/**
* This method will set up a message listener to handle

@@ -111,0 +104,0 @@ * events from the service worker that should trigger

@@ -322,22 +322,2 @@ /**

/**
* Gets a PushSubscription for the current user.
* @private
* @param {ServiceWorkerRegistration} registration
* @return {Promise<PushSubscription>}
*/
WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {
// Check for existing subscription first
var subscription;
var fcmTokenDetails;
return swRegistration.pushManager.getSubscription().then(function (subscription) {
if (subscription) {
return subscription;
}
return swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicVapidKey
});
});
};
/**
* This method will set up a message listener to handle

@@ -344,0 +324,0 @@ * events from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,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,6BAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBACrE,yBAAyB;gBACzB,MAAM,CAAC;YACT,CAAC;YAED,IAAM,iBAAiB,GAAG,KAAK,CAAC,IAAI,CAAC;YACrC,MAAM,CAAC,CAAC,iBAAiB,CAAC,6BAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBAChE,KAAK,6BAAiB,CAAC,YAAY,CAAC,iBAAiB,CAAC;gBACtD,KAAK,6BAAiB,CAAC,YAAY,CAAC,oBAAoB;oBACtD,IAAM,WAAW,GACf,iBAAiB,CAAC,6BAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;wBAC1B,KAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;oBAC1C,CAAC;oBACD,KAAK,CAAC;gBACR;oBACE,QAAQ;oBACR,KAAK,CAAC;YACV,CAAC;QACH,CAAC,EACD,KAAK,CACN,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,uCAAY,GAAZ;QACE,MAAM,CAAC,CACL,eAAe,IAAI,SAAS;YAC5B,aAAa,IAAI,MAAM;YACvB,cAAc,IAAI,MAAM;YACxB,OAAO,IAAI,MAAM;YACjB,yBAAyB,CAAC,SAAS,CAAC,cAAc,CAAC,kBAAkB,CAAC;YACtE,gBAAgB,CAAC,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CACpD,CAAC;IACJ,CAAC;IACH,uBAAC;AAAD,CAjaA,AAiaC,CAja6C,8BAAmB,GAiahE","file":"window-controller.js","sourcesContent":["/**\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 { FirebaseMessaging } from '@firebase/messaging-types';\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 FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface\n implements FirebaseMessaging {\n private registrationToUse_;\n private publicVapidKeyToUse_;\n private manifestCheckPromise_;\n private messageObserver_ = null;\n private onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n private tokenRefreshObserver_ = null;\n private onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\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 /**\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<string> | Promise<null>} 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_().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 = <HTMLAnchorElement>document.querySelector(\n 'link[rel=\"manifest\"]'\n );\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 })\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\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 async requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return;\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(\n this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED)\n );\n } else {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT)\n );\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(\n managePermissionResult\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 * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n usePublicVapidKey(publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(\n Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN\n );\n }\n\n const parsedKey = base64ToArrayBuffer(publicKey);\n\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(\n Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED\n );\n }\n\n this.publicVapidKeyToUse_ = parsedKey;\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<!ServiceWorkerRegistration>} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker =\n registration.installing || registration.waiting || registration.active;\n\n return new Promise<ServiceWorkerRegistration>((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<!ServiceWorkerRegistration>} 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\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION,\n {\n browserErrorMessage: err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration).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 will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n getPublicVapidKey_(): Promise<Uint8Array> {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\n }\n\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise<PushSubscription>}\n */\n getPushSubscription_(swRegistration, publicVapidKey) {\n // Check for existing subscription first\n let subscription;\n let fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\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(\n 'message',\n 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 =\n workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (this.messageObserver_) {\n this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n },\n false\n );\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 (\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n }\n}\n"]}
{"version":3,"sources":["../src/controllers/window-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;;;AAGb,+DAAyD;AACzD,2CAAsC;AACtC,qEAA8D;AAC9D,mDAA6C;AAC7C,6EAAwE;AACxE,qDAA+C;AAC/C,4EAAoE;AACpE,uCAAiD;AAIjD;IAA8C,4CAAmB;IAc/D;;;OAGG;IACH,0BAAY,GAAG;QAAf,YACE,kBAAM,GAAG,CAAC,SAsCX;QApDO,sBAAgB,GAAG,IAAI,CAAC;QACxB,gBAAU,GAAG,sBAAe,CAAC,UAAA,QAAQ;YAC3C,KAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC,CAAC,CAAC;QACK,2BAAqB,GAAG,IAAI,CAAC;QAC7B,qBAAe,GAAG,sBAAe,CAAC,UAAA,QAAQ;YAChD,KAAI,CAAC,qBAAqB,GAAG,QAAQ,CAAC;QACxC,CAAC,CAAC,CAAC;QASD;;;WAGG;QACH,KAAI,CAAC,kBAAkB,CAAC;QAExB;;;WAGG;QACH,KAAI,CAAC,qBAAqB,CAAC;QAE3B;;;WAGG;QACH,KAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAE7B;;;WAGG;QACH,KAAI,CAAC,UAAU,GAAG,sBAAe,CAAC,UAAA,QAAQ;YACxC,KAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC,CAAC,CAAC;QAEH;;;WAGG;QACH,KAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;QAClC,KAAI,CAAC,eAAe,GAAG,sBAAe,CAAC,UAAA,QAAQ;YAC7C,KAAI,CAAC,q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CAAC,CAAC,CAAC;gBAChE,KAAK,6BAAiB,CAAC,YAAY,CAAC,iBAAiB,CAAC;gBACtD,KAAK,6BAAiB,CAAC,YAAY,CAAC,oBAAoB;oBACtD,IAAM,WAAW,GACf,iBAAiB,CAAC,6BAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;wBAC1B,KAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;oBAC1C,CAAC;oBACD,KAAK,CAAC;gBACR;oBACE,QAAQ;oBACR,KAAK,CAAC;YACV,CAAC;QACH,CAAC,EACD,KAAK,CACN,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,uCAAY,GAAZ;QACE,MAAM,CAAC,CACL,eAAe,IAAI,SAAS;YAC5B,aAAa,IAAI,MAAM;YACvB,cAAc,IAAI,MAAM;YACxB,OAAO,IAAI,MAAM;YACjB,yBAAyB,CAAC,SAAS,CAAC,cAAc,CAAC,kBAAkB,CAAC;YACtE,gBAAgB,CAAC,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CACpD,CAAC;IACJ,CAAC;IACH,uBAAC;AAAD,CA3YA,AA2YC,CA3Y6C,8BAAmB,GA2YhE","file":"window-controller.js","sourcesContent":["/**\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 { FirebaseMessaging } from '@firebase/messaging-types';\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 FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface\n implements FirebaseMessaging {\n private registrationToUse_;\n private publicVapidKeyToUse_;\n private manifestCheckPromise_;\n private messageObserver_ = null;\n private onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n private tokenRefreshObserver_ = null;\n private onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\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 /**\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<string> | Promise<null>} 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_().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 = <HTMLAnchorElement>document.querySelector(\n 'link[rel=\"manifest\"]'\n );\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 })\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\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 async requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return;\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(\n this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED)\n );\n } else {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT)\n );\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(\n managePermissionResult\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 * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n usePublicVapidKey(publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(\n Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN\n );\n }\n\n const parsedKey = base64ToArrayBuffer(publicKey);\n\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(\n Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED\n );\n }\n\n this.publicVapidKeyToUse_ = parsedKey;\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<!ServiceWorkerRegistration>} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker =\n registration.installing || registration.waiting || registration.active;\n\n return new Promise<ServiceWorkerRegistration>((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<!ServiceWorkerRegistration>} 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\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION,\n {\n browserErrorMessage: err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration).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 will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n getPublicVapidKey_(): Promise<Uint8Array> {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\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(\n 'message',\n 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 =\n workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (this.messageObserver_) {\n this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n },\n false\n );\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 (\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n }\n}\n"]}

@@ -46,4 +46,7 @@ import TokenDetailsModel from '../models/token-details-model';

requestPermission(): void;
getPushSubscription_(registration: any, publicVapidKey: any): Promise<PushSubscription>;
/**
* Gets a PushSubscription for the current user.
*/
getPushSubscription(swRegistration: ServiceWorkerRegistration, publicVapidKey: Uint8Array): Promise<PushSubscription>;
/**
* @export

@@ -50,0 +53,0 @@ * @param {!ServiceWorkerRegistration} registration

@@ -124,3 +124,3 @@ /**

publicVapidKey = publicKey;
return _this.getPushSubscription_(swReg, publicVapidKey);
return _this.getPushSubscription(swReg, publicVapidKey);
})

@@ -163,3 +163,3 @@ .then(function (pushSubscription) {

publicVapidKey = publicKey;
return _this.getPushSubscription_(swReg, publicVapidKey);
return _this.getPushSubscription(swReg, publicVapidKey);
})

@@ -229,4 +229,15 @@ .then(function (pushSubscription) {

};
ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {
throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
/**
* Gets a PushSubscription for the current user.
*/
ControllerInterface.prototype.getPushSubscription = function (swRegistration, publicVapidKey) {
return swRegistration.pushManager.getSubscription().then(function (subscription) {
if (subscription) {
return subscription;
}
return swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicVapidKey
});
});
};

@@ -233,0 +244,0 @@ /**

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/controllers/controller-interface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;AAEb,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,uBAAuB,MAAM,mCAAmC,CAAC;AACxE,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,mBAAmB,MAAM,mCAAmC,CAAC;AAEpE,IAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAClD,oDAAoD;AACpD,MAAM,CAAC,IAAM,uBAAuB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;AAEzE;IASE;;;OAGG;IACH,6BAAY,GAAG;QAAf,iBAmBC;QAlBC,IAAI,CAAC,aAAa,GAAG,IAAI,YAAY,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QAE5E,EAAE,CAAC,CACD,CAAC,GAAG,CAAC,OAAO,C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IAEF;;;OAGG;IACH,yDAA2B,GAA3B,UAA4B,QAAQ;QAClC,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAChE,CAAC;IAED,EAAE;IACF,2EAA2E;IAC3E,qDAAqD;IACrD,EAAE;IAEF;;;OAGG;IACH,oCAAM,GAAN;QACE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;YACjB,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;YACvC,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;SACxC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,wDAA0B,GAA1B;QACE,MAAM,CAAE,YAAoB,CAAC,UAAU,CAAC;IAC1C,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,yCAAW,GAAX;QACE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IACH,0BAAC;AAAD,CA1VA,AA0VC,IAAA","file":"controller-interface.js","sourcesContent":["/**\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 '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport default class ControllerInterface {\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenDetailsModel_: TokenDetailsModel;\n private vapidDetailsModel_: VapidDetailsModel;\n private iidModel_: IIDModel;\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 (\n !app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'\n ) {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete();\n }\n\n /**\n * @export\n */\n getToken(): Promise<string | null> {\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 let swReg: ServiceWorkerRegistration;\n return this.getSWRegistration_()\n .then(reg => {\n swReg = reg;\n return this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(tokenDetails => {\n if (tokenDetails) {\n return this.manageExistingToken(tokenDetails, swReg);\n }\n return this.getNewToken(swReg);\n });\n }\n\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n private manageExistingToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n return this.isTokenStillValid(tokenDetails).then(isValid => {\n if (isValid) {\n const now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n } else {\n return this.updateToken(tokenDetails, swReg);\n }\n } else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n return this.getNewToken(swReg);\n });\n }\n });\n }\n\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n private isTokenStillValid(tokenDetails: Object): Promise<Boolean> {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(publicKey => {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n }\n\n private updateToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n let publicVapidKey: Uint8Array;\n let updatedToken: string;\n let subscription: PushSubscription;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.updateToken(\n this.messagingSenderId_,\n tokenDetails['fcmToken'],\n tokenDetails['fcmPushSet'],\n subscription,\n publicVapidKey\n );\n })\n .catch(err => {\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n throw err;\n });\n })\n .then(token => {\n updatedToken = token;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return updatedToken;\n });\n }\n\n private getNewToken(swReg: ServiceWorkerRegistration): Promise<string> {\n let publicVapidKey: Uint8Array;\n let subscription: PushSubscription;\n let tokenDetails: Object;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.getToken(\n this.messagingSenderId_,\n subscription,\n publicVapidKey\n );\n })\n .then(iidTokenDetails => {\n tokenDetails = iidTokenDetails;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return tokenDetails['token'];\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n deleteToken(token: string): Promise<Boolean> {\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(details => {\n return this.iidModel_.deleteToken(\n details['fcmSenderId'],\n details['fcmToken'],\n details['fcmPushSet']\n );\n })\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<ServiceWorkerRegistration> {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n getPublicVapidKey_(): Promise<Uint8Array> {\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 getPushSubscription_(\n registration,\n publicVapidKey\n ): Promise<PushSubscription> {\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 {!string} b64PublicKey\n */\n usePublicVapidKey(b64PublicKey) {\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 return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\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 getTokenDetailsModel(): TokenDetailsModel {\n return this.tokenDetailsModel_;\n }\n\n getVapidDetailsModel(): VapidDetailsModel {\n return this.vapidDetailsModel_;\n }\n\n /**\n * @protected\n * @returns {IIDModel}\n */\n getIIDModel() {\n return this.iidModel_;\n }\n}\n"]}
{"version":3,"sources":["../src/controllers/controller-interface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;AAEb,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,uBAAuB,MAAM,mCAAmC,CAAC;AACxE,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,mBAAmB,MAAM,mCAAmC,CAAC;AAEpE,IAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAClD,oDAAoD;AACpD,MAAM,CAAC,IAAM,uBAAuB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;AAEzE;IASE;;;OAGG;IACH,6BAAY,GAAG;QAAf,iBAmBC;QAlBC,IAAI,CAAC,aAAa,GAAG,IAAI,YAAY,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QAE5E,EAAE,CAAC,CACD,CAAC,GAAG,CAAC,OAAO,CAAC,qBAAqB,CAAC;YACnC,OAAO,GAAG,CAAC,OAAO,CAAC,qBAAqB,CAAC,KAAK,QAChD,CAAC,CAAC,CAAC;YACD,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QAC9D,CAAC;QAED,IAAI,CAAC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IACF,6DAA6D;IAC7D,EAAE;IAEF;;;OAGG;IACH,yDAA2B,GAA3B,UAA4B,QAAQ;QAClC,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAChE,CAAC;IAED,EAAE;IACF,2EAA2E;IAC3E,qDAAqD;IACrD,EAAE;IAEF;;;OAGG;IACH,oCAAM,GAAN;QACE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;YACjB,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;YACvC,IAAI,CAAC,kBAAkB,CAAC,aAAa,EAAE;SACxC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,wDAA0B,GAA1B;QACE,MAAM,CAAE,YAAoB,CAAC,UAAU,CAAC;IAC1C,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED,kDAAoB,GAApB;QACE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,yCAAW,GAAX;QACE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IACH,0BAAC;AAAD,CAtWA,AAsWC,IAAA","file":"controller-interface.js","sourcesContent":["/**\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 '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport default class ControllerInterface {\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenDetailsModel_: TokenDetailsModel;\n private vapidDetailsModel_: VapidDetailsModel;\n private iidModel_: IIDModel;\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 (\n !app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'\n ) {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete();\n }\n\n /**\n * @export\n */\n getToken(): Promise<string | null> {\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 let swReg: ServiceWorkerRegistration;\n return this.getSWRegistration_()\n .then(reg => {\n swReg = reg;\n return this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(tokenDetails => {\n if (tokenDetails) {\n return this.manageExistingToken(tokenDetails, swReg);\n }\n return this.getNewToken(swReg);\n });\n }\n\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n private manageExistingToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n return this.isTokenStillValid(tokenDetails).then(isValid => {\n if (isValid) {\n const now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n } else {\n return this.updateToken(tokenDetails, swReg);\n }\n } else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n return this.getNewToken(swReg);\n });\n }\n });\n }\n\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n private isTokenStillValid(tokenDetails: Object): Promise<Boolean> {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(publicKey => {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n }\n\n private updateToken(\n tokenDetails: Object,\n swReg: ServiceWorkerRegistration\n ): Promise<string> {\n let publicVapidKey: Uint8Array;\n let updatedToken: string;\n let subscription: PushSubscription;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.updateToken(\n this.messagingSenderId_,\n tokenDetails['fcmToken'],\n tokenDetails['fcmPushSet'],\n subscription,\n publicVapidKey\n );\n })\n .catch(err => {\n return this.deleteToken(tokenDetails['fcmToken']).then(() => {\n throw err;\n });\n })\n .then(token => {\n updatedToken = token;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return updatedToken;\n });\n }\n\n private getNewToken(swReg: ServiceWorkerRegistration): Promise<string> {\n let publicVapidKey: Uint8Array;\n let subscription: PushSubscription;\n let tokenDetails: Object;\n return this.getPublicVapidKey_()\n .then(publicKey => {\n publicVapidKey = publicKey;\n return this.getPushSubscription(swReg, publicVapidKey);\n })\n .then(pushSubscription => {\n subscription = pushSubscription;\n return this.iidModel_.getToken(\n this.messagingSenderId_,\n subscription,\n publicVapidKey\n );\n })\n .then(iidTokenDetails => {\n tokenDetails = iidTokenDetails;\n const allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(() => {\n return this.vapidDetailsModel_.saveVapidDetails(\n swReg.scope,\n publicVapidKey\n );\n })\n .then(() => {\n return tokenDetails['token'];\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n deleteToken(token: string): Promise<Boolean> {\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(details => {\n return this.iidModel_.deleteToken(\n details['fcmSenderId'],\n details['fcmToken'],\n details['fcmPushSet']\n );\n })\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<ServiceWorkerRegistration> {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n getPublicVapidKey_(): Promise<Uint8Array> {\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 * Gets a PushSubscription for the current user.\n */\n getPushSubscription(\n swRegistration: ServiceWorkerRegistration,\n publicVapidKey: Uint8Array\n ): Promise<PushSubscription> {\n return swRegistration.pushManager.getSubscription().then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\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 {!string} b64PublicKey\n */\n usePublicVapidKey(b64PublicKey) {\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 return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\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 getTokenDetailsModel(): TokenDetailsModel {\n return this.tokenDetailsModel_;\n }\n\n getVapidDetailsModel(): VapidDetailsModel {\n return this.vapidDetailsModel_;\n }\n\n /**\n * @protected\n * @returns {IIDModel}\n */\n getIIDModel() {\n return this.iidModel_;\n }\n}\n"]}

@@ -102,9 +102,2 @@ import { FirebaseMessaging } from '@firebase/messaging-types';

/**
* Gets a PushSubscription for the current user.
* @private
* @param {ServiceWorkerRegistration} registration
* @return {Promise<PushSubscription>}
*/
getPushSubscription_(swRegistration: any, publicVapidKey: any): any;
/**
* This method will set up a message listener to handle

@@ -111,0 +104,0 @@ * events from the service worker that should trigger

@@ -321,22 +321,2 @@ /**

/**
* Gets a PushSubscription for the current user.
* @private
* @param {ServiceWorkerRegistration} registration
* @return {Promise<PushSubscription>}
*/
WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {
// Check for existing subscription first
var subscription;
var fcmTokenDetails;
return swRegistration.pushManager.getSubscription().then(function (subscription) {
if (subscription) {
return subscription;
}
return swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicVapidKey
});
});
};
/**
* This method will set up a message listener to handle

@@ -343,0 +323,0 @@ * events from the service worker that should trigger

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/controllers/window-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;;AAGb,OAAO,mBAAmB,MAAM,wBAAwB,CAAC;AACzD,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,SAAS,MA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CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBACrE,yBAAyB;gBACzB,MAAM,CAAC;YACT,CAAC;YAED,IAAM,iBAAiB,GAAG,KAAK,CAAC,IAAI,CAAC;YACrC,MAAM,CAAC,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBAChE,KAAK,iBAAiB,CAAC,YAAY,CAAC,iBAAiB,CAAC;gBACtD,KAAK,iBAAiB,CAAC,YAAY,CAAC,oBAAoB;oBACtD,IAAM,WAAW,GACf,iBAAiB,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;wBAC1B,KAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;oBAC1C,CAAC;oBACD,KAAK,CAAC;gBACR;oBACE,QAAQ;oBACR,KAAK,CAAC;YACV,CAAC;QACH,CAAC,EACD,KAAK,CACN,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,uCAAY,GAAZ;QACE,MAAM,CAAC,CACL,eAAe,IAAI,SAAS;YAC5B,aAAa,IAAI,MAAM;YACvB,cAAc,IAAI,MAAM;YACxB,OAAO,IAAI,MAAM;YACjB,yBAAyB,CAAC,SAAS,CAAC,cAAc,CAAC,kBAAkB,CAAC;YACtE,gBAAgB,CAAC,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CACpD,CAAC;IACJ,CAAC;IACH,uBAAC;AAAD,CAjaA,AAiaC,CAja6C,mBAAmB,GAiahE","file":"window-controller.js","sourcesContent":["/**\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 { FirebaseMessaging } from '@firebase/messaging-types';\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 FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface\n implements FirebaseMessaging {\n private registrationToUse_;\n private publicVapidKeyToUse_;\n private manifestCheckPromise_;\n private messageObserver_ = null;\n private onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n private tokenRefreshObserver_ = null;\n private onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\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 /**\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<string> | Promise<null>} 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_().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 = <HTMLAnchorElement>document.querySelector(\n 'link[rel=\"manifest\"]'\n );\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 })\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\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 async requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return;\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(\n this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED)\n );\n } else {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT)\n );\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(\n managePermissionResult\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 * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n usePublicVapidKey(publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(\n Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN\n );\n }\n\n const parsedKey = base64ToArrayBuffer(publicKey);\n\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(\n Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED\n );\n }\n\n this.publicVapidKeyToUse_ = parsedKey;\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<!ServiceWorkerRegistration>} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker =\n registration.installing || registration.waiting || registration.active;\n\n return new Promise<ServiceWorkerRegistration>((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<!ServiceWorkerRegistration>} 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\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION,\n {\n browserErrorMessage: err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration).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 will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n getPublicVapidKey_(): Promise<Uint8Array> {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\n }\n\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise<PushSubscription>}\n */\n getPushSubscription_(swRegistration, publicVapidKey) {\n // Check for existing subscription first\n let subscription;\n let fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\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(\n 'message',\n 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 =\n workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (this.messageObserver_) {\n this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n },\n false\n );\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 (\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n }\n}\n"]}
{"version":3,"sources":["../src/controllers/window-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,CAAC;;AAGb,OAAO,mBAAmB,MAAM,wBAAwB,CAAC;AACzD,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,iBAAiB,MAAM,+BAA+B,CAAC;AAC9D,OAAO,SAAS,MAAM,sBAAsB,CAAC;AAC7C,OAAO,uBAAuB,MAAM,mCAAmC,CAAC;AACxE,OAAO,UAAU,MAAM,uBAAuB,CAAC;AAC/C,OAAO,mBAAmB,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAIjD;IAA8C,4CAAmB;IAc/D;;;OAGG;IACH,0BAAY,GAAG;QAAf,YACE,kBAAM,GAAG,CAAC,SAsCX;QApDO,sBAAgB,GAAG,IAAI,CAAC;QACxB,gBAAU,GAAG,eAAe,CAAC,UAAA,QAAQ;YAC3C,KAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC,CAAC,CAAC;QACK,2BAAqB,GAAG,IAAI,CAAC;QAC7B,qBAAe,GAAG,eAAe,CAAC,UAAA,QAAQ;YAChD,KAAI,CAAC,qBAAqB,GAAG,QAAQ,CAAC;QACxC,CAAC,CAAC,CAAC;QASD;;;WAGG;QACH,KAAI,CAAC,kBAAkB,CAAC;QAExB;;;WAGG;QACH,KAAI,CAAC,qBAAqB,CAAC;QAE3B;;;WAGG;QACH,KAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAE7B;;;WAGG;QACH,KAAI,CAAC,UAAU,GAAG,eAAe,CAAC,UAAA,QAAQ;YACxC,KAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC,CAAC,CAAC;Q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AAiB,GAAG,KAAK,CAAC,IAAI,CAAC;YACrC,MAAM,CAAC,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;gBAChE,KAAK,iBAAiB,CAAC,YAAY,CAAC,iBAAiB,CAAC;gBACtD,KAAK,iBAAiB,CAAC,YAAY,CAAC,oBAAoB;oBACtD,IAAM,WAAW,GACf,iBAAiB,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oBACnD,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;wBAC1B,KAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;oBAC1C,CAAC;oBACD,KAAK,CAAC;gBACR;oBACE,QAAQ;oBACR,KAAK,CAAC;YACV,CAAC;QACH,CAAC,EACD,KAAK,CACN,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,uCAAY,GAAZ;QACE,MAAM,CAAC,CACL,eAAe,IAAI,SAAS;YAC5B,aAAa,IAAI,MAAM;YACvB,cAAc,IAAI,MAAM;YACxB,OAAO,IAAI,MAAM;YACjB,yBAAyB,CAAC,SAAS,CAAC,cAAc,CAAC,kBAAkB,CAAC;YACtE,gBAAgB,CAAC,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CACpD,CAAC;IACJ,CAAC;IACH,uBAAC;AAAD,CA3YA,AA2YC,CA3Y6C,mBAAmB,GA2YhE","file":"window-controller.js","sourcesContent":["/**\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 { FirebaseMessaging } from '@firebase/messaging-types';\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 FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface\n implements FirebaseMessaging {\n private registrationToUse_;\n private publicVapidKeyToUse_;\n private manifestCheckPromise_;\n private messageObserver_ = null;\n private onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n private tokenRefreshObserver_ = null;\n private onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\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 /**\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<string> | Promise<null>} 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_().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 = <HTMLAnchorElement>document.querySelector(\n 'link[rel=\"manifest\"]'\n );\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 })\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\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 async requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return;\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(\n this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED)\n );\n } else {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT)\n );\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(\n managePermissionResult\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 * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n usePublicVapidKey(publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(\n Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN\n );\n }\n\n const parsedKey = base64ToArrayBuffer(publicKey);\n\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(\n Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED\n );\n }\n\n this.publicVapidKeyToUse_ = parsedKey;\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<!ServiceWorkerRegistration>} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker =\n registration.installing || registration.waiting || registration.active;\n\n return new Promise<ServiceWorkerRegistration>((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<!ServiceWorkerRegistration>} 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\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION,\n {\n browserErrorMessage: err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration).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 will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n getPublicVapidKey_(): Promise<Uint8Array> {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\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(\n 'message',\n 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 =\n workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (this.messageObserver_) {\n this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n },\n false\n );\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 (\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n }\n}\n"]}
{
"name": "@firebase/messaging",
"version": "0.2.2-canary.9d00c6f",
"version": "0.2.2-canary.ab0faeb",
"description": "",

@@ -16,7 +16,7 @@ "author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)",

"peerDependencies": {
"@firebase/app": "0.1.10-canary.9d00c6f"
"@firebase/app": "0.1.10-canary.ab0faeb"
},
"dependencies": {
"@firebase/messaging-types": "0.1.2-canary.9d00c6f",
"@firebase/util": "0.1.10-canary.9d00c6f",
"@firebase/messaging-types": "0.1.2-canary.ab0faeb",
"@firebase/util": "0.1.10-canary.ab0faeb",
"tslib": "^1.9.0"

@@ -23,0 +23,0 @@ },