@depup/firebase__messaging 0.12.24-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +32 -0
  2. package/changes.json +14 -0
  3. package/dist/esm/index.esm.js +1270 -0
  4. package/dist/esm/index.esm.js.map +1 -0
  5. package/dist/esm/index.sw.esm.js +1278 -0
  6. package/dist/esm/index.sw.esm.js.map +1 -0
  7. package/dist/esm/package.json +1 -0
  8. package/dist/esm/src/api/deleteToken.d.ts +18 -0
  9. package/dist/esm/src/api/getToken.d.ts +19 -0
  10. package/dist/esm/src/api/isSupported.d.ts +30 -0
  11. package/dist/esm/src/api/onBackgroundMessage.d.ts +19 -0
  12. package/dist/esm/src/api/onMessage.d.ts +19 -0
  13. package/dist/esm/src/api/setDeliveryMetricsExportedToBigQueryEnabled.d.ts +18 -0
  14. package/dist/esm/src/api.d.ts +101 -0
  15. package/dist/esm/src/helpers/array-base64-translator.d.ts +18 -0
  16. package/dist/esm/src/helpers/externalizePayload.d.ts +19 -0
  17. package/dist/esm/src/helpers/extract-app-config.d.ts +19 -0
  18. package/dist/esm/src/helpers/is-console-message.d.ts +18 -0
  19. package/dist/esm/src/helpers/logToFirelog.d.ts +30 -0
  20. package/dist/esm/src/helpers/logToScion.d.ts +19 -0
  21. package/dist/esm/src/helpers/migrate-old-database.d.ts +51 -0
  22. package/dist/esm/src/helpers/register.d.ts +23 -0
  23. package/dist/esm/src/helpers/registerDefaultSw.d.ts +18 -0
  24. package/dist/esm/src/helpers/sleep.d.ts +18 -0
  25. package/dist/esm/src/helpers/updateSwReg.d.ts +18 -0
  26. package/dist/esm/src/helpers/updateVapidKey.d.ts +18 -0
  27. package/dist/esm/src/index.d.ts +32 -0
  28. package/dist/esm/src/index.sw.d.ts +26 -0
  29. package/dist/esm/src/interfaces/app-config.d.ts +24 -0
  30. package/dist/esm/src/interfaces/internal-dependencies.d.ts +27 -0
  31. package/dist/esm/src/interfaces/internal-message-payload.d.ts +65 -0
  32. package/dist/esm/src/interfaces/logging-types.d.ts +60 -0
  33. package/dist/esm/src/interfaces/public-types.d.ts +144 -0
  34. package/dist/esm/src/interfaces/token-details.d.ts +32 -0
  35. package/dist/esm/src/internals/idb-manager.d.ts +27 -0
  36. package/dist/esm/src/internals/requests.d.ts +35 -0
  37. package/dist/esm/src/internals/token-manager.d.ts +23 -0
  38. package/dist/esm/src/listeners/sw-listeners.d.ts +21 -0
  39. package/dist/esm/src/listeners/window-listener.d.ts +18 -0
  40. package/dist/esm/src/messaging-service.d.ts +36 -0
  41. package/dist/esm/src/testing/compare-headers.d.ts +22 -0
  42. package/dist/esm/src/testing/fakes/firebase-dependencies.d.ts +25 -0
  43. package/dist/esm/src/testing/fakes/logging-object.d.ts +18 -0
  44. package/dist/esm/src/testing/fakes/messaging-service.d.ts +18 -0
  45. package/dist/esm/src/testing/fakes/service-worker.d.ts +83 -0
  46. package/dist/esm/src/testing/fakes/token-details.d.ts +18 -0
  47. package/dist/esm/src/testing/setup.d.ts +17 -0
  48. package/dist/esm/src/testing/sinon-types.d.ts +19 -0
  49. package/dist/esm/src/util/constants.d.ts +40 -0
  50. package/dist/esm/src/util/errors.d.ts +57 -0
  51. package/dist/esm/src/util/sw-types.d.ts +90 -0
  52. package/dist/index-public.d.ts +204 -0
  53. package/dist/index.cjs.js +1278 -0
  54. package/dist/index.cjs.js.map +1 -0
  55. package/dist/index.sw.cjs +1285 -0
  56. package/dist/index.sw.cjs.map +1 -0
  57. package/dist/internal.d.ts +220 -0
  58. package/dist/private.d.ts +217 -0
  59. package/dist/src/api/deleteToken.d.ts +18 -0
  60. package/dist/src/api/getToken.d.ts +19 -0
  61. package/dist/src/api/isSupported.d.ts +30 -0
  62. package/dist/src/api/onBackgroundMessage.d.ts +19 -0
  63. package/dist/src/api/onMessage.d.ts +19 -0
  64. package/dist/src/api/setDeliveryMetricsExportedToBigQueryEnabled.d.ts +18 -0
  65. package/dist/src/api.d.ts +101 -0
  66. package/dist/src/helpers/array-base64-translator.d.ts +18 -0
  67. package/dist/src/helpers/externalizePayload.d.ts +19 -0
  68. package/dist/src/helpers/extract-app-config.d.ts +19 -0
  69. package/dist/src/helpers/is-console-message.d.ts +18 -0
  70. package/dist/src/helpers/logToFirelog.d.ts +30 -0
  71. package/dist/src/helpers/logToScion.d.ts +19 -0
  72. package/dist/src/helpers/migrate-old-database.d.ts +51 -0
  73. package/dist/src/helpers/register.d.ts +23 -0
  74. package/dist/src/helpers/registerDefaultSw.d.ts +18 -0
  75. package/dist/src/helpers/sleep.d.ts +18 -0
  76. package/dist/src/helpers/updateSwReg.d.ts +18 -0
  77. package/dist/src/helpers/updateVapidKey.d.ts +18 -0
  78. package/dist/src/index.d.ts +32 -0
  79. package/dist/src/index.sw.d.ts +26 -0
  80. package/dist/src/interfaces/app-config.d.ts +24 -0
  81. package/dist/src/interfaces/internal-dependencies.d.ts +27 -0
  82. package/dist/src/interfaces/internal-message-payload.d.ts +65 -0
  83. package/dist/src/interfaces/logging-types.d.ts +60 -0
  84. package/dist/src/interfaces/public-types.d.ts +144 -0
  85. package/dist/src/interfaces/token-details.d.ts +32 -0
  86. package/dist/src/internals/idb-manager.d.ts +27 -0
  87. package/dist/src/internals/requests.d.ts +35 -0
  88. package/dist/src/internals/token-manager.d.ts +23 -0
  89. package/dist/src/listeners/sw-listeners.d.ts +21 -0
  90. package/dist/src/listeners/window-listener.d.ts +18 -0
  91. package/dist/src/messaging-service.d.ts +36 -0
  92. package/dist/src/testing/compare-headers.d.ts +22 -0
  93. package/dist/src/testing/fakes/firebase-dependencies.d.ts +25 -0
  94. package/dist/src/testing/fakes/logging-object.d.ts +18 -0
  95. package/dist/src/testing/fakes/messaging-service.d.ts +18 -0
  96. package/dist/src/testing/fakes/service-worker.d.ts +83 -0
  97. package/dist/src/testing/fakes/token-details.d.ts +18 -0
  98. package/dist/src/testing/setup.d.ts +17 -0
  99. package/dist/src/testing/sinon-types.d.ts +19 -0
  100. package/dist/src/tsdoc-metadata.json +11 -0
  101. package/dist/src/util/constants.d.ts +40 -0
  102. package/dist/src/util/errors.d.ts +57 -0
  103. package/dist/src/util/sw-types.d.ts +90 -0
  104. package/dist/sw/index-public.d.ts +166 -0
  105. package/dist/sw/internal.d.ts +180 -0
  106. package/dist/sw/private.d.ts +177 -0
  107. package/package.json +103 -0
  108. package/sw/package.json +8 -0
