From 358e9f53167daffbd16442b0ac3bb3470dcf671e Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Wed, 16 Oct 2019 17:35:40 -0700 Subject: [PATCH 1/6] Migrate messaging to component framework --- packages/app-types/index.d.ts | 2 + packages/messaging/index.ts | 30 +++-- packages/messaging/package.json | 1 + .../src/controllers/base-controller.ts | 16 ++- .../src/controllers/sw-controller.ts | 5 +- .../src/controllers/window-controller.ts | 36 ++++-- .../src/models/clean-v1-undefined.ts | 16 ++- .../src/models/subscription-manager.ts | 17 ++- .../src/models/token-details-model.ts | 8 +- packages/messaging/test/constructor.test.ts | 16 ++- .../test/controller-delete-token.test.ts | 55 ++++++-- .../test/controller-get-token.test.ts | 68 ++++++++-- .../test/controller-interface.test.ts | 56 ++++++--- packages/messaging/test/get-sw-reg.test.ts | 46 +++++-- packages/messaging/test/index.test.ts | 49 +++++--- .../test/subscription-manager.test.ts | 42 +++++-- packages/messaging/test/sw-controller.test.ts | 88 +++++++------ .../test/testing-utils/make-fake-app.ts | 17 +-- .../test/testing-utils/make-fake-providers.ts | 28 +++++ .../test/token-details-model.test.ts | 44 ++++--- .../messaging/test/window-controller.test.ts | 118 +++++++++++++++--- 21 files changed, 571 insertions(+), 187 deletions(-) create mode 100644 packages/messaging/test/testing-utils/make-fake-providers.ts diff --git a/packages/app-types/index.d.ts b/packages/app-types/index.d.ts index 10b89b83bb9..eab147e16c8 100644 --- a/packages/app-types/index.d.ts +++ b/packages/app-types/index.d.ts @@ -1,3 +1,5 @@ +import { Provider } from '@firebase/component'; + /** * @license * Copyright 2017 Google Inc. diff --git a/packages/messaging/index.ts b/packages/messaging/index.ts index 82990883925..371d7ea9ff9 100644 --- a/packages/messaging/index.ts +++ b/packages/messaging/index.ts @@ -16,30 +16,40 @@ */ import firebase from '@firebase/app'; +import '@firebase/installations'; import { _FirebaseNamespace, - FirebaseServiceFactory + FirebaseService } from '@firebase/app-types/private'; import { FirebaseMessaging } from '@firebase/messaging-types'; - import { SwController } from './src/controllers/sw-controller'; import { WindowController } from './src/controllers/window-controller'; import { ErrorCode, errorFactory } from './src/models/errors'; +import { + Component, + ComponentType, + ComponentContainer +} from '@firebase/component'; export function registerMessaging(instance: _FirebaseNamespace): void { const messagingName = 'messaging'; - const factoryMethod: FirebaseServiceFactory = app => { + const factoryMethod = (container: ComponentContainer): FirebaseService => { + /* Dependencies */ + const app = container.getProvider('app').getImmediate(); + const installations = container.getProvider('installations').getImmediate(); + const analyticsProvider = container.getProvider('analytics-internal'); + if (!isSupported()) { throw errorFactory.create(ErrorCode.UNSUPPORTED_BROWSER); } if (self && 'ServiceWorkerGlobalScope' in self) { // Running in ServiceWorker context - return new SwController(app); + return new SwController(app, installations); } else { // Assume we are in the window context. - return new WindowController(app); + return new WindowController(app, installations, analyticsProvider); } }; @@ -47,10 +57,12 @@ export function registerMessaging(instance: _FirebaseNamespace): void { isSupported }; - instance.INTERNAL.registerService( - messagingName, - factoryMethod, - namespaceExports + instance.INTERNAL.registerComponent( + new Component( + messagingName, + factoryMethod, + ComponentType.PUBLIC + ).setServiceProps(namespaceExports) ); } diff --git a/packages/messaging/package.json b/packages/messaging/package.json index 0803a760915..8d1638a2e22 100644 --- a/packages/messaging/package.json +++ b/packages/messaging/package.json @@ -29,6 +29,7 @@ "@firebase/installations": "0.3.2", "@firebase/messaging-types": "0.3.4", "@firebase/util": "0.2.31", + "@firebase/component": "0.1.0", "tslib": "1.10.0" }, "devDependencies": { diff --git a/packages/messaging/src/controllers/base-controller.ts b/packages/messaging/src/controllers/base-controller.ts index 7a81f49def3..55643ad35b1 100644 --- a/packages/messaging/src/controllers/base-controller.ts +++ b/packages/messaging/src/controllers/base-controller.ts @@ -33,6 +33,7 @@ import { ErrorCode, errorFactory } from '../models/errors'; import { SubscriptionManager } from '../models/subscription-manager'; import { TokenDetailsModel } from '../models/token-details-model'; import { VapidDetailsModel } from '../models/vapid-details-model'; +import { FirebaseInstallations } from '@firebase/installations-types'; export type BgMessageHandler = ( payload: MessagePayload @@ -47,7 +48,10 @@ export abstract class BaseController implements FirebaseMessaging { private readonly vapidDetailsModel = new VapidDetailsModel(); private readonly subscriptionManager = new SubscriptionManager(); - constructor(readonly app: FirebaseApp) { + constructor( + readonly app: FirebaseApp, + private readonly installations: FirebaseInstallations + ) { if ( !app.options.messagingSenderId || typeof app.options.messagingSenderId !== 'string' @@ -59,7 +63,7 @@ export abstract class BaseController implements FirebaseMessaging { delete: () => this.delete() }; - this.tokenDetailsModel = new TokenDetailsModel(app); + this.tokenDetailsModel = new TokenDetailsModel(app, installations); } async getToken(): Promise { @@ -148,6 +152,7 @@ export abstract class BaseController implements FirebaseMessaging { const updatedToken = await this.subscriptionManager.updateToken( tokenDetails, this.app, + this.installations, pushSubscription, publicVapidKey ); @@ -182,6 +187,7 @@ export abstract class BaseController implements FirebaseMessaging { ): Promise { const newToken = await this.subscriptionManager.getToken( this.app, + this.installations, pushSubscription, publicVapidKey ); @@ -228,7 +234,11 @@ export abstract class BaseController implements FirebaseMessaging { */ private async deleteTokenFromDB(token: string): Promise { const tokenDetails = await this.tokenDetailsModel.deleteToken(token); - await this.subscriptionManager.deleteToken(this.app, tokenDetails); + await this.subscriptionManager.deleteToken( + this.app, + this.installations, + tokenDetails + ); } // Visible for testing diff --git a/packages/messaging/src/controllers/sw-controller.ts b/packages/messaging/src/controllers/sw-controller.ts index 5667cf7a63c..bbd61180cc1 100644 --- a/packages/messaging/src/controllers/sw-controller.ts +++ b/packages/messaging/src/controllers/sw-controller.ts @@ -30,6 +30,7 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController, BgMessageHandler } from './base-controller'; +import { FirebaseInstallations } from '@firebase/installations-types'; // Let TS know that this is a service worker declare const self: ServiceWorkerGlobalScope; @@ -39,8 +40,8 @@ const FCM_MSG = 'FCM_MSG'; export class SwController extends BaseController { private bgMessageHandler: BgMessageHandler | null = null; - constructor(app: FirebaseApp) { - super(app); + constructor(app: FirebaseApp, installations: FirebaseInstallations) { + super(app, installations); self.addEventListener('push', e => { this.onPush(e); diff --git a/packages/messaging/src/controllers/window-controller.ts b/packages/messaging/src/controllers/window-controller.ts index 7f990ad160d..d96659609bc 100644 --- a/packages/messaging/src/controllers/window-controller.ts +++ b/packages/messaging/src/controllers/window-controller.ts @@ -39,6 +39,9 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController } from './base-controller'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider } from '@firebase/component'; +import { FirebaseInstallations } from '@firebase/installations-types'; export class WindowController extends BaseController { private registrationToUse: ServiceWorkerRegistration | null = null; @@ -63,8 +66,12 @@ export class WindowController extends BaseController { /** * A service that provides a MessagingService instance. */ - constructor(app: FirebaseApp) { - super(app); + constructor( + app: FirebaseApp, + installations: FirebaseInstallations, + readonly analyticsProvider: Provider + ) { + super(app, installations); this.setupSWMessageListener_(); } @@ -308,16 +315,23 @@ export class WindowController extends BaseController { // This message has a campaign id, meaning it was sent using the FN Console. // Analytics is enabled on this message, so we should log it. const eventType = getEventType(firebaseMessagingType); - (this.app as _FirebaseApp).INTERNAL.analytics.logEvent( - eventType, - /* eslint-disable camelcase */ - { - message_name: data[FN_CAMPAIGN_NAME], - message_id: data[FN_CAMPAIGN_ID], - message_time: data[FN_CAMPAIGN_TIME], - message_device_time: Math.floor(Date.now() / 1000) + this.analyticsProvider.get().then( + analytics => { + analytics.logEvent( + eventType, + /* eslint-disable camelcase */ + { + message_name: data[FN_CAMPAIGN_NAME], + message_id: data[FN_CAMPAIGN_ID], + message_time: data[FN_CAMPAIGN_TIME], + message_device_time: Math.floor(Date.now() / 1000) + } + /* eslint-enable camelcase */ + ); + }, + () => { + /* it will never reject */ } - /* eslint-enable camelcase */ ); } }, diff --git a/packages/messaging/src/models/clean-v1-undefined.ts b/packages/messaging/src/models/clean-v1-undefined.ts index 7952d338934..7afa33caa49 100644 --- a/packages/messaging/src/models/clean-v1-undefined.ts +++ b/packages/messaging/src/models/clean-v1-undefined.ts @@ -29,11 +29,16 @@ import { SubscriptionManager } from './subscription-manager'; import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseInstallations } from '@firebase/installations-types'; const OLD_DB_NAME = 'undefined'; const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store'; -function handleDb(db: IDBDatabase, app: FirebaseApp): void { +function handleDb( + db: IDBDatabase, + app: FirebaseApp, + installations: FirebaseInstallations +): void { if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) { // We found a database with the name 'undefined', but our expected object // store isn't defined. @@ -59,7 +64,7 @@ function handleDb(db: IDBDatabase, app: FirebaseApp): void { const tokenDetails = cursor.value; // eslint-disable-next-line @typescript-eslint/no-floating-promises - subscriptionManager.deleteToken(app, tokenDetails); + subscriptionManager.deleteToken(app, installations, tokenDetails); cursor.continue(); } else { @@ -69,13 +74,16 @@ function handleDb(db: IDBDatabase, app: FirebaseApp): void { }; } -export function cleanV1(app: FirebaseApp): void { +export function cleanV1( + app: FirebaseApp, + installations: FirebaseInstallations +): void { const request: IDBOpenDBRequest = indexedDB.open(OLD_DB_NAME); request.onerror = _event => { // NOOP - Nothing we can do. }; request.onsuccess = _event => { const db = request.result; - handleDb(db, app); + handleDb(db, app, installations); }; } diff --git a/packages/messaging/src/models/subscription-manager.ts b/packages/messaging/src/models/subscription-manager.ts index 54c871d13c6..e39b30118be 100644 --- a/packages/messaging/src/models/subscription-manager.ts +++ b/packages/messaging/src/models/subscription-manager.ts @@ -20,8 +20,8 @@ import { isArrayBufferEqual } from '../helpers/is-array-buffer-equal'; import { ErrorCode, errorFactory } from './errors'; import { DEFAULT_PUBLIC_VAPID_KEY, ENDPOINT } from './fcm-details'; import { FirebaseApp } from '@firebase/app-types'; -import '@firebase/installations'; import { TokenDetails } from '../interfaces/token-details'; +import { FirebaseInstallations } from '@firebase/installations-types'; interface ApiResponse { token?: string; @@ -40,10 +40,11 @@ interface TokenRequestBody { export class SubscriptionManager { async getToken( app: FirebaseApp, + installations: FirebaseInstallations, subscription: PushSubscription, vapidKey: Uint8Array ): Promise { - const headers = await getHeaders(app); + const headers = await getHeaders(app, installations); const body = getBody(subscription, vapidKey); const subscribeOptions = { @@ -82,10 +83,11 @@ export class SubscriptionManager { async updateToken( tokenDetails: TokenDetails, app: FirebaseApp, + installations: FirebaseInstallations, subscription: PushSubscription, vapidKey: Uint8Array ): Promise { - const headers = await getHeaders(app); + const headers = await getHeaders(app, installations); const body = getBody(subscription, vapidKey); const updateOptions = { @@ -123,10 +125,11 @@ export class SubscriptionManager { async deleteToken( app: FirebaseApp, + installations: FirebaseInstallations, tokenDetails: TokenDetails ): Promise { // TODO: Add FIS header - const headers = await getHeaders(app); + const headers = await getHeaders(app, installations); const unsubscribeOptions = { method: 'DELETE', @@ -157,8 +160,10 @@ function getEndpoint(app: FirebaseApp): string { return `${ENDPOINT}/projects/${app.options.projectId!}/registrations`; } -async function getHeaders(app: FirebaseApp): Promise { - const installations = app.installations(); +async function getHeaders( + app: FirebaseApp, + installations: FirebaseInstallations +): Promise { const authToken = await installations.getToken(); return new Headers({ diff --git a/packages/messaging/src/models/token-details-model.ts b/packages/messaging/src/models/token-details-model.ts index 6ae682e54c6..e4e9c9c6f13 100644 --- a/packages/messaging/src/models/token-details-model.ts +++ b/packages/messaging/src/models/token-details-model.ts @@ -21,13 +21,17 @@ import { cleanV1 } from './clean-v1-undefined'; import { DbInterface } from './db-interface'; import { ErrorCode, errorFactory } from './errors'; import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseInstallations } from '@firebase/installations-types'; export class TokenDetailsModel extends DbInterface { protected readonly dbName: string = 'fcm_token_details_db'; protected readonly dbVersion: number = 4; protected readonly objectStoreName: string = 'fcm_token_object_Store'; - constructor(private readonly app: FirebaseApp) { + constructor( + private readonly app: FirebaseApp, + private readonly installations: FirebaseInstallations + ) { super(); } @@ -57,7 +61,7 @@ export class TokenDetailsModel extends DbInterface { // Prior to version 2, we were using either 'fcm_token_details_db' // or 'undefined' as the database name due to bug in the SDK // So remove the old tokens and databases. - cleanV1(this.app); + cleanV1(this.app, this.installations); } case 2: { diff --git a/packages/messaging/test/constructor.test.ts b/packages/messaging/test/constructor.test.ts index 4f3f371720c..37945324c90 100644 --- a/packages/messaging/test/constructor.test.ts +++ b/packages/messaging/test/constructor.test.ts @@ -22,9 +22,15 @@ import { SwController } from '../src/controllers/sw-controller'; import { WindowController } from '../src/controllers/window-controller'; import { ErrorCode } from '../src/models/errors'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; +import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; describe('Firebase Messaging > new *Controller()', () => { + const analyticsProvider = makeFakeAnalyticsProvider(); + const installations = makeFakeInstallations(); it('should handle bad input', () => { const badInputs = [ makeFakeApp({ @@ -45,8 +51,8 @@ describe('Firebase Messaging > new *Controller()', () => { ]; badInputs.forEach(badInput => { try { - new WindowController(badInput); - new SwController(badInput); + new WindowController(badInput, installations, analyticsProvider); + new SwController(badInput, installations); assert.fail( `Bad Input should have thrown: ${JSON.stringify(badInput)}` @@ -60,7 +66,7 @@ describe('Firebase Messaging > new *Controller()', () => { it('should be able to handle good input', () => { const app = makeFakeApp(); - new WindowController(app); - new SwController(app); + new WindowController(app, installations, analyticsProvider); + new SwController(app, installations); }); }); diff --git a/packages/messaging/test/controller-delete-token.test.ts b/packages/messaging/test/controller-delete-token.test.ts index 5e6f3c47d52..8c37bb64a26 100644 --- a/packages/messaging/test/controller-delete-token.test.ts +++ b/packages/messaging/test/controller-delete-token.test.ts @@ -26,16 +26,25 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { deleteDatabase } from './testing-utils/db-helper'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { TokenDetails } from '../src/interfaces/token-details'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider } from '@firebase/component'; +import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; +import { FirebaseInstallations } from '@firebase/installations-types'; let FAKE_SUBSCRIPTION: PushSubscription; let EXAMPLE_TOKEN_SAVE: TokenDetails; describe('Firebase Messaging > *Controller.deleteToken()', () => { let app: FirebaseApp; + let installations: FirebaseInstallations; + let analyticsProvider: Provider; let messagingService: WindowController | SwController; function configureRegistrationMocks( @@ -80,6 +89,8 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { app = makeFakeApp({ messagingSenderId: EXAMPLE_TOKEN_SAVE.fcmSenderId }); + installations = makeFakeInstallations(); + analyticsProvider = makeFakeAnalyticsProvider(); }); afterEach(async () => { @@ -93,7 +104,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { }); it('should handle no token to delete', () => { - messagingService = new WindowController(app); + messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(undefined as any).then( () => { throw new Error('Expected error to be thrown.'); @@ -116,7 +131,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new WindowController(app); + messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -137,7 +156,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new WindowController(app); + messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -166,7 +189,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass(app); + messagingService = new serviceClass( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -195,7 +222,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass(app); + messagingService = new serviceClass( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -229,7 +260,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { throw new Error(errorMsg); }); - messagingService = new serviceClass(app); + messagingService = new serviceClass( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -262,7 +297,11 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass(app); + messagingService = new serviceClass( + app, + installations, + analyticsProvider + ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); }); diff --git a/packages/messaging/test/controller-get-token.test.ts b/packages/messaging/test/controller-get-token.test.ts index b91e06f6f9c..84fb9fe93ed 100644 --- a/packages/messaging/test/controller-get-token.test.ts +++ b/packages/messaging/test/controller-get-token.test.ts @@ -31,9 +31,16 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider } from '@firebase/component'; +import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; +import { FirebaseInstallations } from '@firebase/installations-types'; const ONE_DAY = 24 * 60 * 60 * 1000; @@ -74,6 +81,8 @@ describe('Firebase Messaging > *Controller.getToken()', () => { let EXAMPLE_EXPIRED_TOKEN_DETAILS: TokenDetails; let app: FirebaseApp; + let installations: FirebaseInstallations; + let analyticsProvider: Provider; beforeEach(() => { now = Date.now(); @@ -127,6 +136,9 @@ describe('Firebase Messaging > *Controller.getToken()', () => { app = makeFakeApp({ messagingSenderId: EXAMPLE_SENDER_ID }); + installations = makeFakeInstallations(); + + analyticsProvider = makeFakeAnalyticsProvider(); }); afterEach(() => { @@ -142,7 +154,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { Promise.reject('No Service Worker') ); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); try { await messagingService.getToken(); throw new Error('Expected getToken to throw '); @@ -166,7 +182,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { notificationStub.onCall(3).returns('default'); return servicesToTest.reduce(async (chain, serviceClass) => { - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); stub(serviceClass.prototype, 'getPublicVapidKey_').callsFake(() => Promise.resolve(DEFAULT_PUBLIC_VAPID_KEY) ); @@ -213,7 +233,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { 'getTokenDetailsFromSWScope' ).callsFake(() => Promise.resolve(details)); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const token = await serviceInstance.getToken(); assert.equal(details.fcmToken, token); }); @@ -239,7 +263,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { () => Promise.resolve(EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID) ); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID.fcmToken, token); }); @@ -279,7 +307,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { async () => {} ); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_FCM_TOKEN, token); }); @@ -332,7 +364,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { 'saveTokenDetails' ).callsFake(async () => {}); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const token = await serviceInstance.getToken(); assert.equal('example-token', token); @@ -423,7 +459,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { 'getTokenDetailsFromSWScope' ).callsFake(() => Promise.resolve(details)); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const token = await serviceInstance.getToken(); // make sure we call getToken and retrieve the new token. assert.equal('new-token', token); @@ -472,7 +512,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { Promise.resolve(subscription) ); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); const defaultVAPIDToken = await serviceInstance.getToken(); assert.equal( defaultVAPIDToken, @@ -559,7 +603,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { async () => {} ); - const serviceInstance = new serviceClass(app); + const serviceInstance = new serviceClass( + app, + installations, + analyticsProvider + ); try { await serviceInstance.getToken(); throw new Error('Expected error to be thrown.'); diff --git a/packages/messaging/test/controller-interface.test.ts b/packages/messaging/test/controller-interface.test.ts index cc7cc97a2f8..4544623ecc9 100644 --- a/packages/messaging/test/controller-interface.test.ts +++ b/packages/messaging/test/controller-interface.test.ts @@ -27,9 +27,16 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider, ComponentContainer } from '@firebase/component'; +import { FirebaseInstallations } from '@firebase/installations-types'; + const controllersToTest = [WindowController, SwController]; /** @@ -48,11 +55,18 @@ class MockBaseController extends BaseController { describe('Firebase Messaging > *BaseController', () => { let app: FirebaseApp; + let installations: FirebaseInstallations; + let analyticsProvider: Provider; beforeEach(() => { app = makeFakeApp({ messagingSenderId: '12345' }); + installations = makeFakeInstallations(); + analyticsProvider = new Provider( + 'analytics-interop', + new ComponentContainer('test') + ); }); afterEach(() => { @@ -61,7 +75,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('INTERNAL.delete()', () => { it('should call delete()', async () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); const sinonSpy = spy(controller, 'delete'); await controller.INTERNAL.delete(); expect(sinonSpy.callCount).to.equal(1); @@ -70,7 +84,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('requestPermission()', () => { it(`should throw`, async () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { await controller.requestPermission(); @@ -93,7 +107,11 @@ describe('Firebase Messaging > *BaseController', () => { } }); - const controller = new controllerInTest(app); + const controller = new controllerInTest( + app, + installations, + analyticsProvider + ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then( @@ -113,7 +131,11 @@ describe('Firebase Messaging > *BaseController', () => { getSubscription: async () => exampleSubscription }); - const controller = new controllerInTest(app); + const controller = new controllerInTest( + app, + installations, + analyticsProvider + ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then(subscription => { @@ -136,7 +158,11 @@ describe('Firebase Messaging > *BaseController', () => { } }); - const controller = new controllerInTest(app); + const controller = new controllerInTest( + app, + installations, + analyticsProvider + ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then(subscription => { @@ -148,7 +174,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('useServiceWorker()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { controller.useServiceWorker(null as any); @@ -162,7 +188,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('usePublicVapidKey()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { controller.usePublicVapidKey(null as any); @@ -176,7 +202,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('onMessage()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { controller.onMessage(null as any, null as any, null as any); @@ -190,7 +216,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('onTokenRefresh()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { controller.onTokenRefresh(null as any, null as any, null as any); @@ -204,7 +230,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('setBackgroundMessageHandler()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); let thrownError; try { controller.setBackgroundMessageHandler(null as any); @@ -219,7 +245,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getNotificationPermission_', () => { it('should return current permission', () => { stub(Notification as any, 'permission').value('test'); - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); const result = controller.getNotificationPermission_(); expect(result).to.equal('test'); }); @@ -227,7 +253,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getTokenDetailsModel', () => { it('should return an instance of TokenDetailsModel', () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); const result = controller.getTokenDetailsModel(); expect(result).to.be.instanceof(TokenDetailsModel); }); @@ -235,7 +261,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getVapidDetailsModel', () => { it('should return an instance of VapidDetailsModel', () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); const result = controller.getVapidDetailsModel(); expect(result).to.be.instanceof(VapidDetailsModel); }); @@ -243,7 +269,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getIidModel', () => { it('should return an instance of IidModel', () => { - const controller = new MockBaseController(app); + const controller = new MockBaseController(app, installations); const result = controller.getSubscriptionManager(); expect(result).to.be.instanceof(SubscriptionManager); }); diff --git a/packages/messaging/test/get-sw-reg.test.ts b/packages/messaging/test/get-sw-reg.test.ts index eebd782e061..e04142113e3 100644 --- a/packages/messaging/test/get-sw-reg.test.ts +++ b/packages/messaging/test/get-sw-reg.test.ts @@ -21,14 +21,20 @@ import { SwController } from '../src/controllers/sw-controller'; import { WindowController } from '../src/controllers/window-controller'; import { ErrorCode } from '../src/models/errors'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; +import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; const EXAMPLE_SENDER_ID = '1234567890'; const app = makeFakeApp({ messagingSenderId: EXAMPLE_SENDER_ID }); +const installations = makeFakeInstallations(); +const analyticsProvider = makeFakeAnalyticsProvider(); describe('Firebase Messaging > *Controller.getSWReg_()', () => { const mockWindowRegistration = ( @@ -62,7 +68,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(activatedRegistration); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService .getSWRegistration_() .then(registration => { @@ -82,7 +92,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const fakeReg = makeFakeSWReg(); mockWindowRegistration(fakeReg); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.getSWRegistration_().then( () => { throw new Error('Expected this error to throw due to no SW.'); @@ -97,7 +111,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const fakeReg = makeFakeSWReg(); (self as any).registration = fakeReg; - const messagingService = new SwController(app); + const messagingService = new SwController(app, installations); return messagingService .getSWRegistration_() .then(registration => { @@ -119,7 +133,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { throw new Error(errorMsg); }); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.getSWRegistration_().then( () => { throw new Error('Expect getSWRegistration_ to reject.'); @@ -140,7 +158,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { }); mockWindowRegistration(redundantRegistration); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); @@ -166,7 +188,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const slowRedundantRegistration = makeFakeSWReg('installing', swValue); mockWindowRegistration(slowRedundantRegistration); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); @@ -192,7 +218,11 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const slowRedundantRegistration = makeFakeSWReg('waiting', swValue); mockWindowRegistration(slowRedundantRegistration); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); diff --git a/packages/messaging/test/index.test.ts b/packages/messaging/test/index.test.ts index d3146ec1f64..012c9b20118 100644 --- a/packages/messaging/test/index.test.ts +++ b/packages/messaging/test/index.test.ts @@ -21,7 +21,7 @@ import { stub, restore, SinonStub } from 'sinon'; import { FirebaseApp } from '@firebase/app-types'; import { _FirebaseNamespace, - FirebaseServiceFactory + FirebaseService } from '@firebase/app-types/private'; import { registerMessaging } from '../index'; @@ -29,17 +29,26 @@ import { ErrorCode } from '../src/models/errors'; import { SwController } from '../src/controllers/sw-controller'; import { WindowController } from '../src/controllers/window-controller'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; +import { + InstanceFactory, + ComponentContainer, + Component, + ComponentType +} from '@firebase/component'; describe('Firebase Messaging > registerMessaging', () => { - let registerService: SinonStub; + let registerComponent: SinonStub; let fakeFirebase: _FirebaseNamespace; beforeEach(() => { - registerService = stub(); + registerComponent = stub(); fakeFirebase = { - INTERNAL: { registerService } + INTERNAL: { registerComponent } } as any; }); @@ -47,28 +56,40 @@ describe('Firebase Messaging > registerMessaging', () => { restore(); }); - it('calls registerService', () => { + it('calls registerComponent', () => { registerMessaging(fakeFirebase); - expect(registerService.callCount).to.equal(1); + expect(registerComponent.callCount).to.equal(1); }); describe('factoryMethod', () => { - let factoryMethod: FirebaseServiceFactory; + let factoryMethod: InstanceFactory; let fakeApp: FirebaseApp; + let fakeContainer: ComponentContainer; beforeEach(() => { registerMessaging(fakeFirebase); - factoryMethod = registerService.getCall(0).args[1]; + factoryMethod = registerComponent.getCall(0).args[0].instanceFactory; fakeApp = makeFakeApp({ messagingSenderId: '1234567890' }); + fakeContainer = new ComponentContainer('test'); + fakeContainer.addComponent( + new Component('app', () => fakeApp, ComponentType.PUBLIC) + ); + fakeContainer.addComponent( + new Component( + 'installations', + () => makeFakeInstallations(), + ComponentType.PUBLIC + ) + ); }); describe('isSupported', () => { it('is a namespace export', () => { - const namespaceExports = registerService.getCall(0).args[2]; - expect(namespaceExports.isSupported).to.be.a('function'); + const component = registerComponent.getCall(0).args[0]; + expect(component.serviceProps.isSupported).to.be.a('function'); }); }); @@ -84,7 +105,7 @@ describe('Firebase Messaging > registerMessaging', () => { }); it('returns a SwController', () => { - const firebaseService = factoryMethod(fakeApp); + const firebaseService = factoryMethod(fakeContainer); expect(firebaseService).to.be.instanceOf(SwController); }); }); @@ -95,7 +116,7 @@ describe('Firebase Messaging > registerMessaging', () => { stub(window, 'navigator').value({}); try { - factoryMethod(fakeApp); + factoryMethod(fakeContainer); } catch (e) { expect(e.code).to.equal('messaging/' + ErrorCode.UNSUPPORTED_BROWSER); return; @@ -104,7 +125,7 @@ describe('Firebase Messaging > registerMessaging', () => { }); it('returns a WindowController', () => { - const firebaseService = factoryMethod(fakeApp); + const firebaseService = factoryMethod(fakeContainer); expect(firebaseService).to.be.instanceOf(WindowController); }); }); diff --git a/packages/messaging/test/subscription-manager.test.ts b/packages/messaging/test/subscription-manager.test.ts index d4dda7ae118..191d91e78b2 100644 --- a/packages/messaging/test/subscription-manager.test.ts +++ b/packages/messaging/test/subscription-manager.test.ts @@ -24,9 +24,13 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { fetchMock } from './testing-utils/mock-fetch'; import { FirebaseApp } from '@firebase/app-types'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { TokenDetails } from '../src/interfaces/token-details'; +import { FirebaseInstallations } from '@firebase/installations-types'; // prettier-ignore const appPubKey = new Uint8Array([ @@ -40,12 +44,14 @@ function getDefaultPublicKey(): Uint8Array { describe('Firebase Messaging > SubscriptionManager', () => { let app: FirebaseApp; + let installations: FirebaseInstallations; let subscription: PushSubscription; let tokenDetails: TokenDetails; let subscriptionManager: SubscriptionManager; beforeEach(() => { app = makeFakeApp(); + installations = makeFakeInstallations(); subscription = makeFakeSubscription(); tokenDetails = { swScope: '/example-scope', @@ -77,6 +83,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { ); const token = await subscriptionManager.getToken( app, + installations, subscription, appPubKey ); @@ -93,6 +100,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { ); const token = await subscriptionManager.getToken( app, + installations, subscription, getDefaultPublicKey() ); @@ -106,7 +114,12 @@ describe('Firebase Messaging > SubscriptionManager', () => { const errorMsg = 'invalid token'; stub(window, 'fetch').returns(fetchMock.jsonError(400, errorMsg)); try { - await subscriptionManager.getToken(app, subscription, appPubKey); + await subscriptionManager.getToken( + app, + installations, + subscription, + appPubKey + ); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.message).to.include(errorMsg); @@ -116,7 +129,12 @@ describe('Firebase Messaging > SubscriptionManager', () => { it('handles fetch errors, HTML response returned', async () => { stub(window, 'fetch').returns(fetchMock.htmlError(400, 'html-response')); try { - await subscriptionManager.getToken(app, subscription, appPubKey); + await subscriptionManager.getToken( + app, + installations, + subscription, + appPubKey + ); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_SUBSCRIBE_FAILED); @@ -129,7 +147,12 @@ describe('Firebase Messaging > SubscriptionManager', () => { fetchMock.jsonOk(JSON.stringify(mockInvalidResponse)) ); try { - await subscriptionManager.getToken(app, subscription, appPubKey); + await subscriptionManager.getToken( + app, + installations, + subscription, + appPubKey + ); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.message).to.include( @@ -148,6 +171,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { const res = await subscriptionManager.updateToken( tokenDetails, app, + installations, subscription, appPubKey ); @@ -163,6 +187,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { const res = await subscriptionManager.updateToken( tokenDetails, app, + installations, subscription, getDefaultPublicKey() ); @@ -181,6 +206,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { await subscriptionManager.updateToken( tokenDetails, app, + installations, subscription, appPubKey ); @@ -196,6 +222,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { await subscriptionManager.updateToken( tokenDetails, app, + installations, subscription, appPubKey ); @@ -212,6 +239,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { await subscriptionManager.updateToken( tokenDetails, app, + installations, subscription, appPubKey ); @@ -225,7 +253,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { describe('deleteToken', () => { it('deletes on valid request', async () => { stub(window, 'fetch').returns(fetchMock.jsonOk('{}')); - await subscriptionManager.deleteToken(app, tokenDetails); + await subscriptionManager.deleteToken(app, installations, tokenDetails); }); it('handles fetch errors', async () => { @@ -234,7 +262,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { stub(window, 'fetch').returns(fetchMock.jsonError(400, errorMsg)); try { - await subscriptionManager.deleteToken(app, tokenDetails); + await subscriptionManager.deleteToken(app, installations, tokenDetails); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); @@ -245,7 +273,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { const stubbedFetch = stub(window, 'fetch'); stubbedFetch.returns(fetchMock.htmlError(404, 'html-response')); try { - await subscriptionManager.deleteToken(app, tokenDetails); + await subscriptionManager.deleteToken(app, installations, tokenDetails); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); diff --git a/packages/messaging/test/sw-controller.test.ts b/packages/messaging/test/sw-controller.test.ts index 5a5bec3ee8e..4f06234b1ed 100644 --- a/packages/messaging/test/sw-controller.test.ts +++ b/packages/messaging/test/sw-controller.test.ts @@ -26,19 +26,24 @@ import { stub, restore, spy, SinonSpy } from 'sinon'; import { FirebaseApp } from '@firebase/app-types'; import { FirebaseError } from '@firebase/util'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { SwController } from '../src/controllers/sw-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; +import { FirebaseInstallations } from '@firebase/installations-types'; const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; describe('Firebase Messaging > *SwController', () => { let app: FirebaseApp; + let installations: FirebaseInstallations; beforeEach(() => { // When trying to stub self.clients self.registration, Sinon complains that @@ -58,6 +63,7 @@ describe('Firebase Messaging > *SwController', () => { app = makeFakeApp({ messagingSenderId: '12345' }); + installations = makeFakeInstallations(); }); afterEach(() => { @@ -69,7 +75,7 @@ describe('Firebase Messaging > *SwController', () => { describe('onPush', () => { it('should handle a push event with no data', async () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); const waitUntilSpy = spy(); swController.onPush({ waitUntil: waitUntilSpy, @@ -80,7 +86,7 @@ describe('Firebase Messaging > *SwController', () => { }); it('should handle a push event where .json() throws', async () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); const waitUntilSpy = spy(); swController.onPush({ waitUntil: waitUntilSpy, @@ -102,7 +108,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -124,7 +130,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -148,7 +154,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.setBackgroundMessageHandler((() => {}) as any); swController.onPush({ waitUntil: waitUntilSpy, @@ -171,7 +177,7 @@ describe('Firebase Messaging > *SwController', () => { ); const showNotificationStub = spy(registration, 'showNotification'); - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -209,7 +215,7 @@ describe('Firebase Messaging > *SwController', () => { icon: '/images/test-icon.png' }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -277,7 +283,7 @@ describe('Firebase Messaging > *SwController', () => { ] }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -311,7 +317,7 @@ describe('Firebase Messaging > *SwController', () => { const payloadData = {}; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.setBackgroundMessageHandler(bgMessageHandlerSpy); swController.onPush({ waitUntil: waitUntilSpy, @@ -333,7 +339,7 @@ describe('Firebase Messaging > *SwController', () => { async () => false ); - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -349,7 +355,7 @@ describe('Firebase Messaging > *SwController', () => { describe('setBackgroundMessageHandler', () => { it('should throw on a non-function input', () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); let thrownError: FirebaseError | undefined; try { swController.setBackgroundMessageHandler('' as any); @@ -378,7 +384,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -409,7 +415,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -444,7 +450,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.hasVisibleClients_(); expect(result).to.equal(true); }); @@ -467,7 +473,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -487,7 +493,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.getWindowClient_('/test-url'); expect(result).to.equal(null); }); @@ -515,7 +521,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.getWindowClient_('/test-url'); expect(result).to.equal(null); }); @@ -547,7 +553,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const result = await swController.getWindowClient_(matchingClient.url); expect(result).to.equal(matchingClient); }); @@ -560,7 +566,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); @@ -574,7 +580,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); @@ -590,7 +596,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); @@ -612,7 +618,7 @@ describe('Firebase Messaging > *SwController', () => { stopImmediatePropagation: spy(), action: 'action1' }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); @@ -631,7 +637,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); @@ -653,7 +659,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onNotificationClick(event); await event.waitUntil.getCall(0).args[0]; @@ -712,7 +718,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); stub(swController, 'getWindowClient_').callsFake(async () => null); @@ -739,7 +745,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); stub(swController, 'getWindowClient_').callsFake(async () => null); const attemptToMessageClientStub = stub( @@ -782,7 +788,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); stub(swController, 'getWindowClient_').callsFake( async () => fakeWindowClient as WindowClient @@ -818,14 +824,14 @@ describe('Firebase Messaging > *SwController', () => { describe('getNotificationData_', () => { it('should return nothing for no payload', () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); expect(swController.getNotificationData_(undefined as any)).to.equal( undefined ); }); it('adds message payload to data.FCM_MSG without replacing user defined data', () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); const msgPayload = { notification: { title: 'Hello World', @@ -852,7 +858,7 @@ describe('Firebase Messaging > *SwController', () => { describe('attemptToMessageClient_', () => { it('should reject when no window client provided', () => { - const swController = new SwController(app); + const swController = new SwController(app, installations); return swController.attemptToMessageClient_(null as any, {} as any).then( () => { throw new Error('Expected error to be thrown'); @@ -869,7 +875,7 @@ describe('Firebase Messaging > *SwController', () => { const client: any = { postMessage: spy() }; - const swController = new SwController(app); + const swController = new SwController(app, installations); await swController.attemptToMessageClient_(client, msg); expect(client.postMessage.callCount).to.equal(1); expect(client.postMessage.getCall(0).args[0]).to.equal(msg); @@ -884,7 +890,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const payload = {}; @@ -904,7 +910,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app); + const swController = new SwController(app, installations); const attemptToMessageClientStub = stub( swController, 'attemptToMessageClient_' @@ -943,7 +949,7 @@ describe('Firebase Messaging > *SwController', () => { const onPushStub = stub(SwController.prototype, 'onPush'); const pushEvent = new Event('push'); - new SwController(app); + new SwController(app, installations); expect(listeners['push']).to.exist; listeners['push'](pushEvent); @@ -960,7 +966,7 @@ describe('Firebase Messaging > *SwController', () => { const onSubChangeStub = stub(SwController.prototype, 'onSubChange'); const pushEvent = new Event('pushsubscriptionchange'); - new SwController(app); + new SwController(app, installations); expect(listeners['pushsubscriptionchange']).to.exist; listeners['pushsubscriptionchange'](pushEvent); @@ -986,7 +992,7 @@ describe('Firebase Messaging > *SwController', () => { ); const pushEvent = new Event('notificationclick'); - new SwController(app); + new SwController(app, installations); expect(listeners['notificationclick']).to.exist; listeners['notificationclick'](pushEvent); @@ -1013,7 +1019,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy }; - const swController = new SwController(app); + const swController = new SwController(app, installations); swController.onSubChange(event); let error: FirebaseError | undefined; @@ -1032,7 +1038,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the default key by default', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app); + const controller = new SwController(app, installations); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => undefined ); @@ -1043,7 +1049,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the default key', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app); + const controller = new SwController(app, installations); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => DEFAULT_PUBLIC_VAPID_KEY ); @@ -1054,7 +1060,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the custom key if set', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app); + const controller = new SwController(app, installations); const vapidKeyInUse = base64ToArrayBuffer(VALID_VAPID_KEY); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => vapidKeyInUse diff --git a/packages/messaging/test/testing-utils/make-fake-app.ts b/packages/messaging/test/testing-utils/make-fake-app.ts index 5fd17133a90..57342e631ca 100644 --- a/packages/messaging/test/testing-utils/make-fake-app.ts +++ b/packages/messaging/test/testing-utils/make-fake-app.ts @@ -16,6 +16,7 @@ */ import { FirebaseApp, FirebaseOptions } from '@firebase/app-types'; +import { FirebaseInstallations } from '@firebase/installations-types'; export function makeFakeApp(options: FirebaseOptions = {}): FirebaseApp { options = { @@ -34,12 +35,14 @@ export function makeFakeApp(options: FirebaseOptions = {}): FirebaseApp { automaticDataCollectionEnabled: true, delete: async () => {}, messaging: null as any, - installations() { - return { - getId: () => Promise.resolve('FID'), - getToken: () => Promise.resolve('authToken'), - delete: () => Promise.resolve() - }; - } + installations: null as any + }; +} + +export function makeFakeInstallations(): FirebaseInstallations { + return { + getId: () => Promise.resolve('FID'), + getToken: () => Promise.resolve('authToken'), + delete: () => Promise.resolve() }; } diff --git a/packages/messaging/test/testing-utils/make-fake-providers.ts b/packages/messaging/test/testing-utils/make-fake-providers.ts new file mode 100644 index 00000000000..57f78e3c13d --- /dev/null +++ b/packages/messaging/test/testing-utils/make-fake-providers.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider, ComponentContainer } from '@firebase/component'; + +export function makeFakeAnalyticsProvider(): Provider< + FirebaseAnalyticsInternal +> { + return new Provider( + 'analytics-interop', + new ComponentContainer('test') + ); +} diff --git a/packages/messaging/test/token-details-model.test.ts b/packages/messaging/test/token-details-model.test.ts index e2f7bb3a649..0ea257d92df 100644 --- a/packages/messaging/test/token-details-model.test.ts +++ b/packages/messaging/test/token-details-model.test.ts @@ -28,13 +28,18 @@ import { deleteDatabase } from './testing-utils/db-helper'; import { compareDetails } from './testing-utils/detail-comparator'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { FirebaseApp } from '@firebase/app-types'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; +import { FirebaseInstallations } from '@firebase/installations-types'; const BAD_INPUTS: any[] = ['', [], {}, true, null, 123]; describe('Firebase Messaging > TokenDetailsModel', () => { let clock: sinon.SinonFakeTimers; let app: FirebaseApp; + let installations: FirebaseInstallations; let tokenDetailsModel: TokenDetailsModel; let exampleInput: TokenDetails; let fakeSubscription: PushSubscription; @@ -43,7 +48,8 @@ describe('Firebase Messaging > TokenDetailsModel', () => { clock = useFakeTimers(); app = makeFakeApp(); - tokenDetailsModel = new TokenDetailsModel(app); + installations = makeFakeInstallations(); + tokenDetailsModel = new TokenDetailsModel(app, installations); fakeSubscription = makeFakeSubscription(); exampleInput = { @@ -74,7 +80,10 @@ describe('Firebase Messaging > TokenDetailsModel', () => { protected readonly dbVersion = 2; } - const oldDBTokenDetailsModel = new OldDBTokenDetailsModel(app); + const oldDBTokenDetailsModel = new OldDBTokenDetailsModel( + app, + installations + ); // Old (v2) version of exampleInput // vapidKey, auth and p256dh are strings, @@ -109,7 +118,10 @@ describe('Firebase Messaging > TokenDetailsModel', () => { protected readonly dbVersion = 3; } - const oldDBTokenDetailsModel = new OldDBTokenDetailsModel(app); + const oldDBTokenDetailsModel = new OldDBTokenDetailsModel( + app, + installations + ); // Old (v3) version of exampleInput // fcmPushSet exists @@ -142,7 +154,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { describe('saveToken', () => { it('should throw on bad input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.swScope = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -159,7 +171,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad vapid key input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.vapidKey = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -176,7 +188,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad endpoint input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.endpoint = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -193,7 +205,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad auth input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.auth = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -210,7 +222,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad p256dh input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.p256dh = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -227,7 +239,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad send id input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.fcmSenderId = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -244,7 +256,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad token input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); exampleInput.fcmToken = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -260,7 +272,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should save valid details', () => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); return tokenDetailsModel.saveTokenDetails(exampleInput); }); }); @@ -331,7 +343,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { describe('deleteToken', () => { it('should handle no input', () => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); return tokenDetailsModel.deleteToken(undefined as any).then( () => { throw new Error('Expected this to throw an error due to no token'); @@ -343,7 +355,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should handle empty string', () => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); return tokenDetailsModel.deleteToken('').then( () => { throw new Error('Expected this to throw an error due to no token'); @@ -355,7 +367,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should delete current token', () => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); return tokenDetailsModel .saveTokenDetails(exampleInput) .then(() => { @@ -373,7 +385,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should handle deleting a non-existant token', () => { - tokenDetailsModel = new TokenDetailsModel(app); + tokenDetailsModel = new TokenDetailsModel(app, installations); return tokenDetailsModel.deleteToken('bad-token').then( () => { throw new Error('Expected this delete to throw and error.'); diff --git a/packages/messaging/test/window-controller.test.ts b/packages/messaging/test/window-controller.test.ts index a3831131446..25cf48d1198 100644 --- a/packages/messaging/test/window-controller.test.ts +++ b/packages/messaging/test/window-controller.test.ts @@ -17,7 +17,10 @@ import { expect } from 'chai'; import { stub, restore, spy } from 'sinon'; -import { makeFakeApp } from './testing-utils/make-fake-app'; +import { + makeFakeApp, + makeFakeInstallations +} from './testing-utils/make-fake-app'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { WindowController } from '../src/controllers/window-controller'; @@ -25,6 +28,8 @@ import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { MessageType } from '../src/models/worker-page-message'; +import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; + const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; @@ -32,6 +37,9 @@ describe('Firebase Messaging > *WindowController', () => { const app = makeFakeApp({ messagingSenderId: '12345' }); + const installations = makeFakeInstallations(); + + const analyticsProvider = makeFakeAnalyticsProvider(); const cleanup = (): void => { restore(); @@ -49,7 +57,11 @@ describe('Firebase Messaging > *WindowController', () => { it('should resolve if the permission is already granted', () => { stub(Notification as any, 'permission').value('granted'); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); return controller.requestPermission(); }); @@ -59,7 +71,11 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('denied') ); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); return controller.requestPermission().then( () => { throw new Error('Expected an error.'); @@ -76,7 +92,11 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('default') ); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); return controller.requestPermission().then( () => { throw new Error('Expected an error.'); @@ -93,14 +113,22 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('granted') ); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); return controller.requestPermission(); }); }); describe('useServiceWorker()', () => { it(`should throw on invalid input`, () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); let thrownError; try { controller.useServiceWorker(null as any); @@ -113,7 +141,11 @@ describe('Firebase Messaging > *WindowController', () => { it(`should only be callable once`, () => { const registration = makeFakeSWReg(); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.useServiceWorker(registration); let thrownError; @@ -134,7 +166,11 @@ describe('Firebase Messaging > *WindowController', () => { const errFunc = (): void => {}; const compFunc = (): void => {}; - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); const onMessageStub = stub(controller as any, 'onMessage'); controller.onMessage(nextFunc, errFunc, compFunc); @@ -151,7 +187,11 @@ describe('Firebase Messaging > *WindowController', () => { const errFunc = (): void => {}; const compFunc = (): void => {}; - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); const onTokenRefreshStub = stub(controller as any, 'onTokenRefresh'); controller.onTokenRefresh(nextFunc, errFunc, compFunc); @@ -164,7 +204,11 @@ describe('Firebase Messaging > *WindowController', () => { describe('usePublicVapidKey()', () => { it('should throw an error when passing in an invalid value', () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); let thrownError; try { @@ -177,7 +221,11 @@ describe('Firebase Messaging > *WindowController', () => { }); it('should throw an error when called twice', () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.usePublicVapidKey(VALID_VAPID_KEY); let thrownError; @@ -193,7 +241,11 @@ describe('Firebase Messaging > *WindowController', () => { }); it('should throw when decrypting to invalid value', () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); let thrownError; try { @@ -212,14 +264,22 @@ describe('Firebase Messaging > *WindowController', () => { describe('getPublicVapidKey_()', () => { it('should return the default key by default', () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); return controller.getPublicVapidKey_().then(pubKey => { expect(pubKey).to.equal(DEFAULT_PUBLIC_VAPID_KEY); }); }); it('should return the custom key if set', () => { - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.usePublicVapidKey(VALID_VAPID_KEY); return controller.getPublicVapidKey_().then(pubKey => { expect(pubKey).deep.equal(base64ToArrayBuffer(VALID_VAPID_KEY)); @@ -234,7 +294,11 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: sinonSpy }); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.setupSWMessageListener_(); expect(sinonSpy.args[0][0]).to.equal('message'); @@ -248,7 +312,11 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: sinonSpy }); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.onMessage(onMessageSpy, null as any, null as any); controller.setupSWMessageListener_(); @@ -270,7 +338,11 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: messageCallbackSpy }); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); controller.setupSWMessageListener_(); const callback = messageCallbackSpy.args[0][1]; @@ -293,7 +365,11 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: messageCallbackSpy }); - const controller = new WindowController(app); + const controller = new WindowController( + app, + installations, + analyticsProvider + ); // The API for the observables means it's async and so we kind have to // hope that everything is set up after a task skip @@ -339,7 +415,11 @@ describe('Firebase Messaging > *WindowController', () => { const fakeReg = makeFakeSWReg('installing', swValue); - const messagingService = new WindowController(app); + const messagingService = new WindowController( + app, + installations, + analyticsProvider + ); const waitPromise = messagingService.waitForRegistrationToActivate_( fakeReg ); From 84315a80cc37736bef308941b9faafd43de1a92c Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Fri, 1 Nov 2019 15:40:25 -0700 Subject: [PATCH 2/6] remove unused import --- packages/app-types/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/app-types/index.d.ts b/packages/app-types/index.d.ts index eab147e16c8..10b89b83bb9 100644 --- a/packages/app-types/index.d.ts +++ b/packages/app-types/index.d.ts @@ -1,5 +1,3 @@ -import { Provider } from '@firebase/component'; - /** * @license * Copyright 2017 Google Inc. From 777209aff0e4b0f470ec1c973eb299b752428fa5 Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Tue, 5 Nov 2019 12:36:31 -0800 Subject: [PATCH 3/6] bundle firebase services in a single object --- packages/messaging/index.ts | 6 +- .../src/controllers/base-controller.ts | 21 ++-- .../src/controllers/sw-controller.ts | 10 +- .../src/controllers/window-controller.ts | 15 +-- .../src/interfaces/external-services.ts | 10 ++ .../src/models/clean-v1-undefined.ts | 13 +-- .../src/models/subscription-manager.ts | 26 +++-- .../src/models/token-details-model.ts | 8 +- packages/messaging/test/constructor.test.ts | 14 +-- .../test/controller-delete-token.test.ts | 47 +++------ .../test/controller-get-token.test.ts | 83 ++++++---------- .../test/controller-interface.test.ts | 58 ++++------- packages/messaging/test/get-sw-reg.test.ts | 36 ++----- packages/messaging/test/index.test.ts | 2 +- .../test/subscription-manager.test.ts | 52 ++++------ packages/messaging/test/sw-controller.test.ts | 97 +++++++++---------- ...-app.ts => make-fake-firebase-services.ts} | 21 ++++ .../test/testing-utils/make-fake-providers.ts | 28 ------ .../test/token-details-model.test.ts | 52 +++++----- .../messaging/test/window-controller.test.ts | 87 ++++------------- 20 files changed, 256 insertions(+), 430 deletions(-) create mode 100644 packages/messaging/src/interfaces/external-services.ts rename packages/messaging/test/testing-utils/{make-fake-app.ts => make-fake-firebase-services.ts} (67%) delete mode 100644 packages/messaging/test/testing-utils/make-fake-providers.ts diff --git a/packages/messaging/index.ts b/packages/messaging/index.ts index 371d7ea9ff9..253a7bc58be 100644 --- a/packages/messaging/index.ts +++ b/packages/messaging/index.ts @@ -40,16 +40,18 @@ export function registerMessaging(instance: _FirebaseNamespace): void { const installations = container.getProvider('installations').getImmediate(); const analyticsProvider = container.getProvider('analytics-internal'); + const firebaseServices = { app, installations, analyticsProvider}; + if (!isSupported()) { throw errorFactory.create(ErrorCode.UNSUPPORTED_BROWSER); } if (self && 'ServiceWorkerGlobalScope' in self) { // Running in ServiceWorker context - return new SwController(app, installations); + return new SwController(firebaseServices); } else { // Assume we are in the window context. - return new WindowController(app, installations, analyticsProvider); + return new WindowController(firebaseServices); } }; diff --git a/packages/messaging/src/controllers/base-controller.ts b/packages/messaging/src/controllers/base-controller.ts index 55643ad35b1..0386b815319 100644 --- a/packages/messaging/src/controllers/base-controller.ts +++ b/packages/messaging/src/controllers/base-controller.ts @@ -33,7 +33,7 @@ import { ErrorCode, errorFactory } from '../models/errors'; import { SubscriptionManager } from '../models/subscription-manager'; import { TokenDetailsModel } from '../models/token-details-model'; import { VapidDetailsModel } from '../models/vapid-details-model'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; export type BgMessageHandler = ( payload: MessagePayload @@ -44,14 +44,16 @@ export const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days export abstract class BaseController implements FirebaseMessaging { INTERNAL: FirebaseServiceInternals; + readonly app!: FirebaseApp; private readonly tokenDetailsModel: TokenDetailsModel; private readonly vapidDetailsModel = new VapidDetailsModel(); private readonly subscriptionManager = new SubscriptionManager(); constructor( - readonly app: FirebaseApp, - private readonly installations: FirebaseInstallations + protected readonly services: FirebaseInternalServices ) { + const { app } = services; + this.app = app; if ( !app.options.messagingSenderId || typeof app.options.messagingSenderId !== 'string' @@ -63,7 +65,7 @@ export abstract class BaseController implements FirebaseMessaging { delete: () => this.delete() }; - this.tokenDetailsModel = new TokenDetailsModel(app, installations); + this.tokenDetailsModel = new TokenDetailsModel(services); } async getToken(): Promise { @@ -151,8 +153,7 @@ export abstract class BaseController implements FirebaseMessaging { try { const updatedToken = await this.subscriptionManager.updateToken( tokenDetails, - this.app, - this.installations, + this.services, pushSubscription, publicVapidKey ); @@ -160,7 +161,7 @@ export abstract class BaseController implements FirebaseMessaging { const allDetails: TokenDetails = { swScope: swReg.scope, vapidKey: publicVapidKey, - fcmSenderId: this.app.options.messagingSenderId!, + fcmSenderId: this.services.app.options.messagingSenderId!, fcmToken: updatedToken, createTime: Date.now(), endpoint: pushSubscription.endpoint, @@ -186,8 +187,7 @@ export abstract class BaseController implements FirebaseMessaging { publicVapidKey: Uint8Array ): Promise { const newToken = await this.subscriptionManager.getToken( - this.app, - this.installations, + this.services, pushSubscription, publicVapidKey ); @@ -235,8 +235,7 @@ export abstract class BaseController implements FirebaseMessaging { private async deleteTokenFromDB(token: string): Promise { const tokenDetails = await this.tokenDetailsModel.deleteToken(token); await this.subscriptionManager.deleteToken( - this.app, - this.installations, + this.services, tokenDetails ); } diff --git a/packages/messaging/src/controllers/sw-controller.ts b/packages/messaging/src/controllers/sw-controller.ts index bbd61180cc1..05ea36bd87e 100644 --- a/packages/messaging/src/controllers/sw-controller.ts +++ b/packages/messaging/src/controllers/sw-controller.ts @@ -16,9 +16,6 @@ */ import './sw-types'; - -import { FirebaseApp } from '@firebase/app-types'; - import { MessagePayload, NotificationDetails @@ -30,7 +27,7 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController, BgMessageHandler } from './base-controller'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; // Let TS know that this is a service worker declare const self: ServiceWorkerGlobalScope; @@ -39,9 +36,10 @@ const FCM_MSG = 'FCM_MSG'; export class SwController extends BaseController { private bgMessageHandler: BgMessageHandler | null = null; + - constructor(app: FirebaseApp, installations: FirebaseInstallations) { - super(app, installations); + constructor(services: FirebaseInternalServices) { + super(services); self.addEventListener('push', e => { this.onPush(e); diff --git a/packages/messaging/src/controllers/window-controller.ts b/packages/messaging/src/controllers/window-controller.ts index d96659609bc..93989964d66 100644 --- a/packages/messaging/src/controllers/window-controller.ts +++ b/packages/messaging/src/controllers/window-controller.ts @@ -15,7 +15,6 @@ * limitations under the License. */ -import { FirebaseApp } from '@firebase/app-types'; import { _FirebaseApp } from '@firebase/app-types/private'; import { CompleteFn, @@ -39,9 +38,7 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController } from './base-controller'; -import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; -import { Provider } from '@firebase/component'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; export class WindowController extends BaseController { private registrationToUse: ServiceWorkerRegistration | null = null; @@ -66,12 +63,8 @@ export class WindowController extends BaseController { /** * A service that provides a MessagingService instance. */ - constructor( - app: FirebaseApp, - installations: FirebaseInstallations, - readonly analyticsProvider: Provider - ) { - super(app, installations); + constructor(services: FirebaseInternalServices) { + super(services); this.setupSWMessageListener_(); } @@ -315,7 +308,7 @@ export class WindowController extends BaseController { // This message has a campaign id, meaning it was sent using the FN Console. // Analytics is enabled on this message, so we should log it. const eventType = getEventType(firebaseMessagingType); - this.analyticsProvider.get().then( + this.services.analyticsProvider.get().then( analytics => { analytics.logEvent( eventType, diff --git a/packages/messaging/src/interfaces/external-services.ts b/packages/messaging/src/interfaces/external-services.ts new file mode 100644 index 00000000000..ec3e9891369 --- /dev/null +++ b/packages/messaging/src/interfaces/external-services.ts @@ -0,0 +1,10 @@ +import { FirebaseApp } from '@firebase/app-types'; +import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider } from '@firebase/component'; + +export interface FirebaseInternalServices { + app: FirebaseApp, + installations: FirebaseInstallations, + analyticsProvider: Provider +} \ No newline at end of file diff --git a/packages/messaging/src/models/clean-v1-undefined.ts b/packages/messaging/src/models/clean-v1-undefined.ts index 7afa33caa49..4092c0e82df 100644 --- a/packages/messaging/src/models/clean-v1-undefined.ts +++ b/packages/messaging/src/models/clean-v1-undefined.ts @@ -28,16 +28,14 @@ */ import { SubscriptionManager } from './subscription-manager'; -import { FirebaseApp } from '@firebase/app-types'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; const OLD_DB_NAME = 'undefined'; const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store'; function handleDb( db: IDBDatabase, - app: FirebaseApp, - installations: FirebaseInstallations + services: FirebaseInternalServices ): void { if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) { // We found a database with the name 'undefined', but our expected object @@ -64,7 +62,7 @@ function handleDb( const tokenDetails = cursor.value; // eslint-disable-next-line @typescript-eslint/no-floating-promises - subscriptionManager.deleteToken(app, installations, tokenDetails); + subscriptionManager.deleteToken(services, tokenDetails); cursor.continue(); } else { @@ -75,8 +73,7 @@ function handleDb( } export function cleanV1( - app: FirebaseApp, - installations: FirebaseInstallations + services: FirebaseInternalServices ): void { const request: IDBOpenDBRequest = indexedDB.open(OLD_DB_NAME); request.onerror = _event => { @@ -84,6 +81,6 @@ export function cleanV1( }; request.onsuccess = _event => { const db = request.result; - handleDb(db, app, installations); + handleDb(db, services); }; } diff --git a/packages/messaging/src/models/subscription-manager.ts b/packages/messaging/src/models/subscription-manager.ts index e39b30118be..088e0e5821a 100644 --- a/packages/messaging/src/models/subscription-manager.ts +++ b/packages/messaging/src/models/subscription-manager.ts @@ -21,7 +21,7 @@ import { ErrorCode, errorFactory } from './errors'; import { DEFAULT_PUBLIC_VAPID_KEY, ENDPOINT } from './fcm-details'; import { FirebaseApp } from '@firebase/app-types'; import { TokenDetails } from '../interfaces/token-details'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; interface ApiResponse { token?: string; @@ -39,12 +39,11 @@ interface TokenRequestBody { export class SubscriptionManager { async getToken( - app: FirebaseApp, - installations: FirebaseInstallations, + services: FirebaseInternalServices, subscription: PushSubscription, vapidKey: Uint8Array ): Promise { - const headers = await getHeaders(app, installations); + const headers = await getHeaders(services); const body = getBody(subscription, vapidKey); const subscribeOptions = { @@ -55,7 +54,7 @@ export class SubscriptionManager { let responseData: ApiResponse; try { - const response = await fetch(getEndpoint(app), subscribeOptions); + const response = await fetch(getEndpoint(services.app), subscribeOptions); responseData = await response.json(); } catch (err) { throw errorFactory.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, { @@ -82,12 +81,11 @@ export class SubscriptionManager { */ async updateToken( tokenDetails: TokenDetails, - app: FirebaseApp, - installations: FirebaseInstallations, + services: FirebaseInternalServices, subscription: PushSubscription, vapidKey: Uint8Array ): Promise { - const headers = await getHeaders(app, installations); + const headers = await getHeaders(services); const body = getBody(subscription, vapidKey); const updateOptions = { @@ -99,7 +97,7 @@ export class SubscriptionManager { let responseData: ApiResponse; try { const response = await fetch( - `${getEndpoint(app)}/${tokenDetails.fcmToken}`, + `${getEndpoint(services.app)}/${tokenDetails.fcmToken}`, updateOptions ); responseData = await response.json(); @@ -124,12 +122,11 @@ export class SubscriptionManager { } async deleteToken( - app: FirebaseApp, - installations: FirebaseInstallations, + services: FirebaseInternalServices, tokenDetails: TokenDetails ): Promise { // TODO: Add FIS header - const headers = await getHeaders(app, installations); + const headers = await getHeaders(services); const unsubscribeOptions = { method: 'DELETE', @@ -138,7 +135,7 @@ export class SubscriptionManager { try { const response = await fetch( - `${getEndpoint(app)}/${tokenDetails.fcmToken}`, + `${getEndpoint(services.app)}/${tokenDetails.fcmToken}`, unsubscribeOptions ); const responseData: ApiResponse = await response.json(); @@ -161,8 +158,7 @@ function getEndpoint(app: FirebaseApp): string { } async function getHeaders( - app: FirebaseApp, - installations: FirebaseInstallations + { app, installations }: FirebaseInternalServices, ): Promise { const authToken = await installations.getToken(); diff --git a/packages/messaging/src/models/token-details-model.ts b/packages/messaging/src/models/token-details-model.ts index e4e9c9c6f13..13d0810111b 100644 --- a/packages/messaging/src/models/token-details-model.ts +++ b/packages/messaging/src/models/token-details-model.ts @@ -20,8 +20,7 @@ import { TokenDetails } from '../interfaces/token-details'; import { cleanV1 } from './clean-v1-undefined'; import { DbInterface } from './db-interface'; import { ErrorCode, errorFactory } from './errors'; -import { FirebaseApp } from '@firebase/app-types'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../interfaces/external-services'; export class TokenDetailsModel extends DbInterface { protected readonly dbName: string = 'fcm_token_details_db'; @@ -29,8 +28,7 @@ export class TokenDetailsModel extends DbInterface { protected readonly objectStoreName: string = 'fcm_token_object_Store'; constructor( - private readonly app: FirebaseApp, - private readonly installations: FirebaseInstallations + private readonly services: FirebaseInternalServices ) { super(); } @@ -61,7 +59,7 @@ export class TokenDetailsModel extends DbInterface { // Prior to version 2, we were using either 'fcm_token_details_db' // or 'undefined' as the database name due to bug in the SDK // So remove the old tokens and databases. - cleanV1(this.app, this.installations); + cleanV1(this.services); } case 2: { diff --git a/packages/messaging/test/constructor.test.ts b/packages/messaging/test/constructor.test.ts index 37945324c90..59bf5086041 100644 --- a/packages/messaging/test/constructor.test.ts +++ b/packages/messaging/test/constructor.test.ts @@ -24,9 +24,9 @@ import { ErrorCode } from '../src/models/errors'; import { makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; -import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; + makeFakeInstallations, + makeFakeAnalyticsProvider +} from './testing-utils/make-fake-firebase-services'; describe('Firebase Messaging > new *Controller()', () => { const analyticsProvider = makeFakeAnalyticsProvider(); @@ -51,8 +51,8 @@ describe('Firebase Messaging > new *Controller()', () => { ]; badInputs.forEach(badInput => { try { - new WindowController(badInput, installations, analyticsProvider); - new SwController(badInput, installations); + new WindowController({ app: badInput, installations, analyticsProvider }); + new SwController({ app: badInput, installations, analyticsProvider }); assert.fail( `Bad Input should have thrown: ${JSON.stringify(badInput)}` @@ -66,7 +66,7 @@ describe('Firebase Messaging > new *Controller()', () => { it('should be able to handle good input', () => { const app = makeFakeApp(); - new WindowController(app, installations, analyticsProvider); - new SwController(app, installations); + new WindowController({ app, installations, analyticsProvider }); + new SwController({ app, installations, analyticsProvider }); }); }); diff --git a/packages/messaging/test/controller-delete-token.test.ts b/packages/messaging/test/controller-delete-token.test.ts index 8c37bb64a26..206e59360aa 100644 --- a/packages/messaging/test/controller-delete-token.test.ts +++ b/packages/messaging/test/controller-delete-token.test.ts @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { FirebaseApp } from '@firebase/app-types'; import { assert } from 'chai'; import { stub, restore } from 'sinon'; @@ -27,24 +26,18 @@ import { TokenDetailsModel } from '../src/models/token-details-model'; import { deleteDatabase } from './testing-utils/db-helper'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { TokenDetails } from '../src/interfaces/token-details'; -import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; -import { Provider } from '@firebase/component'; -import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; let FAKE_SUBSCRIPTION: PushSubscription; let EXAMPLE_TOKEN_SAVE: TokenDetails; describe('Firebase Messaging > *Controller.deleteToken()', () => { - let app: FirebaseApp; - let installations: FirebaseInstallations; - let analyticsProvider: Provider; + let firebaseInternalServices: FirebaseInternalServices; let messagingService: WindowController | SwController; function configureRegistrationMocks( @@ -86,11 +79,9 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { }); beforeEach(() => { - app = makeFakeApp({ + firebaseInternalServices = makeFakeFirebaseInternalServices({ messagingSenderId: EXAMPLE_TOKEN_SAVE.fcmSenderId }); - installations = makeFakeInstallations(); - analyticsProvider = makeFakeAnalyticsProvider(); }); afterEach(async () => { @@ -105,9 +96,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { it('should handle no token to delete', () => { messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(undefined as any).then( () => { @@ -132,9 +121,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { ); messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -157,9 +144,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { ); messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { @@ -190,9 +175,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { ); messagingService = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -223,9 +206,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { ); messagingService = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { @@ -261,9 +242,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { }); messagingService = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { @@ -298,9 +277,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { ); messagingService = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); diff --git a/packages/messaging/test/controller-get-token.test.ts b/packages/messaging/test/controller-get-token.test.ts index 84fb9fe93ed..499a6bde901 100644 --- a/packages/messaging/test/controller-get-token.test.ts +++ b/packages/messaging/test/controller-get-token.test.ts @@ -17,8 +17,6 @@ import { assert, expect } from 'chai'; import { stub, restore, useFakeTimers } from 'sinon'; -import { FirebaseApp } from '@firebase/app-types'; - import { BaseController } from '../src/controllers/base-controller'; import { SwController } from '../src/controllers/sw-controller'; import { WindowController } from '../src/controllers/window-controller'; @@ -32,15 +30,11 @@ import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; -import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; -import { Provider } from '@firebase/component'; -import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; const ONE_DAY = 24 * 60 * 60 * 1000; @@ -80,9 +74,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { let EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID: TokenDetails; let EXAMPLE_EXPIRED_TOKEN_DETAILS: TokenDetails; - let app: FirebaseApp; - let installations: FirebaseInstallations; - let analyticsProvider: Provider; + let firebaseInternalServices: FirebaseInternalServices; beforeEach(() => { now = Date.now(); @@ -96,7 +88,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { EXAMPLE_SENDER_ID = '1234567890'; CUSTOM_VAPID_KEY = base64ToArrayBuffer( 'BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXK' + - 'pNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo' + 'pNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo' ); ENDPOINT = FAKE_SUBSCRIPTION.endpoint; AUTH = FAKE_SUBSCRIPTION.getKey('auth')!; @@ -133,12 +125,9 @@ describe('Firebase Messaging > *Controller.getToken()', () => { createTime: expiredDate }; - app = makeFakeApp({ + firebaseInternalServices = makeFakeFirebaseInternalServices({ messagingSenderId: EXAMPLE_SENDER_ID }); - installations = makeFakeInstallations(); - - analyticsProvider = makeFakeAnalyticsProvider(); }); afterEach(() => { @@ -155,9 +144,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); try { await messagingService.getToken(); @@ -183,9 +170,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { return servicesToTest.reduce(async (chain, serviceClass) => { const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); stub(serviceClass.prototype, 'getPublicVapidKey_').callsFake(() => Promise.resolve(DEFAULT_PUBLIC_VAPID_KEY) @@ -234,9 +219,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ).callsFake(() => Promise.resolve(details)); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const token = await serviceInstance.getToken(); assert.equal(details.fcmToken, token); @@ -264,9 +247,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID.fcmToken, token); @@ -300,17 +281,15 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(TokenDetailsModel.prototype, 'saveTokenDetails').callsFake( - async () => {} + async () => { } ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => {} + async () => { } ); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_FCM_TOKEN, token); @@ -348,7 +327,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveVapidDetailsStub = stub( VapidDetailsModel.prototype, 'saveVapidDetails' - ).callsFake(async () => {}); + ).callsFake(async () => { }); stub(SubscriptionManager.prototype, 'getToken').callsFake(() => Promise.resolve(GET_TOKEN_RESPONSE) @@ -362,12 +341,10 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveTokenDetailsStub = stub( TokenDetailsModel.prototype, 'saveTokenDetails' - ).callsFake(async () => {}); + ).callsFake(async () => { }); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const token = await serviceInstance.getToken(); @@ -406,7 +383,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { TokenDetailsModel.prototype, 'saveTokenDetails' ); - saveTokenDetailsStub.callsFake(async () => {}); + saveTokenDetailsStub.callsFake(async () => { }); stub(BaseController.prototype, 'getNotificationPermission_').callsFake( () => 'granted' @@ -426,14 +403,14 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveVapidDetailsStub = stub( VapidDetailsModel.prototype, 'saveVapidDetails' - ).callsFake(async () => {}); + ).callsFake(async () => { }); const GET_TOKEN_RESPONSE = 'new-token'; stub(SubscriptionManager.prototype, 'getToken').callsFake(() => Promise.resolve(GET_TOKEN_RESPONSE) ); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => {} + async () => { } ); const registration = generateFakeReg(); @@ -460,9 +437,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ).callsFake(() => Promise.resolve(details)); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const token = await serviceInstance.getToken(); // make sure we call getToken and retrieve the new token. @@ -501,7 +476,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => {} + async () => { } ); stub(TokenDetailsModel.prototype, 'getTokenDetailsFromSWScope').callsFake( @@ -513,9 +488,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); const defaultVAPIDToken = await serviceInstance.getToken(); assert.equal( @@ -532,7 +505,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { TokenDetailsModel.prototype, 'saveTokenDetails' ); - saveTokenDetailsStub.callsFake(async () => {}); + saveTokenDetailsStub.callsFake(async () => { }); const deleteTokenStub = stub(TokenDetailsModel.prototype, 'deleteToken'); deleteTokenStub.callsFake(token => { @@ -541,7 +514,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { }); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => {} + async () => { } ); stub(SubscriptionManager.prototype, 'getToken').callsFake(() => @@ -586,7 +559,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => {} + async () => { } ); stub(SubscriptionManager.prototype, 'updateToken').callsFake(() => @@ -600,13 +573,11 @@ describe('Firebase Messaging > *Controller.getToken()', () => { }); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => {} + async () => { } ); const serviceInstance = new serviceClass( - app, - installations, - analyticsProvider + firebaseInternalServices ); try { await serviceInstance.getToken(); diff --git a/packages/messaging/test/controller-interface.test.ts b/packages/messaging/test/controller-interface.test.ts index 4544623ecc9..76ec9717de9 100644 --- a/packages/messaging/test/controller-interface.test.ts +++ b/packages/messaging/test/controller-interface.test.ts @@ -15,7 +15,6 @@ * limitations under the License. */ -import { FirebaseApp } from '@firebase/app-types'; import { expect } from 'chai'; import { stub, restore, spy } from 'sinon'; @@ -28,14 +27,10 @@ import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; - -import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; -import { Provider, ComponentContainer } from '@firebase/component'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; const controllersToTest = [WindowController, SwController]; @@ -54,19 +49,12 @@ class MockBaseController extends BaseController { } describe('Firebase Messaging > *BaseController', () => { - let app: FirebaseApp; - let installations: FirebaseInstallations; - let analyticsProvider: Provider; + let firebaseInternalServices: FirebaseInternalServices; beforeEach(() => { - app = makeFakeApp({ + firebaseInternalServices = makeFakeFirebaseInternalServices({ messagingSenderId: '12345' }); - installations = makeFakeInstallations(); - analyticsProvider = new Provider( - 'analytics-interop', - new ComponentContainer('test') - ); }); afterEach(() => { @@ -75,7 +63,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('INTERNAL.delete()', () => { it('should call delete()', async () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); const sinonSpy = spy(controller, 'delete'); await controller.INTERNAL.delete(); expect(sinonSpy.callCount).to.equal(1); @@ -84,7 +72,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('requestPermission()', () => { it(`should throw`, async () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { await controller.requestPermission(); @@ -108,9 +96,7 @@ describe('Firebase Messaging > *BaseController', () => { }); const controller = new controllerInTest( - app, - installations, - analyticsProvider + firebaseInternalServices ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) @@ -132,9 +118,7 @@ describe('Firebase Messaging > *BaseController', () => { }); const controller = new controllerInTest( - app, - installations, - analyticsProvider + firebaseInternalServices ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) @@ -147,7 +131,7 @@ describe('Firebase Messaging > *BaseController', () => { const exampleSubscription = {}; const reg = makeFakeSWReg(); stub(reg, 'pushManager').value({ - getSubscription: async () => {}, + getSubscription: async () => { }, subscribe: async (options: PushSubscriptionOptions) => { expect(options).to.deep.equal({ userVisibleOnly: true, @@ -159,9 +143,7 @@ describe('Firebase Messaging > *BaseController', () => { }); const controller = new controllerInTest( - app, - installations, - analyticsProvider + firebaseInternalServices ); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) @@ -174,7 +156,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('useServiceWorker()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { controller.useServiceWorker(null as any); @@ -188,7 +170,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('usePublicVapidKey()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { controller.usePublicVapidKey(null as any); @@ -202,7 +184,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('onMessage()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { controller.onMessage(null as any, null as any, null as any); @@ -216,7 +198,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('onTokenRefresh()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { controller.onTokenRefresh(null as any, null as any, null as any); @@ -230,7 +212,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('setBackgroundMessageHandler()', () => { it(`should throw`, () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); let thrownError; try { controller.setBackgroundMessageHandler(null as any); @@ -245,7 +227,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getNotificationPermission_', () => { it('should return current permission', () => { stub(Notification as any, 'permission').value('test'); - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); const result = controller.getNotificationPermission_(); expect(result).to.equal('test'); }); @@ -253,7 +235,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getTokenDetailsModel', () => { it('should return an instance of TokenDetailsModel', () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); const result = controller.getTokenDetailsModel(); expect(result).to.be.instanceof(TokenDetailsModel); }); @@ -261,7 +243,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getVapidDetailsModel', () => { it('should return an instance of VapidDetailsModel', () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); const result = controller.getVapidDetailsModel(); expect(result).to.be.instanceof(VapidDetailsModel); }); @@ -269,7 +251,7 @@ describe('Firebase Messaging > *BaseController', () => { describe('getIidModel', () => { it('should return an instance of IidModel', () => { - const controller = new MockBaseController(app, installations); + const controller = new MockBaseController(firebaseInternalServices); const result = controller.getSubscriptionManager(); expect(result).to.be.instanceof(SubscriptionManager); }); diff --git a/packages/messaging/test/get-sw-reg.test.ts b/packages/messaging/test/get-sw-reg.test.ts index e04142113e3..ba08e7f5af7 100644 --- a/packages/messaging/test/get-sw-reg.test.ts +++ b/packages/messaging/test/get-sw-reg.test.ts @@ -22,19 +22,15 @@ import { WindowController } from '../src/controllers/window-controller'; import { ErrorCode } from '../src/models/errors'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; -import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; const EXAMPLE_SENDER_ID = '1234567890'; -const app = makeFakeApp({ +const firebaseInternalServices = makeFakeFirebaseInternalServices({ messagingSenderId: EXAMPLE_SENDER_ID }); -const installations = makeFakeInstallations(); -const analyticsProvider = makeFakeAnalyticsProvider(); describe('Firebase Messaging > *Controller.getSWReg_()', () => { const mockWindowRegistration = ( @@ -69,9 +65,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(activatedRegistration); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService .getSWRegistration_() @@ -93,9 +87,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(fakeReg); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.getSWRegistration_().then( () => { @@ -111,7 +103,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const fakeReg = makeFakeSWReg(); (self as any).registration = fakeReg; - const messagingService = new SwController(app, installations); + const messagingService = new SwController(firebaseInternalServices); return messagingService .getSWRegistration_() .then(registration => { @@ -134,9 +126,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { }); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.getSWRegistration_().then( () => { @@ -159,9 +149,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(redundantRegistration); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.getSWRegistration_().then( () => { @@ -189,9 +177,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(slowRedundantRegistration); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.getSWRegistration_().then( () => { @@ -219,9 +205,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(slowRedundantRegistration); const messagingService = new WindowController( - app, - installations, - analyticsProvider + firebaseInternalServices ); return messagingService.getSWRegistration_().then( () => { diff --git a/packages/messaging/test/index.test.ts b/packages/messaging/test/index.test.ts index 012c9b20118..f5c17df2fdc 100644 --- a/packages/messaging/test/index.test.ts +++ b/packages/messaging/test/index.test.ts @@ -32,7 +32,7 @@ import { WindowController } from '../src/controllers/window-controller'; import { makeFakeApp, makeFakeInstallations -} from './testing-utils/make-fake-app'; +} from './testing-utils/make-fake-firebase-services'; import { InstanceFactory, ComponentContainer, diff --git a/packages/messaging/test/subscription-manager.test.ts b/packages/messaging/test/subscription-manager.test.ts index 191d91e78b2..f8303872f39 100644 --- a/packages/messaging/test/subscription-manager.test.ts +++ b/packages/messaging/test/subscription-manager.test.ts @@ -23,14 +23,12 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { fetchMock } from './testing-utils/mock-fetch'; -import { FirebaseApp } from '@firebase/app-types'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { TokenDetails } from '../src/interfaces/token-details'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; // prettier-ignore const appPubKey = new Uint8Array([ @@ -43,15 +41,13 @@ function getDefaultPublicKey(): Uint8Array { } describe('Firebase Messaging > SubscriptionManager', () => { - let app: FirebaseApp; - let installations: FirebaseInstallations; + let firebaseInternalServices: FirebaseInternalServices; let subscription: PushSubscription; let tokenDetails: TokenDetails; let subscriptionManager: SubscriptionManager; beforeEach(() => { - app = makeFakeApp(); - installations = makeFakeInstallations(); + firebaseInternalServices = makeFakeFirebaseInternalServices(); subscription = makeFakeSubscription(); tokenDetails = { swScope: '/example-scope', @@ -59,7 +55,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { 'BNJxw7sCGkGLOUP2cawBaBXRuWZ3lw_PmQMgreLVVvX_b' + '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' ), - fcmSenderId: app.options.messagingSenderId!, + fcmSenderId: firebaseInternalServices.app.options.messagingSenderId!, fcmToken: 'qwerty', endpoint: subscription.endpoint, auth: subscription.getKey('auth')!, @@ -82,8 +78,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { fetchMock.jsonOk(JSON.stringify(mockResponse)) ); const token = await subscriptionManager.getToken( - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -99,8 +94,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { fetchMock.jsonOk(JSON.stringify(mockResponse)) ); const token = await subscriptionManager.getToken( - app, - installations, + firebaseInternalServices, subscription, getDefaultPublicKey() ); @@ -115,8 +109,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { stub(window, 'fetch').returns(fetchMock.jsonError(400, errorMsg)); try { await subscriptionManager.getToken( - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -130,8 +123,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { stub(window, 'fetch').returns(fetchMock.htmlError(400, 'html-response')); try { await subscriptionManager.getToken( - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -148,8 +140,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { ); try { await subscriptionManager.getToken( - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -170,8 +161,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { ); const res = await subscriptionManager.updateToken( tokenDetails, - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -186,8 +176,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { ); const res = await subscriptionManager.updateToken( tokenDetails, - app, - installations, + firebaseInternalServices, subscription, getDefaultPublicKey() ); @@ -205,8 +194,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { try { await subscriptionManager.updateToken( tokenDetails, - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -221,8 +209,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { try { await subscriptionManager.updateToken( tokenDetails, - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -238,8 +225,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { try { await subscriptionManager.updateToken( tokenDetails, - app, - installations, + firebaseInternalServices, subscription, appPubKey ); @@ -253,7 +239,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { describe('deleteToken', () => { it('deletes on valid request', async () => { stub(window, 'fetch').returns(fetchMock.jsonOk('{}')); - await subscriptionManager.deleteToken(app, installations, tokenDetails); + await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); }); it('handles fetch errors', async () => { @@ -262,7 +248,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { stub(window, 'fetch').returns(fetchMock.jsonError(400, errorMsg)); try { - await subscriptionManager.deleteToken(app, installations, tokenDetails); + await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); @@ -273,7 +259,7 @@ describe('Firebase Messaging > SubscriptionManager', () => { const stubbedFetch = stub(window, 'fetch'); stubbedFetch.returns(fetchMock.htmlError(404, 'html-response')); try { - await subscriptionManager.deleteToken(app, installations, tokenDetails); + await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); diff --git a/packages/messaging/test/sw-controller.test.ts b/packages/messaging/test/sw-controller.test.ts index 4f06234b1ed..ae8437f432f 100644 --- a/packages/messaging/test/sw-controller.test.ts +++ b/packages/messaging/test/sw-controller.test.ts @@ -22,28 +22,22 @@ declare const self: ServiceWorkerGlobalScope; import { expect } from 'chai'; import { stub, restore, spy, SinonSpy } from 'sinon'; - -import { FirebaseApp } from '@firebase/app-types'; import { FirebaseError } from '@firebase/util'; - import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; - import { SwController } from '../src/controllers/sw-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; describe('Firebase Messaging > *SwController', () => { - let app: FirebaseApp; - let installations: FirebaseInstallations; + let firebaseInternalServices: FirebaseInternalServices; beforeEach(() => { // When trying to stub self.clients self.registration, Sinon complains that @@ -60,10 +54,9 @@ describe('Firebase Messaging > *SwController', () => { (self as any).registration = 'This is a placeholder for sinon to overwrite.'; - app = makeFakeApp({ + firebaseInternalServices = makeFakeFirebaseInternalServices({ messagingSenderId: '12345' }); - installations = makeFakeInstallations(); }); afterEach(() => { @@ -75,7 +68,7 @@ describe('Firebase Messaging > *SwController', () => { describe('onPush', () => { it('should handle a push event with no data', async () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const waitUntilSpy = spy(); swController.onPush({ waitUntil: waitUntilSpy, @@ -86,7 +79,7 @@ describe('Firebase Messaging > *SwController', () => { }); it('should handle a push event where .json() throws', async () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const waitUntilSpy = spy(); swController.onPush({ waitUntil: waitUntilSpy, @@ -108,7 +101,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -130,7 +123,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -154,7 +147,7 @@ describe('Firebase Messaging > *SwController', () => { async () => true ); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.setBackgroundMessageHandler((() => {}) as any); swController.onPush({ waitUntil: waitUntilSpy, @@ -177,7 +170,7 @@ describe('Firebase Messaging > *SwController', () => { ); const showNotificationStub = spy(registration, 'showNotification'); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -215,7 +208,7 @@ describe('Firebase Messaging > *SwController', () => { icon: '/images/test-icon.png' }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -283,7 +276,7 @@ describe('Firebase Messaging > *SwController', () => { ] }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -317,7 +310,7 @@ describe('Firebase Messaging > *SwController', () => { const payloadData = {}; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.setBackgroundMessageHandler(bgMessageHandlerSpy); swController.onPush({ waitUntil: waitUntilSpy, @@ -339,7 +332,7 @@ describe('Firebase Messaging > *SwController', () => { async () => false ); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onPush({ waitUntil: waitUntilSpy, data: { @@ -355,7 +348,7 @@ describe('Firebase Messaging > *SwController', () => { describe('setBackgroundMessageHandler', () => { it('should throw on a non-function input', () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); let thrownError: FirebaseError | undefined; try { swController.setBackgroundMessageHandler('' as any); @@ -384,7 +377,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -415,7 +408,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -450,7 +443,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.hasVisibleClients_(); expect(result).to.equal(true); }); @@ -473,7 +466,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.hasVisibleClients_(); expect(result).to.equal(false); }); @@ -493,7 +486,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.getWindowClient_('/test-url'); expect(result).to.equal(null); }); @@ -521,7 +514,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.getWindowClient_('/test-url'); expect(result).to.equal(null); }); @@ -553,7 +546,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const result = await swController.getWindowClient_(matchingClient.url); expect(result).to.equal(matchingClient); }); @@ -566,7 +559,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); @@ -580,7 +573,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); @@ -596,7 +589,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); @@ -618,7 +611,7 @@ describe('Firebase Messaging > *SwController', () => { stopImmediatePropagation: spy(), action: 'action1' }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); @@ -637,7 +630,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); @@ -659,7 +652,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy, stopImmediatePropagation: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onNotificationClick(event); await event.waitUntil.getCall(0).args[0]; @@ -718,7 +711,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); stub(swController, 'getWindowClient_').callsFake(async () => null); @@ -745,7 +738,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); stub(swController, 'getWindowClient_').callsFake(async () => null); const attemptToMessageClientStub = stub( @@ -788,7 +781,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); stub(swController, 'getWindowClient_').callsFake( async () => fakeWindowClient as WindowClient @@ -824,14 +817,14 @@ describe('Firebase Messaging > *SwController', () => { describe('getNotificationData_', () => { it('should return nothing for no payload', () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); expect(swController.getNotificationData_(undefined as any)).to.equal( undefined ); }); it('adds message payload to data.FCM_MSG without replacing user defined data', () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const msgPayload = { notification: { title: 'Hello World', @@ -858,7 +851,7 @@ describe('Firebase Messaging > *SwController', () => { describe('attemptToMessageClient_', () => { it('should reject when no window client provided', () => { - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); return swController.attemptToMessageClient_(null as any, {} as any).then( () => { throw new Error('Expected error to be thrown'); @@ -875,7 +868,7 @@ describe('Firebase Messaging > *SwController', () => { const client: any = { postMessage: spy() }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); await swController.attemptToMessageClient_(client, msg); expect(client.postMessage.callCount).to.equal(1); expect(client.postMessage.getCall(0).args[0]).to.equal(msg); @@ -890,7 +883,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const payload = {}; @@ -910,7 +903,7 @@ describe('Firebase Messaging > *SwController', () => { }; stub(self, 'clients').value(clients); - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); const attemptToMessageClientStub = stub( swController, 'attemptToMessageClient_' @@ -949,7 +942,7 @@ describe('Firebase Messaging > *SwController', () => { const onPushStub = stub(SwController.prototype, 'onPush'); const pushEvent = new Event('push'); - new SwController(app, installations); + new SwController(firebaseInternalServices); expect(listeners['push']).to.exist; listeners['push'](pushEvent); @@ -966,7 +959,7 @@ describe('Firebase Messaging > *SwController', () => { const onSubChangeStub = stub(SwController.prototype, 'onSubChange'); const pushEvent = new Event('pushsubscriptionchange'); - new SwController(app, installations); + new SwController(firebaseInternalServices); expect(listeners['pushsubscriptionchange']).to.exist; listeners['pushsubscriptionchange'](pushEvent); @@ -992,7 +985,7 @@ describe('Firebase Messaging > *SwController', () => { ); const pushEvent = new Event('notificationclick'); - new SwController(app, installations); + new SwController(firebaseInternalServices); expect(listeners['notificationclick']).to.exist; listeners['notificationclick'](pushEvent); @@ -1019,7 +1012,7 @@ describe('Firebase Messaging > *SwController', () => { waitUntil: waitUntilSpy }; - const swController = new SwController(app, installations); + const swController = new SwController(firebaseInternalServices); swController.onSubChange(event); let error: FirebaseError | undefined; @@ -1038,7 +1031,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the default key by default', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app, installations); + const controller = new SwController(firebaseInternalServices); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => undefined ); @@ -1049,7 +1042,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the default key', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app, installations); + const controller = new SwController(firebaseInternalServices); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => DEFAULT_PUBLIC_VAPID_KEY ); @@ -1060,7 +1053,7 @@ describe('Firebase Messaging > *SwController', () => { it('should return the custom key if set', async () => { const registration = makeFakeSWReg(); stub(self, 'registration').value(registration); - const controller = new SwController(app, installations); + const controller = new SwController(firebaseInternalServices); const vapidKeyInUse = base64ToArrayBuffer(VALID_VAPID_KEY); stub(VapidDetailsModel.prototype, 'getVapidFromSWScope').callsFake( async () => vapidKeyInUse diff --git a/packages/messaging/test/testing-utils/make-fake-app.ts b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts similarity index 67% rename from packages/messaging/test/testing-utils/make-fake-app.ts rename to packages/messaging/test/testing-utils/make-fake-firebase-services.ts index 57342e631ca..eedd1017ae2 100644 --- a/packages/messaging/test/testing-utils/make-fake-app.ts +++ b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts @@ -17,6 +17,17 @@ import { FirebaseApp, FirebaseOptions } from '@firebase/app-types'; import { FirebaseInstallations } from '@firebase/installations-types'; +import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; +import { Provider, ComponentContainer } from '@firebase/component'; +import { FirebaseInternalServices } from '../../src/interfaces/external-services'; + +export function makeFakeFirebaseInternalServices(options: FirebaseOptions = {}): FirebaseInternalServices { + return { + app: makeFakeApp(options), + installations: makeFakeInstallations(), + analyticsProvider: makeFakeAnalyticsProvider() + }; +} export function makeFakeApp(options: FirebaseOptions = {}): FirebaseApp { options = { @@ -46,3 +57,13 @@ export function makeFakeInstallations(): FirebaseInstallations { delete: () => Promise.resolve() }; } + +export function makeFakeAnalyticsProvider(): Provider< + FirebaseAnalyticsInternal +> { + return new Provider( + 'analytics-interop', + new ComponentContainer('test') + ); +} + diff --git a/packages/messaging/test/testing-utils/make-fake-providers.ts b/packages/messaging/test/testing-utils/make-fake-providers.ts deleted file mode 100644 index 57f78e3c13d..00000000000 --- a/packages/messaging/test/testing-utils/make-fake-providers.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @license - * Copyright 2019 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; -import { Provider, ComponentContainer } from '@firebase/component'; - -export function makeFakeAnalyticsProvider(): Provider< - FirebaseAnalyticsInternal -> { - return new Provider( - 'analytics-interop', - new ComponentContainer('test') - ); -} diff --git a/packages/messaging/test/token-details-model.test.ts b/packages/messaging/test/token-details-model.test.ts index 0ea257d92df..437d85c4270 100644 --- a/packages/messaging/test/token-details-model.test.ts +++ b/packages/messaging/test/token-details-model.test.ts @@ -17,29 +17,24 @@ import { assert } from 'chai'; import { useFakeTimers } from 'sinon'; - import { arrayBufferToBase64 } from '../src/helpers/array-buffer-to-base64'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { TokenDetails } from '../src/interfaces/token-details'; import { ErrorCode } from '../src/models/errors'; import { TokenDetailsModel } from '../src/models/token-details-model'; - import { deleteDatabase } from './testing-utils/db-helper'; import { compareDetails } from './testing-utils/detail-comparator'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; -import { FirebaseApp } from '@firebase/app-types'; import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; -import { FirebaseInstallations } from '@firebase/installations-types'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; +import { FirebaseInternalServices } from '../src/interfaces/external-services'; const BAD_INPUTS: any[] = ['', [], {}, true, null, 123]; describe('Firebase Messaging > TokenDetailsModel', () => { let clock: sinon.SinonFakeTimers; - let app: FirebaseApp; - let installations: FirebaseInstallations; + let firebaseInternalServices: FirebaseInternalServices; let tokenDetailsModel: TokenDetailsModel; let exampleInput: TokenDetails; let fakeSubscription: PushSubscription; @@ -47,16 +42,15 @@ describe('Firebase Messaging > TokenDetailsModel', () => { beforeEach(() => { clock = useFakeTimers(); - app = makeFakeApp(); - installations = makeFakeInstallations(); - tokenDetailsModel = new TokenDetailsModel(app, installations); + firebaseInternalServices = makeFakeFirebaseInternalServices(); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); fakeSubscription = makeFakeSubscription(); exampleInput = { swScope: '/example-scope', vapidKey: base64ToArrayBuffer( 'BNJxw7sCGkGLOUP2cawBaBXRuWZ3lw_PmQMgreLVVvX_b' + - '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' + '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' ), fcmSenderId: '1234567', fcmToken: 'qwerty', @@ -81,8 +75,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { } const oldDBTokenDetailsModel = new OldDBTokenDetailsModel( - app, - installations + firebaseInternalServices ); // Old (v2) version of exampleInput @@ -119,8 +112,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { } const oldDBTokenDetailsModel = new OldDBTokenDetailsModel( - app, - installations + firebaseInternalServices ); // Old (v3) version of exampleInput @@ -129,7 +121,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { swScope: '/example-scope', vapidKey: base64ToArrayBuffer( 'BNJxw7sCGkGLOUP2cawBaBXRuWZ3lw_PmQMgreLVVvX_b' + - '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' + '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' ), fcmSenderId: '1234567', fcmToken: 'qwerty', @@ -154,7 +146,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { describe('saveToken', () => { it('should throw on bad input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.swScope = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -171,7 +163,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad vapid key input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.vapidKey = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -188,7 +180,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad endpoint input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.endpoint = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -205,7 +197,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad auth input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.auth = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -222,7 +214,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad p256dh input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.p256dh = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -239,7 +231,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad send id input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.fcmSenderId = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -256,7 +248,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { it('should throw on bad token input', () => { const promises = BAD_INPUTS.map(badInput => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); exampleInput.fcmToken = badInput; return tokenDetailsModel.saveTokenDetails(exampleInput).then( () => { @@ -272,7 +264,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should save valid details', () => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); return tokenDetailsModel.saveTokenDetails(exampleInput); }); }); @@ -343,7 +335,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { describe('deleteToken', () => { it('should handle no input', () => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); return tokenDetailsModel.deleteToken(undefined as any).then( () => { throw new Error('Expected this to throw an error due to no token'); @@ -355,7 +347,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should handle empty string', () => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); return tokenDetailsModel.deleteToken('').then( () => { throw new Error('Expected this to throw an error due to no token'); @@ -367,7 +359,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should delete current token', () => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); return tokenDetailsModel .saveTokenDetails(exampleInput) .then(() => { @@ -385,7 +377,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { }); it('should handle deleting a non-existant token', () => { - tokenDetailsModel = new TokenDetailsModel(app, installations); + tokenDetailsModel = new TokenDetailsModel(firebaseInternalServices); return tokenDetailsModel.deleteToken('bad-token').then( () => { throw new Error('Expected this delete to throw and error.'); diff --git a/packages/messaging/test/window-controller.test.ts b/packages/messaging/test/window-controller.test.ts index 25cf48d1198..8d64d50d040 100644 --- a/packages/messaging/test/window-controller.test.ts +++ b/packages/messaging/test/window-controller.test.ts @@ -16,30 +16,21 @@ */ import { expect } from 'chai'; import { stub, restore, spy } from 'sinon'; - import { - makeFakeApp, - makeFakeInstallations -} from './testing-utils/make-fake-app'; + makeFakeFirebaseInternalServices +} from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; - import { WindowController } from '../src/controllers/window-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { MessageType } from '../src/models/worker-page-message'; -import { makeFakeAnalyticsProvider } from './testing-utils/make-fake-providers'; const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; describe('Firebase Messaging > *WindowController', () => { - const app = makeFakeApp({ - messagingSenderId: '12345' - }); - const installations = makeFakeInstallations(); - - const analyticsProvider = makeFakeAnalyticsProvider(); + const fakeFirebaseServices = makeFakeFirebaseInternalServices({messagingSenderId: '12345'}); const cleanup = (): void => { restore(); @@ -58,9 +49,7 @@ describe('Firebase Messaging > *WindowController', () => { stub(Notification as any, 'permission').value('granted'); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); return controller.requestPermission(); }); @@ -72,9 +61,7 @@ describe('Firebase Messaging > *WindowController', () => { ); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); return controller.requestPermission().then( () => { @@ -93,9 +80,7 @@ describe('Firebase Messaging > *WindowController', () => { ); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); return controller.requestPermission().then( () => { @@ -114,9 +99,7 @@ describe('Firebase Messaging > *WindowController', () => { ); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); return controller.requestPermission(); }); @@ -125,9 +108,7 @@ describe('Firebase Messaging > *WindowController', () => { describe('useServiceWorker()', () => { it(`should throw on invalid input`, () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); let thrownError; try { @@ -142,9 +123,7 @@ describe('Firebase Messaging > *WindowController', () => { it(`should only be callable once`, () => { const registration = makeFakeSWReg(); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.useServiceWorker(registration); @@ -167,9 +146,7 @@ describe('Firebase Messaging > *WindowController', () => { const compFunc = (): void => {}; const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); const onMessageStub = stub(controller as any, 'onMessage'); controller.onMessage(nextFunc, errFunc, compFunc); @@ -188,9 +165,7 @@ describe('Firebase Messaging > *WindowController', () => { const compFunc = (): void => {}; const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); const onTokenRefreshStub = stub(controller as any, 'onTokenRefresh'); controller.onTokenRefresh(nextFunc, errFunc, compFunc); @@ -205,9 +180,7 @@ describe('Firebase Messaging > *WindowController', () => { describe('usePublicVapidKey()', () => { it('should throw an error when passing in an invalid value', () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); let thrownError; @@ -222,9 +195,7 @@ describe('Firebase Messaging > *WindowController', () => { it('should throw an error when called twice', () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.usePublicVapidKey(VALID_VAPID_KEY); @@ -242,9 +213,7 @@ describe('Firebase Messaging > *WindowController', () => { it('should throw when decrypting to invalid value', () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); let thrownError; @@ -265,9 +234,7 @@ describe('Firebase Messaging > *WindowController', () => { describe('getPublicVapidKey_()', () => { it('should return the default key by default', () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); return controller.getPublicVapidKey_().then(pubKey => { expect(pubKey).to.equal(DEFAULT_PUBLIC_VAPID_KEY); @@ -276,9 +243,7 @@ describe('Firebase Messaging > *WindowController', () => { it('should return the custom key if set', () => { const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.usePublicVapidKey(VALID_VAPID_KEY); return controller.getPublicVapidKey_().then(pubKey => { @@ -295,9 +260,7 @@ describe('Firebase Messaging > *WindowController', () => { }); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.setupSWMessageListener_(); @@ -313,9 +276,7 @@ describe('Firebase Messaging > *WindowController', () => { }); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.onMessage(onMessageSpy, null as any, null as any); controller.setupSWMessageListener_(); @@ -339,9 +300,7 @@ describe('Firebase Messaging > *WindowController', () => { }); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); controller.setupSWMessageListener_(); const callback = messageCallbackSpy.args[0][1]; @@ -366,9 +325,7 @@ describe('Firebase Messaging > *WindowController', () => { }); const controller = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); // The API for the observables means it's async and so we kind have to @@ -416,9 +373,7 @@ describe('Firebase Messaging > *WindowController', () => { const fakeReg = makeFakeSWReg('installing', swValue); const messagingService = new WindowController( - app, - installations, - analyticsProvider + fakeFirebaseServices ); const waitPromise = messagingService.waitForRegistrationToActivate_( fakeReg From ae1478bbc621e440eb6b5c13ec01474122332d50 Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Tue, 5 Nov 2019 12:36:38 -0800 Subject: [PATCH 4/6] [AUTOMATED]: Prettier Code Styling --- packages/messaging/index.ts | 2 +- .../src/controllers/base-controller.ts | 9 +-- .../src/controllers/sw-controller.ts | 1 - .../src/interfaces/external-services.ts | 8 +- .../src/models/clean-v1-undefined.ts | 9 +-- .../src/models/subscription-manager.ts | 7 +- .../src/models/token-details-model.ts | 4 +- packages/messaging/test/constructor.test.ts | 6 +- .../test/controller-delete-token.test.ts | 32 ++------ .../test/controller-get-token.test.ts | 66 ++++++--------- .../test/controller-interface.test.ts | 18 ++--- packages/messaging/test/get-sw-reg.test.ts | 28 ++----- .../test/subscription-manager.test.ts | 19 +++-- packages/messaging/test/sw-controller.test.ts | 4 +- .../make-fake-firebase-services.ts | 15 ++-- .../test/token-details-model.test.ts | 8 +- .../messaging/test/window-controller.test.ts | 81 +++++-------------- 17 files changed, 109 insertions(+), 208 deletions(-) diff --git a/packages/messaging/index.ts b/packages/messaging/index.ts index 253a7bc58be..d0d00b4108b 100644 --- a/packages/messaging/index.ts +++ b/packages/messaging/index.ts @@ -40,7 +40,7 @@ export function registerMessaging(instance: _FirebaseNamespace): void { const installations = container.getProvider('installations').getImmediate(); const analyticsProvider = container.getProvider('analytics-internal'); - const firebaseServices = { app, installations, analyticsProvider}; + const firebaseServices = { app, installations, analyticsProvider }; if (!isSupported()) { throw errorFactory.create(ErrorCode.UNSUPPORTED_BROWSER); diff --git a/packages/messaging/src/controllers/base-controller.ts b/packages/messaging/src/controllers/base-controller.ts index 0386b815319..8ba7e4c7336 100644 --- a/packages/messaging/src/controllers/base-controller.ts +++ b/packages/messaging/src/controllers/base-controller.ts @@ -49,9 +49,7 @@ export abstract class BaseController implements FirebaseMessaging { private readonly vapidDetailsModel = new VapidDetailsModel(); private readonly subscriptionManager = new SubscriptionManager(); - constructor( - protected readonly services: FirebaseInternalServices - ) { + constructor(protected readonly services: FirebaseInternalServices) { const { app } = services; this.app = app; if ( @@ -234,10 +232,7 @@ export abstract class BaseController implements FirebaseMessaging { */ private async deleteTokenFromDB(token: string): Promise { const tokenDetails = await this.tokenDetailsModel.deleteToken(token); - await this.subscriptionManager.deleteToken( - this.services, - tokenDetails - ); + await this.subscriptionManager.deleteToken(this.services, tokenDetails); } // Visible for testing diff --git a/packages/messaging/src/controllers/sw-controller.ts b/packages/messaging/src/controllers/sw-controller.ts index 05ea36bd87e..31566478233 100644 --- a/packages/messaging/src/controllers/sw-controller.ts +++ b/packages/messaging/src/controllers/sw-controller.ts @@ -36,7 +36,6 @@ const FCM_MSG = 'FCM_MSG'; export class SwController extends BaseController { private bgMessageHandler: BgMessageHandler | null = null; - constructor(services: FirebaseInternalServices) { super(services); diff --git a/packages/messaging/src/interfaces/external-services.ts b/packages/messaging/src/interfaces/external-services.ts index ec3e9891369..a46eebb8982 100644 --- a/packages/messaging/src/interfaces/external-services.ts +++ b/packages/messaging/src/interfaces/external-services.ts @@ -4,7 +4,7 @@ import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; import { Provider } from '@firebase/component'; export interface FirebaseInternalServices { - app: FirebaseApp, - installations: FirebaseInstallations, - analyticsProvider: Provider -} \ No newline at end of file + app: FirebaseApp; + installations: FirebaseInstallations; + analyticsProvider: Provider; +} diff --git a/packages/messaging/src/models/clean-v1-undefined.ts b/packages/messaging/src/models/clean-v1-undefined.ts index 4092c0e82df..e8badb4c08c 100644 --- a/packages/messaging/src/models/clean-v1-undefined.ts +++ b/packages/messaging/src/models/clean-v1-undefined.ts @@ -33,10 +33,7 @@ import { FirebaseInternalServices } from '../interfaces/external-services'; const OLD_DB_NAME = 'undefined'; const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store'; -function handleDb( - db: IDBDatabase, - services: FirebaseInternalServices -): void { +function handleDb(db: IDBDatabase, services: FirebaseInternalServices): void { if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) { // We found a database with the name 'undefined', but our expected object // store isn't defined. @@ -72,9 +69,7 @@ function handleDb( }; } -export function cleanV1( - services: FirebaseInternalServices -): void { +export function cleanV1(services: FirebaseInternalServices): void { const request: IDBOpenDBRequest = indexedDB.open(OLD_DB_NAME); request.onerror = _event => { // NOOP - Nothing we can do. diff --git a/packages/messaging/src/models/subscription-manager.ts b/packages/messaging/src/models/subscription-manager.ts index 088e0e5821a..4ed30df2135 100644 --- a/packages/messaging/src/models/subscription-manager.ts +++ b/packages/messaging/src/models/subscription-manager.ts @@ -157,9 +157,10 @@ function getEndpoint(app: FirebaseApp): string { return `${ENDPOINT}/projects/${app.options.projectId!}/registrations`; } -async function getHeaders( - { app, installations }: FirebaseInternalServices, -): Promise { +async function getHeaders({ + app, + installations +}: FirebaseInternalServices): Promise { const authToken = await installations.getToken(); return new Headers({ diff --git a/packages/messaging/src/models/token-details-model.ts b/packages/messaging/src/models/token-details-model.ts index 13d0810111b..2123cdc910a 100644 --- a/packages/messaging/src/models/token-details-model.ts +++ b/packages/messaging/src/models/token-details-model.ts @@ -27,9 +27,7 @@ export class TokenDetailsModel extends DbInterface { protected readonly dbVersion: number = 4; protected readonly objectStoreName: string = 'fcm_token_object_Store'; - constructor( - private readonly services: FirebaseInternalServices - ) { + constructor(private readonly services: FirebaseInternalServices) { super(); } diff --git a/packages/messaging/test/constructor.test.ts b/packages/messaging/test/constructor.test.ts index 59bf5086041..3984e5c071d 100644 --- a/packages/messaging/test/constructor.test.ts +++ b/packages/messaging/test/constructor.test.ts @@ -51,7 +51,11 @@ describe('Firebase Messaging > new *Controller()', () => { ]; badInputs.forEach(badInput => { try { - new WindowController({ app: badInput, installations, analyticsProvider }); + new WindowController({ + app: badInput, + installations, + analyticsProvider + }); new SwController({ app: badInput, installations, analyticsProvider }); assert.fail( diff --git a/packages/messaging/test/controller-delete-token.test.ts b/packages/messaging/test/controller-delete-token.test.ts index 206e59360aa..32a98aae2ac 100644 --- a/packages/messaging/test/controller-delete-token.test.ts +++ b/packages/messaging/test/controller-delete-token.test.ts @@ -25,9 +25,7 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { deleteDatabase } from './testing-utils/db-helper'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { TokenDetails } from '../src/interfaces/token-details'; @@ -95,9 +93,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { }); it('should handle no token to delete', () => { - messagingService = new WindowController( - firebaseInternalServices - ); + messagingService = new WindowController(firebaseInternalServices); return messagingService.deleteToken(undefined as any).then( () => { throw new Error('Expected error to be thrown.'); @@ -120,9 +116,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new WindowController( - firebaseInternalServices - ); + messagingService = new WindowController(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -143,9 +137,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new WindowController( - firebaseInternalServices - ); + messagingService = new WindowController(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -174,9 +166,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass( - firebaseInternalServices - ); + messagingService = new serviceClass(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); @@ -205,9 +195,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass( - firebaseInternalServices - ); + messagingService = new serviceClass(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -241,9 +229,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { throw new Error(errorMsg); }); - messagingService = new serviceClass( - firebaseInternalServices - ); + messagingService = new serviceClass(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken).then( () => { throw new Error('Expected this to reject'); @@ -276,9 +262,7 @@ describe('Firebase Messaging > *Controller.deleteToken()', () => { async () => {} ); - messagingService = new serviceClass( - firebaseInternalServices - ); + messagingService = new serviceClass(firebaseInternalServices); return messagingService.deleteToken(EXAMPLE_TOKEN_SAVE.fcmToken); }); }); diff --git a/packages/messaging/test/controller-get-token.test.ts b/packages/messaging/test/controller-get-token.test.ts index 499a6bde901..91f4814b209 100644 --- a/packages/messaging/test/controller-get-token.test.ts +++ b/packages/messaging/test/controller-get-token.test.ts @@ -29,9 +29,7 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { FirebaseInternalServices } from '../src/interfaces/external-services'; @@ -88,7 +86,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { EXAMPLE_SENDER_ID = '1234567890'; CUSTOM_VAPID_KEY = base64ToArrayBuffer( 'BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXK' + - 'pNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo' + 'pNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo' ); ENDPOINT = FAKE_SUBSCRIPTION.endpoint; AUTH = FAKE_SUBSCRIPTION.getKey('auth')!; @@ -143,9 +141,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { Promise.reject('No Service Worker') ); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); try { await messagingService.getToken(); throw new Error('Expected getToken to throw '); @@ -169,9 +165,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { notificationStub.onCall(3).returns('default'); return servicesToTest.reduce(async (chain, serviceClass) => { - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); stub(serviceClass.prototype, 'getPublicVapidKey_').callsFake(() => Promise.resolve(DEFAULT_PUBLIC_VAPID_KEY) ); @@ -218,9 +212,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { 'getTokenDetailsFromSWScope' ).callsFake(() => Promise.resolve(details)); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const token = await serviceInstance.getToken(); assert.equal(details.fcmToken, token); }); @@ -246,9 +238,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { () => Promise.resolve(EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID) ); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_TOKEN_DETAILS_CUSTOM_VAPID.fcmToken, token); }); @@ -281,16 +271,14 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(TokenDetailsModel.prototype, 'saveTokenDetails').callsFake( - async () => { } + async () => {} ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => { } + async () => {} ); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const token = await serviceInstance.getToken(); assert.equal(EXAMPLE_FCM_TOKEN, token); }); @@ -327,7 +315,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveVapidDetailsStub = stub( VapidDetailsModel.prototype, 'saveVapidDetails' - ).callsFake(async () => { }); + ).callsFake(async () => {}); stub(SubscriptionManager.prototype, 'getToken').callsFake(() => Promise.resolve(GET_TOKEN_RESPONSE) @@ -341,11 +329,9 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveTokenDetailsStub = stub( TokenDetailsModel.prototype, 'saveTokenDetails' - ).callsFake(async () => { }); + ).callsFake(async () => {}); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const token = await serviceInstance.getToken(); assert.equal('example-token', token); @@ -383,7 +369,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { TokenDetailsModel.prototype, 'saveTokenDetails' ); - saveTokenDetailsStub.callsFake(async () => { }); + saveTokenDetailsStub.callsFake(async () => {}); stub(BaseController.prototype, 'getNotificationPermission_').callsFake( () => 'granted' @@ -403,14 +389,14 @@ describe('Firebase Messaging > *Controller.getToken()', () => { const saveVapidDetailsStub = stub( VapidDetailsModel.prototype, 'saveVapidDetails' - ).callsFake(async () => { }); + ).callsFake(async () => {}); const GET_TOKEN_RESPONSE = 'new-token'; stub(SubscriptionManager.prototype, 'getToken').callsFake(() => Promise.resolve(GET_TOKEN_RESPONSE) ); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => { } + async () => {} ); const registration = generateFakeReg(); @@ -436,9 +422,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { 'getTokenDetailsFromSWScope' ).callsFake(() => Promise.resolve(details)); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const token = await serviceInstance.getToken(); // make sure we call getToken and retrieve the new token. assert.equal('new-token', token); @@ -476,7 +460,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => { } + async () => {} ); stub(TokenDetailsModel.prototype, 'getTokenDetailsFromSWScope').callsFake( @@ -487,9 +471,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { Promise.resolve(subscription) ); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); const defaultVAPIDToken = await serviceInstance.getToken(); assert.equal( defaultVAPIDToken, @@ -505,7 +487,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { TokenDetailsModel.prototype, 'saveTokenDetails' ); - saveTokenDetailsStub.callsFake(async () => { }); + saveTokenDetailsStub.callsFake(async () => {}); const deleteTokenStub = stub(TokenDetailsModel.prototype, 'deleteToken'); deleteTokenStub.callsFake(token => { @@ -514,7 +496,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { }); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => { } + async () => {} ); stub(SubscriptionManager.prototype, 'getToken').callsFake(() => @@ -559,7 +541,7 @@ describe('Firebase Messaging > *Controller.getToken()', () => { ); stub(VapidDetailsModel.prototype, 'saveVapidDetails').callsFake( - async () => { } + async () => {} ); stub(SubscriptionManager.prototype, 'updateToken').callsFake(() => @@ -573,12 +555,10 @@ describe('Firebase Messaging > *Controller.getToken()', () => { }); stub(SubscriptionManager.prototype, 'deleteToken').callsFake( - async () => { } + async () => {} ); - const serviceInstance = new serviceClass( - firebaseInternalServices - ); + const serviceInstance = new serviceClass(firebaseInternalServices); try { await serviceInstance.getToken(); throw new Error('Expected error to be thrown.'); diff --git a/packages/messaging/test/controller-interface.test.ts b/packages/messaging/test/controller-interface.test.ts index 76ec9717de9..3dbc7f1e758 100644 --- a/packages/messaging/test/controller-interface.test.ts +++ b/packages/messaging/test/controller-interface.test.ts @@ -26,9 +26,7 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { TokenDetailsModel } from '../src/models/token-details-model'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { FirebaseInternalServices } from '../src/interfaces/external-services'; @@ -95,9 +93,7 @@ describe('Firebase Messaging > *BaseController', () => { } }); - const controller = new controllerInTest( - firebaseInternalServices - ); + const controller = new controllerInTest(firebaseInternalServices); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then( @@ -117,9 +113,7 @@ describe('Firebase Messaging > *BaseController', () => { getSubscription: async () => exampleSubscription }); - const controller = new controllerInTest( - firebaseInternalServices - ); + const controller = new controllerInTest(firebaseInternalServices); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then(subscription => { @@ -131,7 +125,7 @@ describe('Firebase Messaging > *BaseController', () => { const exampleSubscription = {}; const reg = makeFakeSWReg(); stub(reg, 'pushManager').value({ - getSubscription: async () => { }, + getSubscription: async () => {}, subscribe: async (options: PushSubscriptionOptions) => { expect(options).to.deep.equal({ userVisibleOnly: true, @@ -142,9 +136,7 @@ describe('Firebase Messaging > *BaseController', () => { } }); - const controller = new controllerInTest( - firebaseInternalServices - ); + const controller = new controllerInTest(firebaseInternalServices); return controller .getPushSubscription(reg, DEFAULT_PUBLIC_VAPID_KEY) .then(subscription => { diff --git a/packages/messaging/test/get-sw-reg.test.ts b/packages/messaging/test/get-sw-reg.test.ts index ba08e7f5af7..c50474536a4 100644 --- a/packages/messaging/test/get-sw-reg.test.ts +++ b/packages/messaging/test/get-sw-reg.test.ts @@ -21,9 +21,7 @@ import { SwController } from '../src/controllers/sw-controller'; import { WindowController } from '../src/controllers/window-controller'; import { ErrorCode } from '../src/models/errors'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; const EXAMPLE_SENDER_ID = '1234567890'; @@ -64,9 +62,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { mockWindowRegistration(activatedRegistration); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService .getSWRegistration_() .then(registration => { @@ -86,9 +82,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const fakeReg = makeFakeSWReg(); mockWindowRegistration(fakeReg); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService.getSWRegistration_().then( () => { throw new Error('Expected this error to throw due to no SW.'); @@ -125,9 +119,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { throw new Error(errorMsg); }); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService.getSWRegistration_().then( () => { throw new Error('Expect getSWRegistration_ to reject.'); @@ -148,9 +140,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { }); mockWindowRegistration(redundantRegistration); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); @@ -176,9 +166,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const slowRedundantRegistration = makeFakeSWReg('installing', swValue); mockWindowRegistration(slowRedundantRegistration); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); @@ -204,9 +192,7 @@ describe('Firebase Messaging > *Controller.getSWReg_()', () => { const slowRedundantRegistration = makeFakeSWReg('waiting', swValue); mockWindowRegistration(slowRedundantRegistration); - const messagingService = new WindowController( - firebaseInternalServices - ); + const messagingService = new WindowController(firebaseInternalServices); return messagingService.getSWRegistration_().then( () => { throw new Error('Should throw error due to redundant SW'); diff --git a/packages/messaging/test/subscription-manager.test.ts b/packages/messaging/test/subscription-manager.test.ts index f8303872f39..a1298cb272b 100644 --- a/packages/messaging/test/subscription-manager.test.ts +++ b/packages/messaging/test/subscription-manager.test.ts @@ -23,9 +23,7 @@ import { SubscriptionManager } from '../src/models/subscription-manager'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { fetchMock } from './testing-utils/mock-fetch'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { TokenDetails } from '../src/interfaces/token-details'; import { FirebaseInternalServices } from '../src/interfaces/external-services'; @@ -239,7 +237,10 @@ describe('Firebase Messaging > SubscriptionManager', () => { describe('deleteToken', () => { it('deletes on valid request', async () => { stub(window, 'fetch').returns(fetchMock.jsonOk('{}')); - await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); + await subscriptionManager.deleteToken( + firebaseInternalServices, + tokenDetails + ); }); it('handles fetch errors', async () => { @@ -248,7 +249,10 @@ describe('Firebase Messaging > SubscriptionManager', () => { stub(window, 'fetch').returns(fetchMock.jsonError(400, errorMsg)); try { - await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); + await subscriptionManager.deleteToken( + firebaseInternalServices, + tokenDetails + ); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); @@ -259,7 +263,10 @@ describe('Firebase Messaging > SubscriptionManager', () => { const stubbedFetch = stub(window, 'fetch'); stubbedFetch.returns(fetchMock.htmlError(404, 'html-response')); try { - await subscriptionManager.deleteToken(firebaseInternalServices, tokenDetails); + await subscriptionManager.deleteToken( + firebaseInternalServices, + tokenDetails + ); throw new Error('Expected error to be thrown.'); } catch (e) { expect(e.code).to.include(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED); diff --git a/packages/messaging/test/sw-controller.test.ts b/packages/messaging/test/sw-controller.test.ts index ae8437f432f..a1eb30d7ed7 100644 --- a/packages/messaging/test/sw-controller.test.ts +++ b/packages/messaging/test/sw-controller.test.ts @@ -23,9 +23,7 @@ declare const self: ServiceWorkerGlobalScope; import { expect } from 'chai'; import { stub, restore, spy, SinonSpy } from 'sinon'; import { FirebaseError } from '@firebase/util'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { SwController } from '../src/controllers/sw-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; diff --git a/packages/messaging/test/testing-utils/make-fake-firebase-services.ts b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts index eedd1017ae2..efe1258ed46 100644 --- a/packages/messaging/test/testing-utils/make-fake-firebase-services.ts +++ b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts @@ -21,12 +21,14 @@ import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; import { Provider, ComponentContainer } from '@firebase/component'; import { FirebaseInternalServices } from '../../src/interfaces/external-services'; -export function makeFakeFirebaseInternalServices(options: FirebaseOptions = {}): FirebaseInternalServices { - return { - app: makeFakeApp(options), - installations: makeFakeInstallations(), - analyticsProvider: makeFakeAnalyticsProvider() - }; +export function makeFakeFirebaseInternalServices( + options: FirebaseOptions = {} +): FirebaseInternalServices { + return { + app: makeFakeApp(options), + installations: makeFakeInstallations(), + analyticsProvider: makeFakeAnalyticsProvider() + }; } export function makeFakeApp(options: FirebaseOptions = {}): FirebaseApp { @@ -66,4 +68,3 @@ export function makeFakeAnalyticsProvider(): Provider< new ComponentContainer('test') ); } - diff --git a/packages/messaging/test/token-details-model.test.ts b/packages/messaging/test/token-details-model.test.ts index 437d85c4270..e499f997d09 100644 --- a/packages/messaging/test/token-details-model.test.ts +++ b/packages/messaging/test/token-details-model.test.ts @@ -25,9 +25,7 @@ import { TokenDetailsModel } from '../src/models/token-details-model'; import { deleteDatabase } from './testing-utils/db-helper'; import { compareDetails } from './testing-utils/detail-comparator'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { FirebaseInternalServices } from '../src/interfaces/external-services'; const BAD_INPUTS: any[] = ['', [], {}, true, null, 123]; @@ -50,7 +48,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { swScope: '/example-scope', vapidKey: base64ToArrayBuffer( 'BNJxw7sCGkGLOUP2cawBaBXRuWZ3lw_PmQMgreLVVvX_b' + - '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' + '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' ), fcmSenderId: '1234567', fcmToken: 'qwerty', @@ -121,7 +119,7 @@ describe('Firebase Messaging > TokenDetailsModel', () => { swScope: '/example-scope', vapidKey: base64ToArrayBuffer( 'BNJxw7sCGkGLOUP2cawBaBXRuWZ3lw_PmQMgreLVVvX_b' + - '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' + '4emEWVURkCF8fUTHEFe2xrEgTt5ilh5xD94v0pFe_I' ), fcmSenderId: '1234567', fcmToken: 'qwerty', diff --git a/packages/messaging/test/window-controller.test.ts b/packages/messaging/test/window-controller.test.ts index 8d64d50d040..f3dcde14870 100644 --- a/packages/messaging/test/window-controller.test.ts +++ b/packages/messaging/test/window-controller.test.ts @@ -16,21 +16,20 @@ */ import { expect } from 'chai'; import { stub, restore, spy } from 'sinon'; -import { - makeFakeFirebaseInternalServices -} from './testing-utils/make-fake-firebase-services'; +import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { WindowController } from '../src/controllers/window-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { MessageType } from '../src/models/worker-page-message'; - const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; describe('Firebase Messaging > *WindowController', () => { - const fakeFirebaseServices = makeFakeFirebaseInternalServices({messagingSenderId: '12345'}); + const fakeFirebaseServices = makeFakeFirebaseInternalServices({ + messagingSenderId: '12345' + }); const cleanup = (): void => { restore(); @@ -48,9 +47,7 @@ describe('Firebase Messaging > *WindowController', () => { it('should resolve if the permission is already granted', () => { stub(Notification as any, 'permission').value('granted'); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); return controller.requestPermission(); }); @@ -60,9 +57,7 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('denied') ); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); return controller.requestPermission().then( () => { throw new Error('Expected an error.'); @@ -79,9 +74,7 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('default') ); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); return controller.requestPermission().then( () => { throw new Error('Expected an error.'); @@ -98,18 +91,14 @@ describe('Firebase Messaging > *WindowController', () => { Promise.resolve('granted') ); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); return controller.requestPermission(); }); }); describe('useServiceWorker()', () => { it(`should throw on invalid input`, () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); let thrownError; try { controller.useServiceWorker(null as any); @@ -122,9 +111,7 @@ describe('Firebase Messaging > *WindowController', () => { it(`should only be callable once`, () => { const registration = makeFakeSWReg(); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.useServiceWorker(registration); let thrownError; @@ -145,9 +132,7 @@ describe('Firebase Messaging > *WindowController', () => { const errFunc = (): void => {}; const compFunc = (): void => {}; - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); const onMessageStub = stub(controller as any, 'onMessage'); controller.onMessage(nextFunc, errFunc, compFunc); @@ -164,9 +149,7 @@ describe('Firebase Messaging > *WindowController', () => { const errFunc = (): void => {}; const compFunc = (): void => {}; - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); const onTokenRefreshStub = stub(controller as any, 'onTokenRefresh'); controller.onTokenRefresh(nextFunc, errFunc, compFunc); @@ -179,9 +162,7 @@ describe('Firebase Messaging > *WindowController', () => { describe('usePublicVapidKey()', () => { it('should throw an error when passing in an invalid value', () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); let thrownError; try { @@ -194,9 +175,7 @@ describe('Firebase Messaging > *WindowController', () => { }); it('should throw an error when called twice', () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.usePublicVapidKey(VALID_VAPID_KEY); let thrownError; @@ -212,9 +191,7 @@ describe('Firebase Messaging > *WindowController', () => { }); it('should throw when decrypting to invalid value', () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); let thrownError; try { @@ -233,18 +210,14 @@ describe('Firebase Messaging > *WindowController', () => { describe('getPublicVapidKey_()', () => { it('should return the default key by default', () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); return controller.getPublicVapidKey_().then(pubKey => { expect(pubKey).to.equal(DEFAULT_PUBLIC_VAPID_KEY); }); }); it('should return the custom key if set', () => { - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.usePublicVapidKey(VALID_VAPID_KEY); return controller.getPublicVapidKey_().then(pubKey => { expect(pubKey).deep.equal(base64ToArrayBuffer(VALID_VAPID_KEY)); @@ -259,9 +232,7 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: sinonSpy }); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.setupSWMessageListener_(); expect(sinonSpy.args[0][0]).to.equal('message'); @@ -275,9 +246,7 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: sinonSpy }); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.onMessage(onMessageSpy, null as any, null as any); controller.setupSWMessageListener_(); @@ -299,9 +268,7 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: messageCallbackSpy }); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); controller.setupSWMessageListener_(); const callback = messageCallbackSpy.args[0][1]; @@ -324,9 +291,7 @@ describe('Firebase Messaging > *WindowController', () => { addEventListener: messageCallbackSpy }); - const controller = new WindowController( - fakeFirebaseServices - ); + const controller = new WindowController(fakeFirebaseServices); // The API for the observables means it's async and so we kind have to // hope that everything is set up after a task skip @@ -372,9 +337,7 @@ describe('Firebase Messaging > *WindowController', () => { const fakeReg = makeFakeSWReg('installing', swValue); - const messagingService = new WindowController( - fakeFirebaseServices - ); + const messagingService = new WindowController(fakeFirebaseServices); const waitPromise = messagingService.waitForRegistrationToActivate_( fakeReg ); From 8f15f6eccc67a916fdf787ea3576773c1bc4feb0 Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Tue, 5 Nov 2019 12:36:40 -0800 Subject: [PATCH 5/6] [AUTOMATED]: License Headers --- .../src/interfaces/external-services.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/messaging/src/interfaces/external-services.ts b/packages/messaging/src/interfaces/external-services.ts index a46eebb8982..b122ddaae83 100644 --- a/packages/messaging/src/interfaces/external-services.ts +++ b/packages/messaging/src/interfaces/external-services.ts @@ -1,3 +1,20 @@ +/** + * @license + * Copyright 2019 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { FirebaseApp } from '@firebase/app-types'; import { FirebaseInstallations } from '@firebase/installations-types'; import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; From e1d2bcf30a0d9a57b2936909ad59495bc540e099 Mon Sep 17 00:00:00 2001 From: Feiyang1 Date: Wed, 6 Nov 2019 13:35:07 -0800 Subject: [PATCH 6/6] address comment --- packages/messaging/index.ts | 7 ++++++- packages/messaging/src/controllers/base-controller.ts | 4 ++-- packages/messaging/src/controllers/sw-controller.ts | 2 +- packages/messaging/src/controllers/window-controller.ts | 2 +- .../{external-services.ts => internal-services.ts} | 0 packages/messaging/src/models/clean-v1-undefined.ts | 2 +- packages/messaging/src/models/subscription-manager.ts | 2 +- packages/messaging/src/models/token-details-model.ts | 2 +- packages/messaging/test/controller-delete-token.test.ts | 2 +- packages/messaging/test/controller-get-token.test.ts | 2 +- packages/messaging/test/controller-interface.test.ts | 2 +- packages/messaging/test/subscription-manager.test.ts | 2 +- packages/messaging/test/sw-controller.test.ts | 2 +- .../test/testing-utils/make-fake-firebase-services.ts | 2 +- packages/messaging/test/token-details-model.test.ts | 2 +- 15 files changed, 20 insertions(+), 15 deletions(-) rename packages/messaging/src/interfaces/{external-services.ts => internal-services.ts} (100%) diff --git a/packages/messaging/index.ts b/packages/messaging/index.ts index d0d00b4108b..2d6ca89aabd 100644 --- a/packages/messaging/index.ts +++ b/packages/messaging/index.ts @@ -30,6 +30,7 @@ import { ComponentType, ComponentContainer } from '@firebase/component'; +import { FirebaseInternalServices } from './src/interfaces/internal-services'; export function registerMessaging(instance: _FirebaseNamespace): void { const messagingName = 'messaging'; @@ -40,7 +41,11 @@ export function registerMessaging(instance: _FirebaseNamespace): void { const installations = container.getProvider('installations').getImmediate(); const analyticsProvider = container.getProvider('analytics-internal'); - const firebaseServices = { app, installations, analyticsProvider }; + const firebaseServices: FirebaseInternalServices = { + app, + installations, + analyticsProvider + }; if (!isSupported()) { throw errorFactory.create(ErrorCode.UNSUPPORTED_BROWSER); diff --git a/packages/messaging/src/controllers/base-controller.ts b/packages/messaging/src/controllers/base-controller.ts index 8ba7e4c7336..f0ee2b3e6e2 100644 --- a/packages/messaging/src/controllers/base-controller.ts +++ b/packages/messaging/src/controllers/base-controller.ts @@ -33,7 +33,7 @@ import { ErrorCode, errorFactory } from '../models/errors'; import { SubscriptionManager } from '../models/subscription-manager'; import { TokenDetailsModel } from '../models/token-details-model'; import { VapidDetailsModel } from '../models/vapid-details-model'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; export type BgMessageHandler = ( payload: MessagePayload @@ -44,7 +44,7 @@ export const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days export abstract class BaseController implements FirebaseMessaging { INTERNAL: FirebaseServiceInternals; - readonly app!: FirebaseApp; + readonly app: FirebaseApp; private readonly tokenDetailsModel: TokenDetailsModel; private readonly vapidDetailsModel = new VapidDetailsModel(); private readonly subscriptionManager = new SubscriptionManager(); diff --git a/packages/messaging/src/controllers/sw-controller.ts b/packages/messaging/src/controllers/sw-controller.ts index 31566478233..8c2b291550b 100644 --- a/packages/messaging/src/controllers/sw-controller.ts +++ b/packages/messaging/src/controllers/sw-controller.ts @@ -27,7 +27,7 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController, BgMessageHandler } from './base-controller'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; // Let TS know that this is a service worker declare const self: ServiceWorkerGlobalScope; diff --git a/packages/messaging/src/controllers/window-controller.ts b/packages/messaging/src/controllers/window-controller.ts index 93989964d66..2b97786effd 100644 --- a/packages/messaging/src/controllers/window-controller.ts +++ b/packages/messaging/src/controllers/window-controller.ts @@ -38,7 +38,7 @@ import { } from '../models/fcm-details'; import { InternalMessage, MessageType } from '../models/worker-page-message'; import { BaseController } from './base-controller'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; export class WindowController extends BaseController { private registrationToUse: ServiceWorkerRegistration | null = null; diff --git a/packages/messaging/src/interfaces/external-services.ts b/packages/messaging/src/interfaces/internal-services.ts similarity index 100% rename from packages/messaging/src/interfaces/external-services.ts rename to packages/messaging/src/interfaces/internal-services.ts diff --git a/packages/messaging/src/models/clean-v1-undefined.ts b/packages/messaging/src/models/clean-v1-undefined.ts index e8badb4c08c..bbedc93c4b6 100644 --- a/packages/messaging/src/models/clean-v1-undefined.ts +++ b/packages/messaging/src/models/clean-v1-undefined.ts @@ -28,7 +28,7 @@ */ import { SubscriptionManager } from './subscription-manager'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; const OLD_DB_NAME = 'undefined'; const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store'; diff --git a/packages/messaging/src/models/subscription-manager.ts b/packages/messaging/src/models/subscription-manager.ts index 4ed30df2135..16a62732419 100644 --- a/packages/messaging/src/models/subscription-manager.ts +++ b/packages/messaging/src/models/subscription-manager.ts @@ -21,7 +21,7 @@ import { ErrorCode, errorFactory } from './errors'; import { DEFAULT_PUBLIC_VAPID_KEY, ENDPOINT } from './fcm-details'; import { FirebaseApp } from '@firebase/app-types'; import { TokenDetails } from '../interfaces/token-details'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; interface ApiResponse { token?: string; diff --git a/packages/messaging/src/models/token-details-model.ts b/packages/messaging/src/models/token-details-model.ts index 2123cdc910a..46c29ad9f3d 100644 --- a/packages/messaging/src/models/token-details-model.ts +++ b/packages/messaging/src/models/token-details-model.ts @@ -20,7 +20,7 @@ import { TokenDetails } from '../interfaces/token-details'; import { cleanV1 } from './clean-v1-undefined'; import { DbInterface } from './db-interface'; import { ErrorCode, errorFactory } from './errors'; -import { FirebaseInternalServices } from '../interfaces/external-services'; +import { FirebaseInternalServices } from '../interfaces/internal-services'; export class TokenDetailsModel extends DbInterface { protected readonly dbName: string = 'fcm_token_details_db'; diff --git a/packages/messaging/test/controller-delete-token.test.ts b/packages/messaging/test/controller-delete-token.test.ts index 32a98aae2ac..cc6b81b99b7 100644 --- a/packages/messaging/test/controller-delete-token.test.ts +++ b/packages/messaging/test/controller-delete-token.test.ts @@ -29,7 +29,7 @@ import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-fire import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; import { TokenDetails } from '../src/interfaces/token-details'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; let FAKE_SUBSCRIPTION: PushSubscription; let EXAMPLE_TOKEN_SAVE: TokenDetails; diff --git a/packages/messaging/test/controller-get-token.test.ts b/packages/messaging/test/controller-get-token.test.ts index 91f4814b209..95c56e378dd 100644 --- a/packages/messaging/test/controller-get-token.test.ts +++ b/packages/messaging/test/controller-get-token.test.ts @@ -32,7 +32,7 @@ import { VapidDetailsModel } from '../src/models/vapid-details-model'; import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; const ONE_DAY = 24 * 60 * 60 * 1000; diff --git a/packages/messaging/test/controller-interface.test.ts b/packages/messaging/test/controller-interface.test.ts index 3dbc7f1e758..824bdaa6d3f 100644 --- a/packages/messaging/test/controller-interface.test.ts +++ b/packages/messaging/test/controller-interface.test.ts @@ -28,7 +28,7 @@ import { VapidDetailsModel } from '../src/models/vapid-details-model'; import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; const controllersToTest = [WindowController, SwController]; diff --git a/packages/messaging/test/subscription-manager.test.ts b/packages/messaging/test/subscription-manager.test.ts index a1298cb272b..5c77bcb8a7b 100644 --- a/packages/messaging/test/subscription-manager.test.ts +++ b/packages/messaging/test/subscription-manager.test.ts @@ -26,7 +26,7 @@ import { fetchMock } from './testing-utils/mock-fetch'; import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { TokenDetails } from '../src/interfaces/token-details'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; // prettier-ignore const appPubKey = new Uint8Array([ diff --git a/packages/messaging/test/sw-controller.test.ts b/packages/messaging/test/sw-controller.test.ts index a1eb30d7ed7..bed0ecafabc 100644 --- a/packages/messaging/test/sw-controller.test.ts +++ b/packages/messaging/test/sw-controller.test.ts @@ -29,7 +29,7 @@ import { SwController } from '../src/controllers/sw-controller'; import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer'; import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details'; import { VapidDetailsModel } from '../src/models/vapid-details-model'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; const VALID_VAPID_KEY = 'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw'; diff --git a/packages/messaging/test/testing-utils/make-fake-firebase-services.ts b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts index efe1258ed46..d4ddebb7d35 100644 --- a/packages/messaging/test/testing-utils/make-fake-firebase-services.ts +++ b/packages/messaging/test/testing-utils/make-fake-firebase-services.ts @@ -19,7 +19,7 @@ import { FirebaseApp, FirebaseOptions } from '@firebase/app-types'; import { FirebaseInstallations } from '@firebase/installations-types'; import { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types'; import { Provider, ComponentContainer } from '@firebase/component'; -import { FirebaseInternalServices } from '../../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../../src/interfaces/internal-services'; export function makeFakeFirebaseInternalServices( options: FirebaseOptions = {} diff --git a/packages/messaging/test/token-details-model.test.ts b/packages/messaging/test/token-details-model.test.ts index e499f997d09..19356552d4b 100644 --- a/packages/messaging/test/token-details-model.test.ts +++ b/packages/messaging/test/token-details-model.test.ts @@ -26,7 +26,7 @@ import { deleteDatabase } from './testing-utils/db-helper'; import { compareDetails } from './testing-utils/detail-comparator'; import { makeFakeSubscription } from './testing-utils/make-fake-subscription'; import { makeFakeFirebaseInternalServices } from './testing-utils/make-fake-firebase-services'; -import { FirebaseInternalServices } from '../src/interfaces/external-services'; +import { FirebaseInternalServices } from '../src/interfaces/internal-services'; const BAD_INPUTS: any[] = ['', [], {}, true, null, 123];