@@ -0,0 +1,1278 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ require('@firebase/installations');
6
+ var component = require('@firebase/component');
7
+ var idb = require('idb');
8
+ var util = require('@firebase/util');
9
+ var app = require('@firebase/app');
10
+
11
+ /**
12
+ * @license
13
+ * Copyright 2019 Google LLC
14
+ *
15
+ * Licensed under the Apache License, Version 2.0 (the "License");
16
+ * you may not use this file except in compliance with the License.
17
+ * You may obtain a copy of the License at
18
+ *
19
+ * http://www.apache.org/licenses/LICENSE-2.0
20
+ *
21
+ * Unless required by applicable law or agreed to in writing, software
22
+ * distributed under the License is distributed on an "AS IS" BASIS,
23
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ * See the License for the specific language governing permissions and
25
+ * limitations under the License.
26
+ */
27
+ const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';
28
+ const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';
29
+ const DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';
30
+ const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';
31
+ const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';
32
+ const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';
33
+ const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';
34
+ /** Set to '1' if Analytics is enabled for the campaign */
35
+ const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';
36
+ const DEFAULT_REGISTRATION_TIMEOUT = 10000;
37
+ var MessageType$1;
38
+ (function (MessageType) {
39
+ MessageType[MessageType["DATA_MESSAGE"] = 1] = "DATA_MESSAGE";
40
+ MessageType[MessageType["DISPLAY_NOTIFICATION"] = 3] = "DISPLAY_NOTIFICATION";
41
+ })(MessageType$1 || (MessageType$1 = {}));
42
+
43
+ /**
44
+ * @license
45
+ * Copyright 2018 Google LLC
46
+ *
47
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
48
+ * in compliance with the License. You may obtain a copy of the License at
49
+ *
50
+ * http://www.apache.org/licenses/LICENSE-2.0
51
+ *
52
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
53
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
54
+ * or implied. See the License for the specific language governing permissions and limitations under
55
+ * the License.
56
+ */
57
+ var MessageType;
58
+ (function (MessageType) {
59
+ MessageType["PUSH_RECEIVED"] = "push-received";
60
+ MessageType["NOTIFICATION_CLICKED"] = "notification-clicked";
61
+ })(MessageType || (MessageType = {}));
62
+
63
+ /**
64
+ * @license
65
+ * Copyright 2017 Google LLC
66
+ *
67
+ * Licensed under the Apache License, Version 2.0 (the "License");
68
+ * you may not use this file except in compliance with the License.
69
+ * You may obtain a copy of the License at
70
+ *
71
+ * http://www.apache.org/licenses/LICENSE-2.0
72
+ *
73
+ * Unless required by applicable law or agreed to in writing, software
74
+ * distributed under the License is distributed on an "AS IS" BASIS,
75
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
+ * See the License for the specific language governing permissions and
77
+ * limitations under the License.
78
+ */
79
+ function arrayToBase64(array) {
80
+ const uint8Array = new Uint8Array(array);
81
+ const base64String = btoa(String.fromCharCode(...uint8Array));
82
+ return base64String.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
83
+ }
84
+ function base64ToArray(base64String) {
85
+ const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
86
+ const base64 = (base64String + padding)
87
+ .replace(/\-/g, '+')
88
+ .replace(/_/g, '/');
89
+ const rawData = atob(base64);
90
+ const outputArray = new Uint8Array(rawData.length);
91
+ for (let i = 0; i < rawData.length; ++i) {
92
+ outputArray[i] = rawData.charCodeAt(i);
93
+ }
94
+ return outputArray;
95
+ }
96
+
97
+ /**
98
+ * @license
99
+ * Copyright 2019 Google LLC
100
+ *
101
+ * Licensed under the Apache License, Version 2.0 (the "License");
102
+ * you may not use this file except in compliance with the License.
103
+ * You may obtain a copy of the License at
104
+ *
105
+ * http://www.apache.org/licenses/LICENSE-2.0
106
+ *
107
+ * Unless required by applicable law or agreed to in writing, software
108
+ * distributed under the License is distributed on an "AS IS" BASIS,
109
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
110
+ * See the License for the specific language governing permissions and
111
+ * limitations under the License.
112
+ */
113
+ const OLD_DB_NAME = 'fcm_token_details_db';
114
+ /**
115
+ * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade
116
+ * callback is called for all versions of the old DB.
117
+ */
118
+ const OLD_DB_VERSION = 5;
119
+ const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';
120
+ async function migrateOldDatabase(senderId) {
121
+ if ('databases' in indexedDB) {
122
+ // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove
123
+ // typecast when it lands in TS types.
124
+ const databases = await indexedDB.databases();
125
+ const dbNames = databases.map(db => db.name);
126
+ if (!dbNames.includes(OLD_DB_NAME)) {
127
+ // old DB didn't exist, no need to open.
128
+ return null;
129
+ }
130
+ }
131
+ let tokenDetails = null;
132
+ const db = await idb.openDB(OLD_DB_NAME, OLD_DB_VERSION, {
133
+ upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {
134
+ if (oldVersion < 2) {
135
+ // Database too old, skip migration.
136
+ return;
137
+ }
138
+ if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
139
+ // Database did not exist. Nothing to do.
140
+ return;
141
+ }
142
+ const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);
143
+ const value = await objectStore.index('fcmSenderId').get(senderId);
144
+ await objectStore.clear();
145
+ if (!value) {
146
+ // No entry in the database, nothing to migrate.
147
+ return;
148
+ }
149
+ if (oldVersion === 2) {
150
+ const oldDetails = value;
151
+ if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {
152
+ return;
153
+ }
154
+ tokenDetails = {
155
+ token: oldDetails.fcmToken,
156
+ createTime: oldDetails.createTime ?? Date.now(),
157
+ subscriptionOptions: {
158
+ auth: oldDetails.auth,
159
+ p256dh: oldDetails.p256dh,
160
+ endpoint: oldDetails.endpoint,
161
+ swScope: oldDetails.swScope,
162
+ vapidKey: typeof oldDetails.vapidKey === 'string'
163
+ ? oldDetails.vapidKey
164
+ : arrayToBase64(oldDetails.vapidKey)
165
+ }
166
+ };
167
+ }
168
+ else if (oldVersion === 3) {
169
+ const oldDetails = value;
170
+ tokenDetails = {
171
+ token: oldDetails.fcmToken,
172
+ createTime: oldDetails.createTime,
173
+ subscriptionOptions: {
174
+ auth: arrayToBase64(oldDetails.auth),
175
+ p256dh: arrayToBase64(oldDetails.p256dh),
176
+ endpoint: oldDetails.endpoint,
177
+ swScope: oldDetails.swScope,
178
+ vapidKey: arrayToBase64(oldDetails.vapidKey)
179
+ }
180
+ };
181
+ }
182
+ else if (oldVersion === 4) {
183
+ const oldDetails = value;
184
+ tokenDetails = {
185
+ token: oldDetails.fcmToken,
186
+ createTime: oldDetails.createTime,
187
+ subscriptionOptions: {
188
+ auth: arrayToBase64(oldDetails.auth),
189
+ p256dh: arrayToBase64(oldDetails.p256dh),
190
+ endpoint: oldDetails.endpoint,
191
+ swScope: oldDetails.swScope,
192
+ vapidKey: arrayToBase64(oldDetails.vapidKey)
193
+ }
194
+ };
195
+ }
196
+ }
197
+ });
198
+ db.close();
199
+ // Delete all old databases.
200
+ await idb.deleteDB(OLD_DB_NAME);
201
+ await idb.deleteDB('fcm_vapid_details_db');
202
+ await idb.deleteDB('undefined');
203
+ return checkTokenDetails(tokenDetails) ? tokenDetails : null;
204
+ }
205
+ function checkTokenDetails(tokenDetails) {
206
+ if (!tokenDetails || !tokenDetails.subscriptionOptions) {
207
+ return false;
208
+ }
209
+ const { subscriptionOptions } = tokenDetails;
210
+ return (typeof tokenDetails.createTime === 'number' &&
211
+ tokenDetails.createTime > 0 &&
212
+ typeof tokenDetails.token === 'string' &&
213
+ tokenDetails.token.length > 0 &&
214
+ typeof subscriptionOptions.auth === 'string' &&
215
+ subscriptionOptions.auth.length > 0 &&
216
+ typeof subscriptionOptions.p256dh === 'string' &&
217
+ subscriptionOptions.p256dh.length > 0 &&
218
+ typeof subscriptionOptions.endpoint === 'string' &&
219
+ subscriptionOptions.endpoint.length > 0 &&
220
+ typeof subscriptionOptions.swScope === 'string' &&
221
+ subscriptionOptions.swScope.length > 0 &&
222
+ typeof subscriptionOptions.vapidKey === 'string' &&
223
+ subscriptionOptions.vapidKey.length > 0);
224
+ }
225
+
226
+ /**
227
+ * @license
228
+ * Copyright 2019 Google LLC
229
+ *
230
+ * Licensed under the Apache License, Version 2.0 (the "License");
231
+ * you may not use this file except in compliance with the License.
232
+ * You may obtain a copy of the License at
233
+ *
234
+ * http://www.apache.org/licenses/LICENSE-2.0
235
+ *
236
+ * Unless required by applicable law or agreed to in writing, software
237
+ * distributed under the License is distributed on an "AS IS" BASIS,
238
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
239
+ * See the License for the specific language governing permissions and
240
+ * limitations under the License.
241
+ */
242
+ // Exported for tests.
243
+ const DATABASE_NAME = 'firebase-messaging-database';
244
+ const DATABASE_VERSION = 1;
245
+ const OBJECT_STORE_NAME = 'firebase-messaging-store';
246
+ let dbPromise = null;
247
+ function getDbPromise() {
248
+ if (!dbPromise) {
249
+ dbPromise = idb.openDB(DATABASE_NAME, DATABASE_VERSION, {
250
+ upgrade: (upgradeDb, oldVersion) => {
251
+ // We don't use 'break' in this switch statement, the fall-through behavior is what we want,
252
+ // because if there are multiple versions between the old version and the current version, we
253
+ // want ALL the migrations that correspond to those versions to run, not only the last one.
254
+ // eslint-disable-next-line default-case
255
+ switch (oldVersion) {
256
+ case 0:
257
+ upgradeDb.createObjectStore(OBJECT_STORE_NAME);
258
+ }
259
+ }
260
+ });
261
+ }
262
+ return dbPromise;
263
+ }
264
+ /** Gets record(s) from the objectStore that match the given key. */
265
+ async function dbGet(firebaseDependencies) {
266
+ const key = getKey(firebaseDependencies);
267
+ const db = await getDbPromise();
268
+ const tokenDetails = (await db
269
+ .transaction(OBJECT_STORE_NAME)
270
+ .objectStore(OBJECT_STORE_NAME)
271
+ .get(key));
272
+ if (tokenDetails) {
273
+ return tokenDetails;
274
+ }
275
+ else {
276
+ // Check if there is a tokenDetails object in the old DB.
277
+ const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);
278
+ if (oldTokenDetails) {
279
+ await dbSet(firebaseDependencies, oldTokenDetails);
280
+ return oldTokenDetails;
281
+ }
282
+ }
283
+ }
284
+ /** Assigns or overwrites the record for the given key with the given value. */
285
+ async function dbSet(firebaseDependencies, tokenDetails) {
286
+ const key = getKey(firebaseDependencies);
287
+ const db = await getDbPromise();
288
+ const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
289
+ await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);
290
+ await tx.done;
291
+ return tokenDetails;
292
+ }
293
+ /** Removes record(s) from the objectStore that match the given key. */
294
+ async function dbRemove(firebaseDependencies) {
295
+ const key = getKey(firebaseDependencies);
296
+ const db = await getDbPromise();
297
+ const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
298
+ await tx.objectStore(OBJECT_STORE_NAME).delete(key);
299
+ await tx.done;
300
+ }
301
+ function getKey({ appConfig }) {
302
+ return appConfig.appId;
303
+ }
304
+
305
+ /**
306
+ * @license
307
+ * Copyright 2017 Google LLC
308
+ *
309
+ * Licensed under the Apache License, Version 2.0 (the "License");
310
+ * you may not use this file except in compliance with the License.
311
+ * You may obtain a copy of the License at
312
+ *
313
+ * http://www.apache.org/licenses/LICENSE-2.0
314
+ *
315
+ * Unless required by applicable law or agreed to in writing, software
316
+ * distributed under the License is distributed on an "AS IS" BASIS,
317
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
318
+ * See the License for the specific language governing permissions and
319
+ * limitations under the License.
320
+ */
321
+ const ERROR_MAP = {
322
+ ["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
323
+ ["only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',
324
+ ["only-available-in-sw" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',
325
+ ["permission-default" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',
326
+ ["permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',
327
+ ["unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */]: "This browser doesn't support the API's required to use the Firebase SDK.",
328
+ ["indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: "This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)",
329
+ ["failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',
330
+ ["token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',
331
+ ["token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',
332
+ ["token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +
333
+ 'user from FCM: {$errorInfo}',
334
+ ["token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',
335
+ ["token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',
336
+ ["use-sw-after-get-token" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +
337
+ 'called before calling getToken() to ensure your service worker is used.',
338
+ ["invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',
339
+ ["invalid-bg-handler" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',
340
+ ["invalid-vapid-key" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',
341
+ ["use-vapid-key-after-get-token" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +
342
+ 'called before calling getToken() to ensure your VAPID key is used.'
343
+ };
344
+ const ERROR_FACTORY = new util.ErrorFactory('messaging', 'Messaging', ERROR_MAP);
345
+
346
+ /**
347
+ * @license
348
+ * Copyright 2019 Google LLC
349
+ *
350
+ * Licensed under the Apache License, Version 2.0 (the "License");
351
+ * you may not use this file except in compliance with the License.
352
+ * You may obtain a copy of the License at
353
+ *
354
+ * http://www.apache.org/licenses/LICENSE-2.0
355
+ *
356
+ * Unless required by applicable law or agreed to in writing, software
357
+ * distributed under the License is distributed on an "AS IS" BASIS,
358
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
359
+ * See the License for the specific language governing permissions and
360
+ * limitations under the License.
361
+ */
362
+ async function requestGetToken(firebaseDependencies, subscriptionOptions) {
363
+ const headers = await getHeaders(firebaseDependencies);
364
+ const body = getBody(subscriptionOptions);
365
+ const subscribeOptions = {
366
+ method: 'POST',
367
+ headers,
368
+ body: JSON.stringify(body)
369
+ };
370
+ let responseData;
371
+ try {
372
+ const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);
373
+ responseData = await response.json();
374
+ }
375
+ catch (err) {
376
+ throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
377
+ errorInfo: err?.toString()
378
+ });
379
+ }
380
+ if (responseData.error) {
381
+ const message = responseData.error.message;
382
+ throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
383
+ errorInfo: message
384
+ });
385
+ }
386
+ if (!responseData.token) {
387
+ throw ERROR_FACTORY.create("token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);
388
+ }
389
+ return responseData.token;
390
+ }
391
+ async function requestUpdateToken(firebaseDependencies, tokenDetails) {
392
+ const headers = await getHeaders(firebaseDependencies);
393
+ const body = getBody(tokenDetails.subscriptionOptions);
394
+ const updateOptions = {
395
+ method: 'PATCH',
396
+ headers,
397
+ body: JSON.stringify(body)
398
+ };
399
+ let responseData;
400
+ try {
401
+ const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);
402
+ responseData = await response.json();
403
+ }
404
+ catch (err) {
405
+ throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
406
+ errorInfo: err?.toString()
407
+ });
408
+ }
409
+ if (responseData.error) {
410
+ const message = responseData.error.message;
411
+ throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
412
+ errorInfo: message
413
+ });
414
+ }
415
+ if (!responseData.token) {
416
+ throw ERROR_FACTORY.create("token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);
417
+ }
418
+ return responseData.token;
419
+ }
420
+ async function requestDeleteToken(firebaseDependencies, token) {
421
+ const headers = await getHeaders(firebaseDependencies);
422
+ const unsubscribeOptions = {
423
+ method: 'DELETE',
424
+ headers
425
+ };
426
+ try {
427
+ const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);
428
+ const responseData = await response.json();
429
+ if (responseData.error) {
430
+ const message = responseData.error.message;
431
+ throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
432
+ errorInfo: message
433
+ });
434
+ }
435
+ }
436
+ catch (err) {
437
+ throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
438
+ errorInfo: err?.toString()
439
+ });
440
+ }
441
+ }
442
+ function getEndpoint({ projectId }) {
443
+ return `${ENDPOINT}/projects/${projectId}/registrations`;
444
+ }
445
+ async function getHeaders({ appConfig, installations }) {
446
+ const authToken = await installations.getToken();
447
+ return new Headers({
448
+ 'Content-Type': 'application/json',
449
+ Accept: 'application/json',
450
+ 'x-goog-api-key': appConfig.apiKey,
451
+ 'x-goog-firebase-installations-auth': `FIS ${authToken}`
452
+ });
453
+ }
454
+ function getBody({ p256dh, auth, endpoint, vapidKey }) {
455
+ const body = {
456
+ web: {
457
+ endpoint,
458
+ auth,
459
+ p256dh
460
+ }
461
+ };
462
+ if (vapidKey !== DEFAULT_VAPID_KEY) {
463
+ body.web.applicationPubKey = vapidKey;
464
+ }
465
+ return body;
466
+ }
467
+
468
+ /**
469
+ * @license
470
+ * Copyright 2019 Google LLC
471
+ *
472
+ * Licensed under the Apache License, Version 2.0 (the "License");
473
+ * you may not use this file except in compliance with the License.
474
+ * You may obtain a copy of the License at
475
+ *
476
+ * http://www.apache.org/licenses/LICENSE-2.0
477
+ *
478
+ * Unless required by applicable law or agreed to in writing, software
479
+ * distributed under the License is distributed on an "AS IS" BASIS,
480
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
481
+ * See the License for the specific language governing permissions and
482
+ * limitations under the License.
483
+ */
484
+ // UpdateRegistration will be called once every week.
485
+ const TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
486
+ async function getTokenInternal(messaging) {
487
+ const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);
488
+ const subscriptionOptions = {
489
+ vapidKey: messaging.vapidKey,
490
+ swScope: messaging.swRegistration.scope,
491
+ endpoint: pushSubscription.endpoint,
492
+ auth: arrayToBase64(pushSubscription.getKey('auth')),
493
+ p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))
494
+ };
495
+ const tokenDetails = await dbGet(messaging.firebaseDependencies);
496
+ if (!tokenDetails) {
497
+ // No token, get a new one.
498
+ return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
499
+ }
500
+ else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {
501
+ // Invalid token, get a new one.
502
+ try {
503
+ await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);
504
+ }
505
+ catch (e) {
506
+ // Suppress errors because of #2364
507
+ console.warn(e);
508
+ }
509
+ return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
510
+ }
511
+ else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {
512
+ // Weekly token refresh
513
+ return updateToken(messaging, {
514
+ token: tokenDetails.token,
515
+ createTime: Date.now(),
516
+ subscriptionOptions
517
+ });
518
+ }
519
+ else {
520
+ // Valid token, nothing to do.
521
+ return tokenDetails.token;
522
+ }
523
+ }
524
+ /**
525
+ * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters
526
+ * the push subscription if it exists.
527
+ */
528
+ async function deleteTokenInternal(messaging) {
529
+ const tokenDetails = await dbGet(messaging.firebaseDependencies);
530
+ if (tokenDetails) {
531
+ await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);
532
+ await dbRemove(messaging.firebaseDependencies);
533
+ }
534
+ // Unsubscribe from the push subscription.
535
+ const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();
536
+ if (pushSubscription) {
537
+ return pushSubscription.unsubscribe();
538
+ }
539
+ // If there's no SW, consider it a success.
540
+ return true;
541
+ }
542
+ async function updateToken(messaging, tokenDetails) {
543
+ try {
544
+ const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);
545
+ const updatedTokenDetails = {
546
+ ...tokenDetails,
547
+ token: updatedToken,
548
+ createTime: Date.now()
549
+ };
550
+ await dbSet(messaging.firebaseDependencies, updatedTokenDetails);
551
+ return updatedToken;
552
+ }
553
+ catch (e) {
554
+ throw e;
555
+ }
556
+ }
557
+ async function getNewToken(firebaseDependencies, subscriptionOptions) {
558
+ const token = await requestGetToken(firebaseDependencies, subscriptionOptions);
559
+ const tokenDetails = {
560
+ token,
561
+ createTime: Date.now(),
562
+ subscriptionOptions
563
+ };
564
+ await dbSet(firebaseDependencies, tokenDetails);
565
+ return tokenDetails.token;
566
+ }
567
+ /**
568
+ * Gets a PushSubscription for the current user.
569
+ */
570
+ async function getPushSubscription(swRegistration, vapidKey) {
571
+ const subscription = await swRegistration.pushManager.getSubscription();
572
+ if (subscription) {
573
+ return subscription;
574
+ }
575
+ return swRegistration.pushManager.subscribe({
576
+ userVisibleOnly: true,
577
+ // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key
578
+ // submitted to pushManager#subscribe must be of type Uint8Array.
579
+ applicationServerKey: base64ToArray(vapidKey)
580
+ });
581
+ }
582
+ /**
583
+ * Checks if the saved tokenDetails object matches the configuration provided.
584
+ */
585
+ function isTokenValid(dbOptions, currentOptions) {
586
+ const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;
587
+ const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;
588
+ const isAuthEqual = currentOptions.auth === dbOptions.auth;
589
+ const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;
590
+ return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;
591
+ }
592
+
593
+ /**
594
+ * @license
595
+ * Copyright 2020 Google LLC
596
+ *
597
+ * Licensed under the Apache License, Version 2.0 (the "License");
598
+ * you may not use this file except in compliance with the License.
599
+ * You may obtain a copy of the License at
600
+ *
601
+ * http://www.apache.org/licenses/LICENSE-2.0
602
+ *
603
+ * Unless required by applicable law or agreed to in writing, software
604
+ * distributed under the License is distributed on an "AS IS" BASIS,
605
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
606
+ * See the License for the specific language governing permissions and
607
+ * limitations under the License.
608
+ */
609
+ function externalizePayload(internalPayload) {
610
+ const payload = {
611
+ from: internalPayload.from,
612
+ // eslint-disable-next-line camelcase
613
+ collapseKey: internalPayload.collapse_key,
614
+ // eslint-disable-next-line camelcase
615
+ messageId: internalPayload.fcmMessageId
616
+ };
617
+ propagateNotificationPayload(payload, internalPayload);
618
+ propagateDataPayload(payload, internalPayload);
619
+ propagateFcmOptions(payload, internalPayload);
620
+ return payload;
621
+ }
622
+ function propagateNotificationPayload(payload, messagePayloadInternal) {
623
+ if (!messagePayloadInternal.notification) {
624
+ return;
625
+ }
626
+ payload.notification = {};
627
+ const title = messagePayloadInternal.notification.title;
628
+ if (!!title) {
629
+ payload.notification.title = title;
630
+ }
631
+ const body = messagePayloadInternal.notification.body;
632
+ if (!!body) {
633
+ payload.notification.body = body;
634
+ }
635
+ const image = messagePayloadInternal.notification.image;
636
+ if (!!image) {
637
+ payload.notification.image = image;
638
+ }
639
+ const icon = messagePayloadInternal.notification.icon;
640
+ if (!!icon) {
641
+ payload.notification.icon = icon;
642
+ }
643
+ }
644
+ function propagateDataPayload(payload, messagePayloadInternal) {
645
+ if (!messagePayloadInternal.data) {
646
+ return;
647
+ }
648
+ payload.data = messagePayloadInternal.data;
649
+ }
650
+ function propagateFcmOptions(payload, messagePayloadInternal) {
651
+ // fcmOptions.link value is written into notification.click_action. see more in b/232072111
652
+ if (!messagePayloadInternal.fcmOptions &&
653
+ !messagePayloadInternal.notification?.click_action) {
654
+ return;
655
+ }
656
+ payload.fcmOptions = {};
657
+ const link = messagePayloadInternal.fcmOptions?.link ??
658
+ messagePayloadInternal.notification?.click_action;
659
+ if (!!link) {
660
+ payload.fcmOptions.link = link;
661
+ }
662
+ // eslint-disable-next-line camelcase
663
+ const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;
664
+ if (!!analyticsLabel) {
665
+ payload.fcmOptions.analyticsLabel = analyticsLabel;
666
+ }
667
+ }
668
+
669
+ /**
670
+ * @license
671
+ * Copyright 2019 Google LLC
672
+ *
673
+ * Licensed under the Apache License, Version 2.0 (the "License");
674
+ * you may not use this file except in compliance with the License.
675
+ * You may obtain a copy of the License at
676
+ *
677
+ * http://www.apache.org/licenses/LICENSE-2.0
678
+ *
679
+ * Unless required by applicable law or agreed to in writing, software
680
+ * distributed under the License is distributed on an "AS IS" BASIS,
681
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
682
+ * See the License for the specific language governing permissions and
683
+ * limitations under the License.
684
+ */
685
+ function isConsoleMessage(data) {
686
+ // This message has a campaign ID, meaning it was sent using the Firebase Console.
687
+ return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;
688
+ }
689
+
690
+ /**
691
+ * @license
692
+ * Copyright 2019 Google LLC
693
+ *
694
+ * Licensed under the Apache License, Version 2.0 (the "License");
695
+ * you may not use this file except in compliance with the License.
696
+ * You may obtain a copy of the License at
697
+ *
698
+ * http://www.apache.org/licenses/LICENSE-2.0
699
+ *
700
+ * Unless required by applicable law or agreed to in writing, software
701
+ * distributed under the License is distributed on an "AS IS" BASIS,
702
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
703
+ * See the License for the specific language governing permissions and
704
+ * limitations under the License.
705
+ */
706
+ _mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');
707
+ function _mergeStrings(s1, s2) {
708
+ const resultArray = [];
709
+ for (let i = 0; i < s1.length; i++) {
710
+ resultArray.push(s1.charAt(i));
711
+ if (i < s2.length) {
712
+ resultArray.push(s2.charAt(i));
713
+ }
714
+ }
715
+ return resultArray.join('');
716
+ }
717
+
718
+ /**
719
+ * @license
720
+ * Copyright 2019 Google LLC
721
+ *
722
+ * Licensed under the Apache License, Version 2.0 (the "License");
723
+ * you may not use this file except in compliance with the License.
724
+ * You may obtain a copy of the License at
725
+ *
726
+ * http://www.apache.org/licenses/LICENSE-2.0
727
+ *
728
+ * Unless required by applicable law or agreed to in writing, software
729
+ * distributed under the License is distributed on an "AS IS" BASIS,
730
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
731
+ * See the License for the specific language governing permissions and
732
+ * limitations under the License.
733
+ */
734
+ function extractAppConfig(app) {
735
+ if (!app || !app.options) {
736
+ throw getMissingValueError('App Configuration Object');
737
+ }
738
+ if (!app.name) {
739
+ throw getMissingValueError('App Name');
740
+ }
741
+ // Required app config keys
742
+ const configKeys = [
743
+ 'projectId',
744
+ 'apiKey',
745
+ 'appId',
746
+ 'messagingSenderId'
747
+ ];
748
+ const { options } = app;
749
+ for (const keyName of configKeys) {
750
+ if (!options[keyName]) {
751
+ throw getMissingValueError(keyName);
752
+ }
753
+ }
754
+ return {
755
+ appName: app.name,
756
+ projectId: options.projectId,
757
+ apiKey: options.apiKey,
758
+ appId: options.appId,
759
+ senderId: options.messagingSenderId
760
+ };
761
+ }
762
+ function getMissingValueError(valueName) {
763
+ return ERROR_FACTORY.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
764
+ valueName
765
+ });
766
+ }
767
+
768
+ /**
769
+ * @license
770
+ * Copyright 2020 Google LLC
771
+ *
772
+ * Licensed under the Apache License, Version 2.0 (the "License");
773
+ * you may not use this file except in compliance with the License.
774
+ * You may obtain a copy of the License at
775
+ *
776
+ * http://www.apache.org/licenses/LICENSE-2.0
777
+ *
778
+ * Unless required by applicable law or agreed to in writing, software
779
+ * distributed under the License is distributed on an "AS IS" BASIS,
780
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
781
+ * See the License for the specific language governing permissions and
782
+ * limitations under the License.
783
+ */
784
+ class MessagingService {
785
+ constructor(app, installations, analyticsProvider) {
786
+ // logging is only done with end user consent. Default to false.
787
+ this.deliveryMetricsExportedToBigQueryEnabled = false;
788
+ this.onBackgroundMessageHandler = null;
789
+ this.onMessageHandler = null;
790
+ this.logEvents = [];
791
+ this.isLogServiceStarted = false;
792
+ const appConfig = extractAppConfig(app);
793
+ this.firebaseDependencies = {
794
+ app,
795
+ appConfig,
796
+ installations,
797
+ analyticsProvider
798
+ };
799
+ }
800
+ _delete() {
801
+ return Promise.resolve();
802
+ }
803
+ }
804
+
805
+ /**
806
+ * @license
807
+ * Copyright 2020 Google LLC
808
+ *
809
+ * Licensed under the Apache License, Version 2.0 (the "License");
810
+ * you may not use this file except in compliance with the License.
811
+ * You may obtain a copy of the License at
812
+ *
813
+ * http://www.apache.org/licenses/LICENSE-2.0
814
+ *
815
+ * Unless required by applicable law or agreed to in writing, software
816
+ * distributed under the License is distributed on an "AS IS" BASIS,
817
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
818
+ * See the License for the specific language governing permissions and
819
+ * limitations under the License.
820
+ */
821
+ async function registerDefaultSw(messaging) {
822
+ try {
823
+ messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {
824
+ scope: DEFAULT_SW_SCOPE
825
+ });
826
+ // The timing when browser updates sw when sw has an update is unreliable from experiment. It
827
+ // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw
828
+ // is stuck with the old version. For example,
829
+ // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates
830
+ // sw if there was an update.
831
+ messaging.swRegistration.update().catch(() => {
832
+ /* it is non blocking and we don't care if it failed */
833
+ });
834
+ await waitForRegistrationActive(messaging.swRegistration);
835
+ }
836
+ catch (e) {
837
+ throw ERROR_FACTORY.create("failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {
838
+ browserErrorMessage: e?.message
839
+ });
840
+ }
841
+ }
842
+ /**
843
+ * Waits for registration to become active. MDN documentation claims that
844
+ * a service worker registration should be ready to use after awaiting
845
+ * navigator.serviceWorker.register() but that doesn't seem to be the case in
846
+ * practice, causing the SDK to throw errors when calling
847
+ * swRegistration.pushManager.subscribe() too soon after register(). The only
848
+ * solution seems to be waiting for the service worker registration `state`
849
+ * to become "active".
850
+ */
851
+ async function waitForRegistrationActive(registration) {
852
+ return new Promise((resolve, reject) => {
853
+ const rejectTimeout = setTimeout(() => reject(new Error(`Service worker not registered after ${DEFAULT_REGISTRATION_TIMEOUT} ms`)), DEFAULT_REGISTRATION_TIMEOUT);
854
+ const incomingSw = registration.installing || registration.waiting;
855
+ if (registration.active) {
856
+ clearTimeout(rejectTimeout);
857
+ resolve();
858
+ }
859
+ else if (incomingSw) {
860
+ incomingSw.onstatechange = ev => {
861
+ if (ev.target?.state === 'activated') {
862
+ incomingSw.onstatechange = null;
863
+ clearTimeout(rejectTimeout);
864
+ resolve();
865
+ }
866
+ };
867
+ }
868
+ else {
869
+ clearTimeout(rejectTimeout);
870
+ reject(new Error('No incoming service worker found.'));
871
+ }
872
+ });
873
+ }
874
+
875
+ /**
876
+ * @license
877
+ * Copyright 2020 Google LLC
878
+ *
879
+ * Licensed under the Apache License, Version 2.0 (the "License");
880
+ * you may not use this file except in compliance with the License.
881
+ * You may obtain a copy of the License at
882
+ *
883
+ * http://www.apache.org/licenses/LICENSE-2.0
884
+ *
885
+ * Unless required by applicable law or agreed to in writing, software
886
+ * distributed under the License is distributed on an "AS IS" BASIS,
887
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
888
+ * See the License for the specific language governing permissions and
889
+ * limitations under the License.
890
+ */
891
+ async function updateSwReg(messaging, swRegistration) {
892
+ if (!swRegistration && !messaging.swRegistration) {
893
+ await registerDefaultSw(messaging);
894
+ }
895
+ if (!swRegistration && !!messaging.swRegistration) {
896
+ return;
897
+ }
898
+ if (!(swRegistration instanceof ServiceWorkerRegistration)) {
899
+ throw ERROR_FACTORY.create("invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */);
900
+ }
901
+ messaging.swRegistration = swRegistration;
902
+ }
903
+
904
+ /**
905
+ * @license
906
+ * Copyright 2020 Google LLC
907
+ *
908
+ * Licensed under the Apache License, Version 2.0 (the "License");
909
+ * you may not use this file except in compliance with the License.
910
+ * You may obtain a copy of the License at
911
+ *
912
+ * http://www.apache.org/licenses/LICENSE-2.0
913
+ *
914
+ * Unless required by applicable law or agreed to in writing, software
915
+ * distributed under the License is distributed on an "AS IS" BASIS,
916
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
917
+ * See the License for the specific language governing permissions and
918
+ * limitations under the License.
919
+ */
920
+ async function updateVapidKey(messaging, vapidKey) {
921
+ if (!!vapidKey) {
922
+ messaging.vapidKey = vapidKey;
923
+ }
924
+ else if (!messaging.vapidKey) {
925
+ messaging.vapidKey = DEFAULT_VAPID_KEY;
926
+ }
927
+ }
928
+
929
+ /**
930
+ * @license
931
+ * Copyright 2020 Google LLC
932
+ *
933
+ * Licensed under the Apache License, Version 2.0 (the "License");
934
+ * you may not use this file except in compliance with the License.
935
+ * You may obtain a copy of the License at
936
+ *
937
+ * http://www.apache.org/licenses/LICENSE-2.0
938
+ *
939
+ * Unless required by applicable law or agreed to in writing, software
940
+ * distributed under the License is distributed on an "AS IS" BASIS,
941
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
942
+ * See the License for the specific language governing permissions and
943
+ * limitations under the License.
944
+ */
945
+ async function getToken$1(messaging, options) {
946
+ if (!navigator) {
947
+ throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
948
+ }
949
+ if (Notification.permission === 'default') {
950
+ await Notification.requestPermission();
951
+ }
952
+ if (Notification.permission !== 'granted') {
953
+ throw ERROR_FACTORY.create("permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */);
954
+ }
955
+ await updateVapidKey(messaging, options?.vapidKey);
956
+ await updateSwReg(messaging, options?.serviceWorkerRegistration);
957
+ return getTokenInternal(messaging);
958
+ }
959
+
960
+ /**
961
+ * @license
962
+ * Copyright 2019 Google LLC
963
+ *
964
+ * Licensed under the Apache License, Version 2.0 (the "License");
965
+ * you may not use this file except in compliance with the License.
966
+ * You may obtain a copy of the License at
967
+ *
968
+ * http://www.apache.org/licenses/LICENSE-2.0
969
+ *
970
+ * Unless required by applicable law or agreed to in writing, software
971
+ * distributed under the License is distributed on an "AS IS" BASIS,
972
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
973
+ * See the License for the specific language governing permissions and
974
+ * limitations under the License.
975
+ */
976
+ async function logToScion(messaging, messageType, data) {
977
+ const eventType = getEventType(messageType);
978
+ const analytics = await messaging.firebaseDependencies.analyticsProvider.get();
979
+ analytics.logEvent(eventType, {
980
+ /* eslint-disable camelcase */
981
+ message_id: data[CONSOLE_CAMPAIGN_ID],
982
+ message_name: data[CONSOLE_CAMPAIGN_NAME],
983
+ message_time: data[CONSOLE_CAMPAIGN_TIME],
984
+ message_device_time: Math.floor(Date.now() / 1000)
985
+ /* eslint-enable camelcase */
986
+ });
987
+ }
988
+ function getEventType(messageType) {
989
+ switch (messageType) {
990
+ case MessageType.NOTIFICATION_CLICKED:
991
+ return 'notification_open';
992
+ case MessageType.PUSH_RECEIVED:
993
+ return 'notification_foreground';
994
+ default:
995
+ throw new Error();
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * @license
1001
+ * Copyright 2017 Google LLC
1002
+ *
1003
+ * Licensed under the Apache License, Version 2.0 (the "License");
1004
+ * you may not use this file except in compliance with the License.
1005
+ * You may obtain a copy of the License at
1006
+ *
1007
+ * http://www.apache.org/licenses/LICENSE-2.0
1008
+ *
1009
+ * Unless required by applicable law or agreed to in writing, software
1010
+ * distributed under the License is distributed on an "AS IS" BASIS,
1011
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1012
+ * See the License for the specific language governing permissions and
1013
+ * limitations under the License.
1014
+ */
1015
+ async function messageEventListener(messaging, event) {
1016
+ const internalPayload = event.data;
1017
+ if (!internalPayload.isFirebaseMessaging) {
1018
+ return;
1019
+ }
1020
+ if (messaging.onMessageHandler &&
1021
+ internalPayload.messageType === MessageType.PUSH_RECEIVED) {
1022
+ if (typeof messaging.onMessageHandler === 'function') {
1023
+ messaging.onMessageHandler(externalizePayload(internalPayload));
1024
+ }
1025
+ else {
1026
+ messaging.onMessageHandler.next(externalizePayload(internalPayload));
1027
+ }
1028
+ }
1029
+ // Log to Scion if applicable
1030
+ const dataPayload = internalPayload.data;
1031
+ if (isConsoleMessage(dataPayload) &&
1032
+ dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {
1033
+ await logToScion(messaging, internalPayload.messageType, dataPayload);
1034
+ }
1035
+ }
1036
+
1037
+ const name = "@firebase/messaging";
1038
+ const version = "0.12.24";
1039
+
1040
+ /**
1041
+ * @license
1042
+ * Copyright 2020 Google LLC
1043
+ *
1044
+ * Licensed under the Apache License, Version 2.0 (the "License");
1045
+ * you may not use this file except in compliance with the License.
1046
+ * You may obtain a copy of the License at
1047
+ *
1048
+ * http://www.apache.org/licenses/LICENSE-2.0
1049
+ *
1050
+ * Unless required by applicable law or agreed to in writing, software
1051
+ * distributed under the License is distributed on an "AS IS" BASIS,
1052
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1053
+ * See the License for the specific language governing permissions and
1054
+ * limitations under the License.
1055
+ */
1056
+ const WindowMessagingFactory = (container) => {
1057
+ const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));
1058
+ navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));
1059
+ return messaging;
1060
+ };
1061
+ const WindowMessagingInternalFactory = (container) => {
1062
+ const messaging = container
1063
+ .getProvider('messaging')
1064
+ .getImmediate();
1065
+ const messagingInternal = {
1066
+ getToken: (options) => getToken$1(messaging, options)
1067
+ };
1068
+ return messagingInternal;
1069
+ };
1070
+ function registerMessagingInWindow() {
1071
+ app._registerComponent(new component.Component('messaging', WindowMessagingFactory, "PUBLIC" /* ComponentType.PUBLIC */));
1072
+ app._registerComponent(new component.Component('messaging-internal', WindowMessagingInternalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
1073
+ app.registerVersion(name, version);
1074
+ // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
1075
+ app.registerVersion(name, version, 'cjs2020');
1076
+ }
1077
+
1078
+ /**
1079
+ * @license
1080
+ * Copyright 2020 Google LLC
1081
+ *
1082
+ * Licensed under the Apache License, Version 2.0 (the "License");
1083
+ * you may not use this file except in compliance with the License.
1084
+ * You may obtain a copy of the License at
1085
+ *
1086
+ * http://www.apache.org/licenses/LICENSE-2.0
1087
+ *
1088
+ * Unless required by applicable law or agreed to in writing, software
1089
+ * distributed under the License is distributed on an "AS IS" BASIS,
1090
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1091
+ * See the License for the specific language governing permissions and
1092
+ * limitations under the License.
1093
+ */
1094
+ /**
1095
+ * Checks if all required APIs exist in the browser.
1096
+ * @returns a Promise that resolves to a boolean.
1097
+ *
1098
+ * @public
1099
+ */
1100
+ async function isWindowSupported() {
1101
+ try {
1102
+ // This throws if open() is unsupported, so adding it to the conditional
1103
+ // statement below can cause an uncaught error.
1104
+ await util.validateIndexedDBOpenable();
1105
+ }
1106
+ catch (e) {
1107
+ return false;
1108
+ }
1109
+ // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing
1110
+ // might be prohibited to run. In these contexts, an error would be thrown during the messaging
1111
+ // instantiating phase, informing the developers to import/call isSupported for special handling.
1112
+ return (typeof window !== 'undefined' &&
1113
+ util.isIndexedDBAvailable() &&
1114
+ util.areCookiesEnabled() &&
1115
+ 'serviceWorker' in navigator &&
1116
+ 'PushManager' in window &&
1117
+ 'Notification' in window &&
1118
+ 'fetch' in window &&
1119
+ ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
1120
+ PushSubscription.prototype.hasOwnProperty('getKey'));
1121
+ }
1122
+
1123
+ /**
1124
+ * @license
1125
+ * Copyright 2020 Google LLC
1126
+ *
1127
+ * Licensed under the Apache License, Version 2.0 (the "License");
1128
+ * you may not use this file except in compliance with the License.
1129
+ * You may obtain a copy of the License at
1130
+ *
1131
+ * http://www.apache.org/licenses/LICENSE-2.0
1132
+ *
1133
+ * Unless required by applicable law or agreed to in writing, software
1134
+ * distributed under the License is distributed on an "AS IS" BASIS,
1135
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1136
+ * See the License for the specific language governing permissions and
1137
+ * limitations under the License.
1138
+ */
1139
+ async function deleteToken$1(messaging) {
1140
+ if (!navigator) {
1141
+ throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
1142
+ }
1143
+ if (!messaging.swRegistration) {
1144
+ await registerDefaultSw(messaging);
1145
+ }
1146
+ return deleteTokenInternal(messaging);
1147
+ }
1148
+
1149
+ /**
1150
+ * @license
1151
+ * Copyright 2020 Google LLC
1152
+ *
1153
+ * Licensed under the Apache License, Version 2.0 (the "License");
1154
+ * you may not use this file except in compliance with the License.
1155
+ * You may obtain a copy of the License at
1156
+ *
1157
+ * http://www.apache.org/licenses/LICENSE-2.0
1158
+ *
1159
+ * Unless required by applicable law or agreed to in writing, software
1160
+ * distributed under the License is distributed on an "AS IS" BASIS,
1161
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1162
+ * See the License for the specific language governing permissions and
1163
+ * limitations under the License.
1164
+ */
1165
+ function onMessage$1(messaging, nextOrObserver) {
1166
+ if (!navigator) {
1167
+ throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
1168
+ }
1169
+ messaging.onMessageHandler = nextOrObserver;
1170
+ return () => {
1171
+ messaging.onMessageHandler = null;
1172
+ };
1173
+ }
1174
+
1175
+ /**
1176
+ * @license
1177
+ * Copyright 2017 Google LLC
1178
+ *
1179
+ * Licensed under the Apache License, Version 2.0 (the "License");
1180
+ * you may not use this file except in compliance with the License.
1181
+ * You may obtain a copy of the License at
1182
+ *
1183
+ * http://www.apache.org/licenses/LICENSE-2.0
1184
+ *
1185
+ * Unless required by applicable law or agreed to in writing, software
1186
+ * distributed under the License is distributed on an "AS IS" BASIS,
1187
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1188
+ * See the License for the specific language governing permissions and
1189
+ * limitations under the License.
1190
+ */
1191
+ /**
1192
+ * Retrieves a Firebase Cloud Messaging instance.
1193
+ *
1194
+ * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
1195
+ *
1196
+ * @public
1197
+ */
1198
+ function getMessagingInWindow(app$1 = app.getApp()) {
1199
+ // Conscious decision to make this async check non-blocking during the messaging instance
1200
+ // initialization phase for performance consideration. An error would be thrown latter for
1201
+ // developer's information. Developers can then choose to import and call `isSupported` for
1202
+ // special handling.
1203
+ isWindowSupported().then(isSupported => {
1204
+ // If `isWindowSupported()` resolved, but returned false.
1205
+ if (!isSupported) {
1206
+ throw ERROR_FACTORY.create("unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */);
1207
+ }
1208
+ }, _ => {
1209
+ // If `isWindowSupported()` rejected.
1210
+ throw ERROR_FACTORY.create("indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);
1211
+ });
1212
+ return app._getProvider(util.getModularInstance(app$1), 'messaging').getImmediate();
1213
+ }
1214
+ /**
1215
+ * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud
1216
+ * Messaging registration token that can be used to send push messages to that {@link Messaging}
1217
+ * instance.
1218
+ *
1219
+ * If notification permission isn't already granted, this method asks the user for permission. The
1220
+ * returned promise rejects if the user does not allow the app to show notifications.
1221
+ *
1222
+ * @param messaging - The {@link Messaging} instance.
1223
+ * @param options - Provides an optional vapid key and an optional service worker registration.
1224
+ *
1225
+ * @returns The promise resolves with an FCM registration token.
1226
+ *
1227
+ * @public
1228
+ */
1229
+ async function getToken(messaging, options) {
1230
+ messaging = util.getModularInstance(messaging);
1231
+ return getToken$1(messaging, options);
1232
+ }
1233
+ /**
1234
+ * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes
1235
+ * the {@link Messaging} instance from the push subscription.
1236
+ *
1237
+ * @param messaging - The {@link Messaging} instance.
1238
+ *
1239
+ * @returns The promise resolves when the token has been successfully deleted.
1240
+ *
1241
+ * @public
1242
+ */
1243
+ function deleteToken(messaging) {
1244
+ messaging = util.getModularInstance(messaging);
1245
+ return deleteToken$1(messaging);
1246
+ }
1247
+ /**
1248
+ * When a push message is received and the user is currently on a page for your origin, the
1249
+ * message is passed to the page and an `onMessage()` event is dispatched with the payload of
1250
+ * the push message.
1251
+ *
1252
+ *
1253
+ * @param messaging - The {@link Messaging} instance.
1254
+ * @param nextOrObserver - This function, or observer object with `next` defined,
1255
+ * is called when a message is received and the user is currently viewing your page.
1256
+ * @returns To stop listening for messages execute this returned function.
1257
+ *
1258
+ * @public
1259
+ */
1260
+ function onMessage(messaging, nextOrObserver) {
1261
+ messaging = util.getModularInstance(messaging);
1262
+ return onMessage$1(messaging, nextOrObserver);
1263
+ }
1264
+
1265
+ /**
1266
+ * The Firebase Cloud Messaging Web SDK.
1267
+ * This SDK does not work in a Node.js environment.
1268
+ *
1269
+ * @packageDocumentation
1270
+ */
1271
+ registerMessagingInWindow();
1272
+
1273
+ exports.deleteToken = deleteToken;
1274
+ exports.getMessaging = getMessagingInWindow;
1275
+ exports.getToken = getToken;
1276
+ exports.isSupported = isWindowSupported;
1277
+ exports.onMessage = onMessage;
1278
+ //# sourceMappingURL=index.cjs.js.map