@firebase/messaging 0.9.5 → 0.9.6

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.
@@ -0,0 +1,1578 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ require('@firebase/installations');
6
+ var component = require('@firebase/component');
7
+ var tslib = require('tslib');
8
+ var idb = require('idb');
9
+ var util = require('@firebase/util');
10
+ var app = require('@firebase/app');
11
+
12
+ /**
13
+ * @license
14
+ * Copyright 2019 Google LLC
15
+ *
16
+ * Licensed under the Apache License, Version 2.0 (the "License");
17
+ * you may not use this file except in compliance with the License.
18
+ * You may obtain a copy of the License at
19
+ *
20
+ * http://www.apache.org/licenses/LICENSE-2.0
21
+ *
22
+ * Unless required by applicable law or agreed to in writing, software
23
+ * distributed under the License is distributed on an "AS IS" BASIS,
24
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ * See the License for the specific language governing permissions and
26
+ * limitations under the License.
27
+ */
28
+ var DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';
29
+ var ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';
30
+ /** Key of FCM Payload in Notification's data field. */
31
+ var FCM_MSG = 'FCM_MSG';
32
+ var CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';
33
+ // Defined as in proto/messaging_event.proto. Neglecting fields that are supported.
34
+ var SDK_PLATFORM_WEB = 3;
35
+ var EVENT_MESSAGE_DELIVERED = 1;
36
+ var MessageType$1;
37
+ (function (MessageType) {
38
+ MessageType[MessageType["DATA_MESSAGE"] = 1] = "DATA_MESSAGE";
39
+ MessageType[MessageType["DISPLAY_NOTIFICATION"] = 3] = "DISPLAY_NOTIFICATION";
40
+ })(MessageType$1 || (MessageType$1 = {}));
41
+
42
+ /**
43
+ * @license
44
+ * Copyright 2018 Google LLC
45
+ *
46
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
47
+ * in compliance with the License. You may obtain a copy of the License at
48
+ *
49
+ * http://www.apache.org/licenses/LICENSE-2.0
50
+ *
51
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
52
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
53
+ * or implied. See the License for the specific language governing permissions and limitations under
54
+ * the License.
55
+ */
56
+ var MessageType;
57
+ (function (MessageType) {
58
+ MessageType["PUSH_RECEIVED"] = "push-received";
59
+ MessageType["NOTIFICATION_CLICKED"] = "notification-clicked";
60
+ })(MessageType || (MessageType = {}));
61
+
62
+ /**
63
+ * @license
64
+ * Copyright 2017 Google LLC
65
+ *
66
+ * Licensed under the Apache License, Version 2.0 (the "License");
67
+ * you may not use this file except in compliance with the License.
68
+ * You may obtain a copy of the License at
69
+ *
70
+ * http://www.apache.org/licenses/LICENSE-2.0
71
+ *
72
+ * Unless required by applicable law or agreed to in writing, software
73
+ * distributed under the License is distributed on an "AS IS" BASIS,
74
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
75
+ * See the License for the specific language governing permissions and
76
+ * limitations under the License.
77
+ */
78
+ function arrayToBase64(array) {
79
+ var uint8Array = new Uint8Array(array);
80
+ var base64String = btoa(String.fromCharCode.apply(String, tslib.__spreadArray([], tslib.__read(uint8Array))));
81
+ return base64String.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
82
+ }
83
+ function base64ToArray(base64String) {
84
+ var padding = '='.repeat((4 - (base64String.length % 4)) % 4);
85
+ var base64 = (base64String + padding)
86
+ .replace(/\-/g, '+')
87
+ .replace(/_/g, '/');
88
+ var rawData = atob(base64);
89
+ var outputArray = new Uint8Array(rawData.length);
90
+ for (var i = 0; i < rawData.length; ++i) {
91
+ outputArray[i] = rawData.charCodeAt(i);
92
+ }
93
+ return outputArray;
94
+ }
95
+
96
+ /**
97
+ * @license
98
+ * Copyright 2019 Google LLC
99
+ *
100
+ * Licensed under the Apache License, Version 2.0 (the "License");
101
+ * you may not use this file except in compliance with the License.
102
+ * You may obtain a copy of the License at
103
+ *
104
+ * http://www.apache.org/licenses/LICENSE-2.0
105
+ *
106
+ * Unless required by applicable law or agreed to in writing, software
107
+ * distributed under the License is distributed on an "AS IS" BASIS,
108
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
109
+ * See the License for the specific language governing permissions and
110
+ * limitations under the License.
111
+ */
112
+ var OLD_DB_NAME = 'fcm_token_details_db';
113
+ /**
114
+ * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade
115
+ * callback is called for all versions of the old DB.
116
+ */
117
+ var OLD_DB_VERSION = 5;
118
+ var OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';
119
+ function migrateOldDatabase(senderId) {
120
+ return tslib.__awaiter(this, void 0, void 0, function () {
121
+ var databases, dbNames, tokenDetails, db;
122
+ var _this = this;
123
+ return tslib.__generator(this, function (_a) {
124
+ switch (_a.label) {
125
+ case 0:
126
+ if (!('databases' in indexedDB)) return [3 /*break*/, 2];
127
+ return [4 /*yield*/, indexedDB.databases()];
128
+ case 1:
129
+ databases = _a.sent();
130
+ dbNames = databases.map(function (db) { return db.name; });
131
+ if (!dbNames.includes(OLD_DB_NAME)) {
132
+ // old DB didn't exist, no need to open.
133
+ return [2 /*return*/, null];
134
+ }
135
+ _a.label = 2;
136
+ case 2:
137
+ tokenDetails = null;
138
+ return [4 /*yield*/, idb.openDb(OLD_DB_NAME, OLD_DB_VERSION, function (db) { return tslib.__awaiter(_this, void 0, void 0, function () {
139
+ var objectStore, value, oldDetails, oldDetails, oldDetails;
140
+ var _a;
141
+ return tslib.__generator(this, function (_b) {
142
+ switch (_b.label) {
143
+ case 0:
144
+ if (db.oldVersion < 2) {
145
+ // Database too old, skip migration.
146
+ return [2 /*return*/];
147
+ }
148
+ if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
149
+ // Database did not exist. Nothing to do.
150
+ return [2 /*return*/];
151
+ }
152
+ objectStore = db.transaction.objectStore(OLD_OBJECT_STORE_NAME);
153
+ return [4 /*yield*/, objectStore.index('fcmSenderId').get(senderId)];
154
+ case 1:
155
+ value = _b.sent();
156
+ return [4 /*yield*/, objectStore.clear()];
157
+ case 2:
158
+ _b.sent();
159
+ if (!value) {
160
+ // No entry in the database, nothing to migrate.
161
+ return [2 /*return*/];
162
+ }
163
+ if (db.oldVersion === 2) {
164
+ oldDetails = value;
165
+ if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {
166
+ return [2 /*return*/];
167
+ }
168
+ tokenDetails = {
169
+ token: oldDetails.fcmToken,
170
+ createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),
171
+ subscriptionOptions: {
172
+ auth: oldDetails.auth,
173
+ p256dh: oldDetails.p256dh,
174
+ endpoint: oldDetails.endpoint,
175
+ swScope: oldDetails.swScope,
176
+ vapidKey: typeof oldDetails.vapidKey === 'string'
177
+ ? oldDetails.vapidKey
178
+ : arrayToBase64(oldDetails.vapidKey)
179
+ }
180
+ };
181
+ }
182
+ else if (db.oldVersion === 3) {
183
+ 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
+ else if (db.oldVersion === 4) {
197
+ oldDetails = value;
198
+ tokenDetails = {
199
+ token: oldDetails.fcmToken,
200
+ createTime: oldDetails.createTime,
201
+ subscriptionOptions: {
202
+ auth: arrayToBase64(oldDetails.auth),
203
+ p256dh: arrayToBase64(oldDetails.p256dh),
204
+ endpoint: oldDetails.endpoint,
205
+ swScope: oldDetails.swScope,
206
+ vapidKey: arrayToBase64(oldDetails.vapidKey)
207
+ }
208
+ };
209
+ }
210
+ return [2 /*return*/];
211
+ }
212
+ });
213
+ }); })];
214
+ case 3:
215
+ db = _a.sent();
216
+ db.close();
217
+ // Delete all old databases.
218
+ return [4 /*yield*/, idb.deleteDb(OLD_DB_NAME)];
219
+ case 4:
220
+ // Delete all old databases.
221
+ _a.sent();
222
+ return [4 /*yield*/, idb.deleteDb('fcm_vapid_details_db')];
223
+ case 5:
224
+ _a.sent();
225
+ return [4 /*yield*/, idb.deleteDb('undefined')];
226
+ case 6:
227
+ _a.sent();
228
+ return [2 /*return*/, checkTokenDetails(tokenDetails) ? tokenDetails : null];
229
+ }
230
+ });
231
+ });
232
+ }
233
+ function checkTokenDetails(tokenDetails) {
234
+ if (!tokenDetails || !tokenDetails.subscriptionOptions) {
235
+ return false;
236
+ }
237
+ var subscriptionOptions = tokenDetails.subscriptionOptions;
238
+ return (typeof tokenDetails.createTime === 'number' &&
239
+ tokenDetails.createTime > 0 &&
240
+ typeof tokenDetails.token === 'string' &&
241
+ tokenDetails.token.length > 0 &&
242
+ typeof subscriptionOptions.auth === 'string' &&
243
+ subscriptionOptions.auth.length > 0 &&
244
+ typeof subscriptionOptions.p256dh === 'string' &&
245
+ subscriptionOptions.p256dh.length > 0 &&
246
+ typeof subscriptionOptions.endpoint === 'string' &&
247
+ subscriptionOptions.endpoint.length > 0 &&
248
+ typeof subscriptionOptions.swScope === 'string' &&
249
+ subscriptionOptions.swScope.length > 0 &&
250
+ typeof subscriptionOptions.vapidKey === 'string' &&
251
+ subscriptionOptions.vapidKey.length > 0);
252
+ }
253
+
254
+ /**
255
+ * @license
256
+ * Copyright 2019 Google LLC
257
+ *
258
+ * Licensed under the Apache License, Version 2.0 (the "License");
259
+ * you may not use this file except in compliance with the License.
260
+ * You may obtain a copy of the License at
261
+ *
262
+ * http://www.apache.org/licenses/LICENSE-2.0
263
+ *
264
+ * Unless required by applicable law or agreed to in writing, software
265
+ * distributed under the License is distributed on an "AS IS" BASIS,
266
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
267
+ * See the License for the specific language governing permissions and
268
+ * limitations under the License.
269
+ */
270
+ // Exported for tests.
271
+ var DATABASE_NAME = 'firebase-messaging-database';
272
+ var DATABASE_VERSION = 1;
273
+ var OBJECT_STORE_NAME = 'firebase-messaging-store';
274
+ var dbPromise = null;
275
+ function getDbPromise() {
276
+ if (!dbPromise) {
277
+ dbPromise = idb.openDb(DATABASE_NAME, DATABASE_VERSION, function (upgradeDb) {
278
+ // We don't use 'break' in this switch statement, the fall-through behavior is what we want,
279
+ // because if there are multiple versions between the old version and the current version, we
280
+ // want ALL the migrations that correspond to those versions to run, not only the last one.
281
+ // eslint-disable-next-line default-case
282
+ switch (upgradeDb.oldVersion) {
283
+ case 0:
284
+ upgradeDb.createObjectStore(OBJECT_STORE_NAME);
285
+ }
286
+ });
287
+ }
288
+ return dbPromise;
289
+ }
290
+ /** Gets record(s) from the objectStore that match the given key. */
291
+ function dbGet(firebaseDependencies) {
292
+ return tslib.__awaiter(this, void 0, void 0, function () {
293
+ var key, db, tokenDetails, oldTokenDetails;
294
+ return tslib.__generator(this, function (_a) {
295
+ switch (_a.label) {
296
+ case 0:
297
+ key = getKey(firebaseDependencies);
298
+ return [4 /*yield*/, getDbPromise()];
299
+ case 1:
300
+ db = _a.sent();
301
+ return [4 /*yield*/, db
302
+ .transaction(OBJECT_STORE_NAME)
303
+ .objectStore(OBJECT_STORE_NAME)
304
+ .get(key)];
305
+ case 2:
306
+ tokenDetails = _a.sent();
307
+ if (!tokenDetails) return [3 /*break*/, 3];
308
+ return [2 /*return*/, tokenDetails];
309
+ case 3: return [4 /*yield*/, migrateOldDatabase(firebaseDependencies.appConfig.senderId)];
310
+ case 4:
311
+ oldTokenDetails = _a.sent();
312
+ if (!oldTokenDetails) return [3 /*break*/, 6];
313
+ return [4 /*yield*/, dbSet(firebaseDependencies, oldTokenDetails)];
314
+ case 5:
315
+ _a.sent();
316
+ return [2 /*return*/, oldTokenDetails];
317
+ case 6: return [2 /*return*/];
318
+ }
319
+ });
320
+ });
321
+ }
322
+ /** Assigns or overwrites the record for the given key with the given value. */
323
+ function dbSet(firebaseDependencies, tokenDetails) {
324
+ return tslib.__awaiter(this, void 0, void 0, function () {
325
+ var key, db, tx;
326
+ return tslib.__generator(this, function (_a) {
327
+ switch (_a.label) {
328
+ case 0:
329
+ key = getKey(firebaseDependencies);
330
+ return [4 /*yield*/, getDbPromise()];
331
+ case 1:
332
+ db = _a.sent();
333
+ tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
334
+ return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key)];
335
+ case 2:
336
+ _a.sent();
337
+ return [4 /*yield*/, tx.complete];
338
+ case 3:
339
+ _a.sent();
340
+ return [2 /*return*/, tokenDetails];
341
+ }
342
+ });
343
+ });
344
+ }
345
+ /** Removes record(s) from the objectStore that match the given key. */
346
+ function dbRemove(firebaseDependencies) {
347
+ return tslib.__awaiter(this, void 0, void 0, function () {
348
+ var key, db, tx;
349
+ return tslib.__generator(this, function (_a) {
350
+ switch (_a.label) {
351
+ case 0:
352
+ key = getKey(firebaseDependencies);
353
+ return [4 /*yield*/, getDbPromise()];
354
+ case 1:
355
+ db = _a.sent();
356
+ tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
357
+ return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];
358
+ case 2:
359
+ _a.sent();
360
+ return [4 /*yield*/, tx.complete];
361
+ case 3:
362
+ _a.sent();
363
+ return [2 /*return*/];
364
+ }
365
+ });
366
+ });
367
+ }
368
+ function getKey(_a) {
369
+ var appConfig = _a.appConfig;
370
+ return appConfig.appId;
371
+ }
372
+
373
+ /**
374
+ * @license
375
+ * Copyright 2017 Google LLC
376
+ *
377
+ * Licensed under the Apache License, Version 2.0 (the "License");
378
+ * you may not use this file except in compliance with the License.
379
+ * You may obtain a copy of the License at
380
+ *
381
+ * http://www.apache.org/licenses/LICENSE-2.0
382
+ *
383
+ * Unless required by applicable law or agreed to in writing, software
384
+ * distributed under the License is distributed on an "AS IS" BASIS,
385
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
386
+ * See the License for the specific language governing permissions and
387
+ * limitations under the License.
388
+ */
389
+ var _a;
390
+ var ERROR_MAP = (_a = {},
391
+ _a["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"',
392
+ _a["only-available-in-window" /* AVAILABLE_IN_WINDOW */] = 'This method is available in a Window context.',
393
+ _a["only-available-in-sw" /* AVAILABLE_IN_SW */] = 'This method is available in a service worker context.',
394
+ _a["permission-default" /* PERMISSION_DEFAULT */] = 'The notification permission was not granted and dismissed instead.',
395
+ _a["permission-blocked" /* PERMISSION_BLOCKED */] = 'The notification permission was not granted and blocked instead.',
396
+ _a["unsupported-browser" /* UNSUPPORTED_BROWSER */] = "This browser doesn't support the API's required to use the Firebase SDK.",
397
+ _a["indexed-db-unsupported" /* INDEXED_DB_UNSUPPORTED */] = "This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)",
398
+ _a["failed-service-worker-registration" /* FAILED_DEFAULT_REGISTRATION */] = 'We are unable to register the default service worker. {$browserErrorMessage}',
399
+ _a["token-subscribe-failed" /* TOKEN_SUBSCRIBE_FAILED */] = 'A problem occurred while subscribing the user to FCM: {$errorInfo}',
400
+ _a["token-subscribe-no-token" /* TOKEN_SUBSCRIBE_NO_TOKEN */] = 'FCM returned no token when subscribing the user to push.',
401
+ _a["token-unsubscribe-failed" /* TOKEN_UNSUBSCRIBE_FAILED */] = 'A problem occurred while unsubscribing the ' +
402
+ 'user from FCM: {$errorInfo}',
403
+ _a["token-update-failed" /* TOKEN_UPDATE_FAILED */] = 'A problem occurred while updating the user from FCM: {$errorInfo}',
404
+ _a["token-update-no-token" /* TOKEN_UPDATE_NO_TOKEN */] = 'FCM returned no token when updating the user to push.',
405
+ _a["use-sw-after-get-token" /* USE_SW_AFTER_GET_TOKEN */] = 'The useServiceWorker() method may only be called once and must be ' +
406
+ 'called before calling getToken() to ensure your service worker is used.',
407
+ _a["invalid-sw-registration" /* INVALID_SW_REGISTRATION */] = 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',
408
+ _a["invalid-bg-handler" /* INVALID_BG_HANDLER */] = 'The input to setBackgroundMessageHandler() must be a function.',
409
+ _a["invalid-vapid-key" /* INVALID_VAPID_KEY */] = 'The public VAPID key must be a string.',
410
+ _a["use-vapid-key-after-get-token" /* USE_VAPID_KEY_AFTER_GET_TOKEN */] = 'The usePublicVapidKey() method may only be called once and must be ' +
411
+ 'called before calling getToken() to ensure your VAPID key is used.',
412
+ _a);
413
+ var ERROR_FACTORY = new util.ErrorFactory('messaging', 'Messaging', ERROR_MAP);
414
+
415
+ /**
416
+ * @license
417
+ * Copyright 2019 Google LLC
418
+ *
419
+ * Licensed under the Apache License, Version 2.0 (the "License");
420
+ * you may not use this file except in compliance with the License.
421
+ * You may obtain a copy of the License at
422
+ *
423
+ * http://www.apache.org/licenses/LICENSE-2.0
424
+ *
425
+ * Unless required by applicable law or agreed to in writing, software
426
+ * distributed under the License is distributed on an "AS IS" BASIS,
427
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
428
+ * See the License for the specific language governing permissions and
429
+ * limitations under the License.
430
+ */
431
+ function requestGetToken(firebaseDependencies, subscriptionOptions) {
432
+ return tslib.__awaiter(this, void 0, void 0, function () {
433
+ var headers, body, subscribeOptions, responseData, response, err_1, message;
434
+ return tslib.__generator(this, function (_a) {
435
+ switch (_a.label) {
436
+ case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
437
+ case 1:
438
+ headers = _a.sent();
439
+ body = getBody(subscriptionOptions);
440
+ subscribeOptions = {
441
+ method: 'POST',
442
+ headers: headers,
443
+ body: JSON.stringify(body)
444
+ };
445
+ _a.label = 2;
446
+ case 2:
447
+ _a.trys.push([2, 5, , 6]);
448
+ return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions)];
449
+ case 3:
450
+ response = _a.sent();
451
+ return [4 /*yield*/, response.json()];
452
+ case 4:
453
+ responseData = _a.sent();
454
+ return [3 /*break*/, 6];
455
+ case 5:
456
+ err_1 = _a.sent();
457
+ throw ERROR_FACTORY.create("token-subscribe-failed" /* TOKEN_SUBSCRIBE_FAILED */, {
458
+ errorInfo: err_1
459
+ });
460
+ case 6:
461
+ if (responseData.error) {
462
+ message = responseData.error.message;
463
+ throw ERROR_FACTORY.create("token-subscribe-failed" /* TOKEN_SUBSCRIBE_FAILED */, {
464
+ errorInfo: message
465
+ });
466
+ }
467
+ if (!responseData.token) {
468
+ throw ERROR_FACTORY.create("token-subscribe-no-token" /* TOKEN_SUBSCRIBE_NO_TOKEN */);
469
+ }
470
+ return [2 /*return*/, responseData.token];
471
+ }
472
+ });
473
+ });
474
+ }
475
+ function requestUpdateToken(firebaseDependencies, tokenDetails) {
476
+ return tslib.__awaiter(this, void 0, void 0, function () {
477
+ var headers, body, updateOptions, responseData, response, err_2, message;
478
+ return tslib.__generator(this, function (_a) {
479
+ switch (_a.label) {
480
+ case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
481
+ case 1:
482
+ headers = _a.sent();
483
+ body = getBody(tokenDetails.subscriptionOptions);
484
+ updateOptions = {
485
+ method: 'PATCH',
486
+ headers: headers,
487
+ body: JSON.stringify(body)
488
+ };
489
+ _a.label = 2;
490
+ case 2:
491
+ _a.trys.push([2, 5, , 6]);
492
+ return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig) + "/" + tokenDetails.token, updateOptions)];
493
+ case 3:
494
+ response = _a.sent();
495
+ return [4 /*yield*/, response.json()];
496
+ case 4:
497
+ responseData = _a.sent();
498
+ return [3 /*break*/, 6];
499
+ case 5:
500
+ err_2 = _a.sent();
501
+ throw ERROR_FACTORY.create("token-update-failed" /* TOKEN_UPDATE_FAILED */, {
502
+ errorInfo: err_2
503
+ });
504
+ case 6:
505
+ if (responseData.error) {
506
+ message = responseData.error.message;
507
+ throw ERROR_FACTORY.create("token-update-failed" /* TOKEN_UPDATE_FAILED */, {
508
+ errorInfo: message
509
+ });
510
+ }
511
+ if (!responseData.token) {
512
+ throw ERROR_FACTORY.create("token-update-no-token" /* TOKEN_UPDATE_NO_TOKEN */);
513
+ }
514
+ return [2 /*return*/, responseData.token];
515
+ }
516
+ });
517
+ });
518
+ }
519
+ function requestDeleteToken(firebaseDependencies, token) {
520
+ return tslib.__awaiter(this, void 0, void 0, function () {
521
+ var headers, unsubscribeOptions, response, responseData, message, err_3;
522
+ return tslib.__generator(this, function (_a) {
523
+ switch (_a.label) {
524
+ case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
525
+ case 1:
526
+ headers = _a.sent();
527
+ unsubscribeOptions = {
528
+ method: 'DELETE',
529
+ headers: headers
530
+ };
531
+ _a.label = 2;
532
+ case 2:
533
+ _a.trys.push([2, 5, , 6]);
534
+ return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig) + "/" + token, unsubscribeOptions)];
535
+ case 3:
536
+ response = _a.sent();
537
+ return [4 /*yield*/, response.json()];
538
+ case 4:
539
+ responseData = _a.sent();
540
+ if (responseData.error) {
541
+ message = responseData.error.message;
542
+ throw ERROR_FACTORY.create("token-unsubscribe-failed" /* TOKEN_UNSUBSCRIBE_FAILED */, {
543
+ errorInfo: message
544
+ });
545
+ }
546
+ return [3 /*break*/, 6];
547
+ case 5:
548
+ err_3 = _a.sent();
549
+ throw ERROR_FACTORY.create("token-unsubscribe-failed" /* TOKEN_UNSUBSCRIBE_FAILED */, {
550
+ errorInfo: err_3
551
+ });
552
+ case 6: return [2 /*return*/];
553
+ }
554
+ });
555
+ });
556
+ }
557
+ function getEndpoint(_a) {
558
+ var projectId = _a.projectId;
559
+ return ENDPOINT + "/projects/" + projectId + "/registrations";
560
+ }
561
+ function getHeaders(_a) {
562
+ var appConfig = _a.appConfig, installations = _a.installations;
563
+ return tslib.__awaiter(this, void 0, void 0, function () {
564
+ var authToken;
565
+ return tslib.__generator(this, function (_b) {
566
+ switch (_b.label) {
567
+ case 0: return [4 /*yield*/, installations.getToken()];
568
+ case 1:
569
+ authToken = _b.sent();
570
+ return [2 /*return*/, new Headers({
571
+ 'Content-Type': 'application/json',
572
+ Accept: 'application/json',
573
+ 'x-goog-api-key': appConfig.apiKey,
574
+ 'x-goog-firebase-installations-auth': "FIS " + authToken
575
+ })];
576
+ }
577
+ });
578
+ });
579
+ }
580
+ function getBody(_a) {
581
+ var p256dh = _a.p256dh, auth = _a.auth, endpoint = _a.endpoint, vapidKey = _a.vapidKey;
582
+ var body = {
583
+ web: {
584
+ endpoint: endpoint,
585
+ auth: auth,
586
+ p256dh: p256dh
587
+ }
588
+ };
589
+ if (vapidKey !== DEFAULT_VAPID_KEY) {
590
+ body.web.applicationPubKey = vapidKey;
591
+ }
592
+ return body;
593
+ }
594
+
595
+ /**
596
+ * @license
597
+ * Copyright 2019 Google LLC
598
+ *
599
+ * Licensed under the Apache License, Version 2.0 (the "License");
600
+ * you may not use this file except in compliance with the License.
601
+ * You may obtain a copy of the License at
602
+ *
603
+ * http://www.apache.org/licenses/LICENSE-2.0
604
+ *
605
+ * Unless required by applicable law or agreed to in writing, software
606
+ * distributed under the License is distributed on an "AS IS" BASIS,
607
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
608
+ * See the License for the specific language governing permissions and
609
+ * limitations under the License.
610
+ */
611
+ // UpdateRegistration will be called once every week.
612
+ var TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
613
+ function getTokenInternal(messaging) {
614
+ return tslib.__awaiter(this, void 0, void 0, function () {
615
+ var pushSubscription, subscriptionOptions, tokenDetails, e_1;
616
+ return tslib.__generator(this, function (_a) {
617
+ switch (_a.label) {
618
+ case 0: return [4 /*yield*/, getPushSubscription(messaging.swRegistration, messaging.vapidKey)];
619
+ case 1:
620
+ pushSubscription = _a.sent();
621
+ subscriptionOptions = {
622
+ vapidKey: messaging.vapidKey,
623
+ swScope: messaging.swRegistration.scope,
624
+ endpoint: pushSubscription.endpoint,
625
+ auth: arrayToBase64(pushSubscription.getKey('auth')),
626
+ p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))
627
+ };
628
+ return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
629
+ case 2:
630
+ tokenDetails = _a.sent();
631
+ if (!!tokenDetails) return [3 /*break*/, 3];
632
+ // No token, get a new one.
633
+ return [2 /*return*/, getNewToken(messaging.firebaseDependencies, subscriptionOptions)];
634
+ case 3:
635
+ if (!!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) return [3 /*break*/, 8];
636
+ _a.label = 4;
637
+ case 4:
638
+ _a.trys.push([4, 6, , 7]);
639
+ return [4 /*yield*/, requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token)];
640
+ case 5:
641
+ _a.sent();
642
+ return [3 /*break*/, 7];
643
+ case 6:
644
+ e_1 = _a.sent();
645
+ // Suppress errors because of #2364
646
+ console.warn(e_1);
647
+ return [3 /*break*/, 7];
648
+ case 7: return [2 /*return*/, getNewToken(messaging.firebaseDependencies, subscriptionOptions)];
649
+ case 8:
650
+ if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {
651
+ // Weekly token refresh
652
+ return [2 /*return*/, updateToken(messaging, {
653
+ token: tokenDetails.token,
654
+ createTime: Date.now(),
655
+ subscriptionOptions: subscriptionOptions
656
+ })];
657
+ }
658
+ else {
659
+ // Valid token, nothing to do.
660
+ return [2 /*return*/, tokenDetails.token];
661
+ }
662
+ case 9: return [2 /*return*/];
663
+ }
664
+ });
665
+ });
666
+ }
667
+ /**
668
+ * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters
669
+ * the push subscription if it exists.
670
+ */
671
+ function deleteTokenInternal(messaging) {
672
+ return tslib.__awaiter(this, void 0, void 0, function () {
673
+ var tokenDetails, pushSubscription;
674
+ return tslib.__generator(this, function (_a) {
675
+ switch (_a.label) {
676
+ case 0: return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
677
+ case 1:
678
+ tokenDetails = _a.sent();
679
+ if (!tokenDetails) return [3 /*break*/, 4];
680
+ return [4 /*yield*/, requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token)];
681
+ case 2:
682
+ _a.sent();
683
+ return [4 /*yield*/, dbRemove(messaging.firebaseDependencies)];
684
+ case 3:
685
+ _a.sent();
686
+ _a.label = 4;
687
+ case 4: return [4 /*yield*/, messaging.swRegistration.pushManager.getSubscription()];
688
+ case 5:
689
+ pushSubscription = _a.sent();
690
+ if (pushSubscription) {
691
+ return [2 /*return*/, pushSubscription.unsubscribe()];
692
+ }
693
+ // If there's no SW, consider it a success.
694
+ return [2 /*return*/, true];
695
+ }
696
+ });
697
+ });
698
+ }
699
+ function updateToken(messaging, tokenDetails) {
700
+ return tslib.__awaiter(this, void 0, void 0, function () {
701
+ var updatedToken, updatedTokenDetails, e_2;
702
+ return tslib.__generator(this, function (_a) {
703
+ switch (_a.label) {
704
+ case 0:
705
+ _a.trys.push([0, 3, , 5]);
706
+ return [4 /*yield*/, requestUpdateToken(messaging.firebaseDependencies, tokenDetails)];
707
+ case 1:
708
+ updatedToken = _a.sent();
709
+ updatedTokenDetails = tslib.__assign(tslib.__assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });
710
+ return [4 /*yield*/, dbSet(messaging.firebaseDependencies, updatedTokenDetails)];
711
+ case 2:
712
+ _a.sent();
713
+ return [2 /*return*/, updatedToken];
714
+ case 3:
715
+ e_2 = _a.sent();
716
+ return [4 /*yield*/, deleteTokenInternal(messaging)];
717
+ case 4:
718
+ _a.sent();
719
+ throw e_2;
720
+ case 5: return [2 /*return*/];
721
+ }
722
+ });
723
+ });
724
+ }
725
+ function getNewToken(firebaseDependencies, subscriptionOptions) {
726
+ return tslib.__awaiter(this, void 0, void 0, function () {
727
+ var token, tokenDetails;
728
+ return tslib.__generator(this, function (_a) {
729
+ switch (_a.label) {
730
+ case 0: return [4 /*yield*/, requestGetToken(firebaseDependencies, subscriptionOptions)];
731
+ case 1:
732
+ token = _a.sent();
733
+ tokenDetails = {
734
+ token: token,
735
+ createTime: Date.now(),
736
+ subscriptionOptions: subscriptionOptions
737
+ };
738
+ return [4 /*yield*/, dbSet(firebaseDependencies, tokenDetails)];
739
+ case 2:
740
+ _a.sent();
741
+ return [2 /*return*/, tokenDetails.token];
742
+ }
743
+ });
744
+ });
745
+ }
746
+ /**
747
+ * Gets a PushSubscription for the current user.
748
+ */
749
+ function getPushSubscription(swRegistration, vapidKey) {
750
+ return tslib.__awaiter(this, void 0, void 0, function () {
751
+ var subscription;
752
+ return tslib.__generator(this, function (_a) {
753
+ switch (_a.label) {
754
+ case 0: return [4 /*yield*/, swRegistration.pushManager.getSubscription()];
755
+ case 1:
756
+ subscription = _a.sent();
757
+ if (subscription) {
758
+ return [2 /*return*/, subscription];
759
+ }
760
+ return [2 /*return*/, swRegistration.pushManager.subscribe({
761
+ userVisibleOnly: true,
762
+ // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key
763
+ // submitted to pushManager#subscribe must be of type Uint8Array.
764
+ applicationServerKey: base64ToArray(vapidKey)
765
+ })];
766
+ }
767
+ });
768
+ });
769
+ }
770
+ /**
771
+ * Checks if the saved tokenDetails object matches the configuration provided.
772
+ */
773
+ function isTokenValid(dbOptions, currentOptions) {
774
+ var isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;
775
+ var isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;
776
+ var isAuthEqual = currentOptions.auth === dbOptions.auth;
777
+ var isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;
778
+ return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;
779
+ }
780
+
781
+ /**
782
+ * @license
783
+ * Copyright 2020 Google LLC
784
+ *
785
+ * Licensed under the Apache License, Version 2.0 (the "License");
786
+ * you may not use this file except in compliance with the License.
787
+ * You may obtain a copy of the License at
788
+ *
789
+ * http://www.apache.org/licenses/LICENSE-2.0
790
+ *
791
+ * Unless required by applicable law or agreed to in writing, software
792
+ * distributed under the License is distributed on an "AS IS" BASIS,
793
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
794
+ * See the License for the specific language governing permissions and
795
+ * limitations under the License.
796
+ */
797
+ function externalizePayload(internalPayload) {
798
+ var payload = {
799
+ from: internalPayload.from,
800
+ // eslint-disable-next-line camelcase
801
+ collapseKey: internalPayload.collapse_key,
802
+ // eslint-disable-next-line camelcase
803
+ messageId: internalPayload.fcmMessageId
804
+ };
805
+ propagateNotificationPayload(payload, internalPayload);
806
+ propagateDataPayload(payload, internalPayload);
807
+ propagateFcmOptions(payload, internalPayload);
808
+ return payload;
809
+ }
810
+ function propagateNotificationPayload(payload, messagePayloadInternal) {
811
+ if (!messagePayloadInternal.notification) {
812
+ return;
813
+ }
814
+ payload.notification = {};
815
+ var title = messagePayloadInternal.notification.title;
816
+ if (!!title) {
817
+ payload.notification.title = title;
818
+ }
819
+ var body = messagePayloadInternal.notification.body;
820
+ if (!!body) {
821
+ payload.notification.body = body;
822
+ }
823
+ var image = messagePayloadInternal.notification.image;
824
+ if (!!image) {
825
+ payload.notification.image = image;
826
+ }
827
+ }
828
+ function propagateDataPayload(payload, messagePayloadInternal) {
829
+ if (!messagePayloadInternal.data) {
830
+ return;
831
+ }
832
+ payload.data = messagePayloadInternal.data;
833
+ }
834
+ function propagateFcmOptions(payload, messagePayloadInternal) {
835
+ if (!messagePayloadInternal.fcmOptions) {
836
+ return;
837
+ }
838
+ payload.fcmOptions = {};
839
+ var link = messagePayloadInternal.fcmOptions.link;
840
+ if (!!link) {
841
+ payload.fcmOptions.link = link;
842
+ }
843
+ // eslint-disable-next-line camelcase
844
+ var analyticsLabel = messagePayloadInternal.fcmOptions.analytics_label;
845
+ if (!!analyticsLabel) {
846
+ payload.fcmOptions.analyticsLabel = analyticsLabel;
847
+ }
848
+ }
849
+
850
+ /**
851
+ * @license
852
+ * Copyright 2019 Google LLC
853
+ *
854
+ * Licensed under the Apache License, Version 2.0 (the "License");
855
+ * you may not use this file except in compliance with the License.
856
+ * You may obtain a copy of the License at
857
+ *
858
+ * http://www.apache.org/licenses/LICENSE-2.0
859
+ *
860
+ * Unless required by applicable law or agreed to in writing, software
861
+ * distributed under the License is distributed on an "AS IS" BASIS,
862
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
863
+ * See the License for the specific language governing permissions and
864
+ * limitations under the License.
865
+ */
866
+ function isConsoleMessage(data) {
867
+ // This message has a campaign ID, meaning it was sent using the Firebase Console.
868
+ return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;
869
+ }
870
+
871
+ /**
872
+ * @license
873
+ * Copyright 2019 Google LLC
874
+ *
875
+ * Licensed under the Apache License, Version 2.0 (the "License");
876
+ * you may not use this file except in compliance with the License.
877
+ * You may obtain a copy of the License at
878
+ *
879
+ * http://www.apache.org/licenses/LICENSE-2.0
880
+ *
881
+ * Unless required by applicable law or agreed to in writing, software
882
+ * distributed under the License is distributed on an "AS IS" BASIS,
883
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
884
+ * See the License for the specific language governing permissions and
885
+ * limitations under the License.
886
+ */
887
+ /** Returns a promise that resolves after given time passes. */
888
+ function sleep(ms) {
889
+ return new Promise(function (resolve) {
890
+ setTimeout(resolve, ms);
891
+ });
892
+ }
893
+
894
+ /**
895
+ * @license
896
+ * Copyright 2019 Google LLC
897
+ *
898
+ * Licensed under the Apache License, Version 2.0 (the "License");
899
+ * you may not use this file except in compliance with the License.
900
+ * You may obtain a copy of the License at
901
+ *
902
+ * http://www.apache.org/licenses/LICENSE-2.0
903
+ *
904
+ * Unless required by applicable law or agreed to in writing, software
905
+ * distributed under the License is distributed on an "AS IS" BASIS,
906
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
907
+ * See the License for the specific language governing permissions and
908
+ * limitations under the License.
909
+ */
910
+ _mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');
911
+ _mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');
912
+ function stageLog(messaging, internalPayload) {
913
+ return tslib.__awaiter(this, void 0, void 0, function () {
914
+ var fcmEvent, _a, _b;
915
+ return tslib.__generator(this, function (_c) {
916
+ switch (_c.label) {
917
+ case 0:
918
+ _a = createFcmEvent;
919
+ _b = [internalPayload];
920
+ return [4 /*yield*/, messaging.firebaseDependencies.installations.getId()];
921
+ case 1:
922
+ fcmEvent = _a.apply(void 0, _b.concat([_c.sent()]));
923
+ createAndEnqueueLogEvent(messaging, fcmEvent);
924
+ return [2 /*return*/];
925
+ }
926
+ });
927
+ });
928
+ }
929
+ function createFcmEvent(internalPayload, fid) {
930
+ var _a, _b;
931
+ var fcmEvent = {};
932
+ /* eslint-disable camelcase */
933
+ // some fields should always be non-null. Still check to ensure.
934
+ if (!!internalPayload.from) {
935
+ fcmEvent.project_number = internalPayload.from;
936
+ }
937
+ if (!!internalPayload.fcmMessageId) {
938
+ fcmEvent.message_id = internalPayload.fcmMessageId;
939
+ }
940
+ fcmEvent.instance_id = fid;
941
+ if (!!internalPayload.notification) {
942
+ fcmEvent.message_type = MessageType$1.DISPLAY_NOTIFICATION.toString();
943
+ }
944
+ else {
945
+ fcmEvent.message_type = MessageType$1.DATA_MESSAGE.toString();
946
+ }
947
+ fcmEvent.sdk_platform = SDK_PLATFORM_WEB.toString();
948
+ fcmEvent.package_name = self.origin.replace(/(^\w+:|^)\/\//, '');
949
+ if (!!internalPayload.collapse_key) {
950
+ fcmEvent.collapse_key = internalPayload.collapse_key;
951
+ }
952
+ fcmEvent.event = EVENT_MESSAGE_DELIVERED.toString();
953
+ if (!!((_a = internalPayload.fcmOptions) === null || _a === void 0 ? void 0 : _a.analytics_label)) {
954
+ fcmEvent.analytics_label = (_b = internalPayload.fcmOptions) === null || _b === void 0 ? void 0 : _b.analytics_label;
955
+ }
956
+ /* eslint-enable camelcase */
957
+ return fcmEvent;
958
+ }
959
+ function createAndEnqueueLogEvent(messaging, fcmEvent) {
960
+ var logEvent = {};
961
+ /* eslint-disable camelcase */
962
+ logEvent.event_time_ms = Math.floor(Date.now()).toString();
963
+ logEvent.source_extension_json_proto3 = JSON.stringify(fcmEvent);
964
+ // eslint-disable-next-line camelcase
965
+ messaging.logEvents.push(logEvent);
966
+ }
967
+ function _mergeStrings(s1, s2) {
968
+ var resultArray = [];
969
+ for (var i = 0; i < s1.length; i++) {
970
+ resultArray.push(s1.charAt(i));
971
+ if (i < s2.length) {
972
+ resultArray.push(s2.charAt(i));
973
+ }
974
+ }
975
+ return resultArray.join('');
976
+ }
977
+
978
+ /**
979
+ * @license
980
+ * Copyright 2017 Google LLC
981
+ *
982
+ * Licensed under the Apache License, Version 2.0 (the "License");
983
+ * you may not use this file except in compliance with the License.
984
+ * You may obtain a copy of the License at
985
+ *
986
+ * http://www.apache.org/licenses/LICENSE-2.0
987
+ *
988
+ * Unless required by applicable law or agreed to in writing, software
989
+ * distributed under the License is distributed on an "AS IS" BASIS,
990
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
991
+ * See the License for the specific language governing permissions and
992
+ * limitations under the License.
993
+ */
994
+ function onSubChange(event, messaging) {
995
+ var _a, _b;
996
+ return tslib.__awaiter(this, void 0, void 0, function () {
997
+ var newSubscription, tokenDetails;
998
+ return tslib.__generator(this, function (_c) {
999
+ switch (_c.label) {
1000
+ case 0:
1001
+ newSubscription = event.newSubscription;
1002
+ if (!!newSubscription) return [3 /*break*/, 2];
1003
+ // Subscription revoked, delete token
1004
+ return [4 /*yield*/, deleteTokenInternal(messaging)];
1005
+ case 1:
1006
+ // Subscription revoked, delete token
1007
+ _c.sent();
1008
+ return [2 /*return*/];
1009
+ case 2: return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
1010
+ case 3:
1011
+ tokenDetails = _c.sent();
1012
+ return [4 /*yield*/, deleteTokenInternal(messaging)];
1013
+ case 4:
1014
+ _c.sent();
1015
+ messaging.vapidKey =
1016
+ (_b = (_a = tokenDetails === null || tokenDetails === void 0 ? void 0 : tokenDetails.subscriptionOptions) === null || _a === void 0 ? void 0 : _a.vapidKey) !== null && _b !== void 0 ? _b : DEFAULT_VAPID_KEY;
1017
+ return [4 /*yield*/, getTokenInternal(messaging)];
1018
+ case 5:
1019
+ _c.sent();
1020
+ return [2 /*return*/];
1021
+ }
1022
+ });
1023
+ });
1024
+ }
1025
+ function onPush(event, messaging) {
1026
+ return tslib.__awaiter(this, void 0, void 0, function () {
1027
+ var internalPayload, clientList, payload;
1028
+ return tslib.__generator(this, function (_a) {
1029
+ switch (_a.label) {
1030
+ case 0:
1031
+ internalPayload = getMessagePayloadInternal(event);
1032
+ if (!internalPayload) {
1033
+ // Failed to get parsed MessagePayload from the PushEvent. Skip handling the push.
1034
+ return [2 /*return*/];
1035
+ }
1036
+ if (!messaging.deliveryMetricsExportedToBigQueryEnabled) return [3 /*break*/, 2];
1037
+ return [4 /*yield*/, stageLog(messaging, internalPayload)];
1038
+ case 1:
1039
+ _a.sent();
1040
+ _a.label = 2;
1041
+ case 2: return [4 /*yield*/, getClientList()];
1042
+ case 3:
1043
+ clientList = _a.sent();
1044
+ if (hasVisibleClients(clientList)) {
1045
+ return [2 /*return*/, sendMessagePayloadInternalToWindows(clientList, internalPayload)];
1046
+ }
1047
+ if (!!!internalPayload.notification) return [3 /*break*/, 5];
1048
+ return [4 /*yield*/, showNotification(wrapInternalPayload(internalPayload))];
1049
+ case 4:
1050
+ _a.sent();
1051
+ _a.label = 5;
1052
+ case 5:
1053
+ if (!messaging) {
1054
+ return [2 /*return*/];
1055
+ }
1056
+ if (!!messaging.onBackgroundMessageHandler) {
1057
+ payload = externalizePayload(internalPayload);
1058
+ if (typeof messaging.onBackgroundMessageHandler === 'function') {
1059
+ messaging.onBackgroundMessageHandler(payload);
1060
+ }
1061
+ else {
1062
+ messaging.onBackgroundMessageHandler.next(payload);
1063
+ }
1064
+ }
1065
+ return [2 /*return*/];
1066
+ }
1067
+ });
1068
+ });
1069
+ }
1070
+ function onNotificationClick(event) {
1071
+ var _a, _b;
1072
+ return tslib.__awaiter(this, void 0, void 0, function () {
1073
+ var internalPayload, link, url, originUrl, client;
1074
+ return tslib.__generator(this, function (_c) {
1075
+ switch (_c.label) {
1076
+ case 0:
1077
+ internalPayload = (_b = (_a = event.notification) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[FCM_MSG];
1078
+ if (!internalPayload) {
1079
+ return [2 /*return*/];
1080
+ }
1081
+ else if (event.action) {
1082
+ // User clicked on an action button. This will allow developers to act on action button clicks
1083
+ // by using a custom onNotificationClick listener that they define.
1084
+ return [2 /*return*/];
1085
+ }
1086
+ // Prevent other listeners from receiving the event
1087
+ event.stopImmediatePropagation();
1088
+ event.notification.close();
1089
+ link = getLink(internalPayload);
1090
+ if (!link) {
1091
+ return [2 /*return*/];
1092
+ }
1093
+ url = new URL(link, self.location.href);
1094
+ originUrl = new URL(self.location.origin);
1095
+ if (url.host !== originUrl.host) {
1096
+ return [2 /*return*/];
1097
+ }
1098
+ return [4 /*yield*/, getWindowClient(url)];
1099
+ case 1:
1100
+ client = _c.sent();
1101
+ if (!!client) return [3 /*break*/, 4];
1102
+ return [4 /*yield*/, self.clients.openWindow(link)];
1103
+ case 2:
1104
+ client = _c.sent();
1105
+ // Wait three seconds for the client to initialize and set up the message handler so that it
1106
+ // can receive the message.
1107
+ return [4 /*yield*/, sleep(3000)];
1108
+ case 3:
1109
+ // Wait three seconds for the client to initialize and set up the message handler so that it
1110
+ // can receive the message.
1111
+ _c.sent();
1112
+ return [3 /*break*/, 6];
1113
+ case 4: return [4 /*yield*/, client.focus()];
1114
+ case 5:
1115
+ client = _c.sent();
1116
+ _c.label = 6;
1117
+ case 6:
1118
+ if (!client) {
1119
+ // Window Client will not be returned if it's for a third party origin.
1120
+ return [2 /*return*/];
1121
+ }
1122
+ internalPayload.messageType = MessageType.NOTIFICATION_CLICKED;
1123
+ internalPayload.isFirebaseMessaging = true;
1124
+ return [2 /*return*/, client.postMessage(internalPayload)];
1125
+ }
1126
+ });
1127
+ });
1128
+ }
1129
+ function wrapInternalPayload(internalPayload) {
1130
+ var _a;
1131
+ var wrappedInternalPayload = tslib.__assign({}, internalPayload.notification);
1132
+ // Put the message payload under FCM_MSG name so we can identify the notification as being an FCM
1133
+ // notification vs a notification from somewhere else (i.e. normal web push or developer generated
1134
+ // notification).
1135
+ wrappedInternalPayload.data = (_a = {},
1136
+ _a[FCM_MSG] = internalPayload,
1137
+ _a);
1138
+ return wrappedInternalPayload;
1139
+ }
1140
+ function getMessagePayloadInternal(_a) {
1141
+ var data = _a.data;
1142
+ if (!data) {
1143
+ return null;
1144
+ }
1145
+ try {
1146
+ return data.json();
1147
+ }
1148
+ catch (err) {
1149
+ // Not JSON so not an FCM message.
1150
+ return null;
1151
+ }
1152
+ }
1153
+ /**
1154
+ * @param url The URL to look for when focusing a client.
1155
+ * @return Returns an existing window client or a newly opened WindowClient.
1156
+ */
1157
+ function getWindowClient(url) {
1158
+ return tslib.__awaiter(this, void 0, void 0, function () {
1159
+ var clientList, clientList_1, clientList_1_1, client, clientUrl;
1160
+ var e_1, _a;
1161
+ return tslib.__generator(this, function (_b) {
1162
+ switch (_b.label) {
1163
+ case 0: return [4 /*yield*/, getClientList()];
1164
+ case 1:
1165
+ clientList = _b.sent();
1166
+ try {
1167
+ for (clientList_1 = tslib.__values(clientList), clientList_1_1 = clientList_1.next(); !clientList_1_1.done; clientList_1_1 = clientList_1.next()) {
1168
+ client = clientList_1_1.value;
1169
+ clientUrl = new URL(client.url, self.location.href);
1170
+ if (url.host === clientUrl.host) {
1171
+ return [2 /*return*/, client];
1172
+ }
1173
+ }
1174
+ }
1175
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1176
+ finally {
1177
+ try {
1178
+ if (clientList_1_1 && !clientList_1_1.done && (_a = clientList_1.return)) _a.call(clientList_1);
1179
+ }
1180
+ finally { if (e_1) throw e_1.error; }
1181
+ }
1182
+ return [2 /*return*/, null];
1183
+ }
1184
+ });
1185
+ });
1186
+ }
1187
+ /**
1188
+ * @returns If there is currently a visible WindowClient, this method will resolve to true,
1189
+ * otherwise false.
1190
+ */
1191
+ function hasVisibleClients(clientList) {
1192
+ return clientList.some(function (client) {
1193
+ return client.visibilityState === 'visible' &&
1194
+ // Ignore chrome-extension clients as that matches the background pages of extensions, which
1195
+ // are always considered visible for some reason.
1196
+ !client.url.startsWith('chrome-extension://');
1197
+ });
1198
+ }
1199
+ function sendMessagePayloadInternalToWindows(clientList, internalPayload) {
1200
+ var e_2, _a;
1201
+ internalPayload.isFirebaseMessaging = true;
1202
+ internalPayload.messageType = MessageType.PUSH_RECEIVED;
1203
+ try {
1204
+ for (var clientList_2 = tslib.__values(clientList), clientList_2_1 = clientList_2.next(); !clientList_2_1.done; clientList_2_1 = clientList_2.next()) {
1205
+ var client = clientList_2_1.value;
1206
+ client.postMessage(internalPayload);
1207
+ }
1208
+ }
1209
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1210
+ finally {
1211
+ try {
1212
+ if (clientList_2_1 && !clientList_2_1.done && (_a = clientList_2.return)) _a.call(clientList_2);
1213
+ }
1214
+ finally { if (e_2) throw e_2.error; }
1215
+ }
1216
+ }
1217
+ function getClientList() {
1218
+ return self.clients.matchAll({
1219
+ type: 'window',
1220
+ includeUncontrolled: true
1221
+ // TS doesn't know that "type: 'window'" means it'll return WindowClient[]
1222
+ });
1223
+ }
1224
+ function showNotification(notificationPayloadInternal) {
1225
+ var _a;
1226
+ // Note: Firefox does not support the maxActions property.
1227
+ // https://developer.mozilla.org/en-US/docs/Web/API/notification/maxActions
1228
+ var actions = notificationPayloadInternal.actions;
1229
+ var maxActions = Notification.maxActions;
1230
+ if (actions && maxActions && actions.length > maxActions) {
1231
+ console.warn("This browser only supports " + maxActions + " actions. The remaining actions will not be displayed.");
1232
+ }
1233
+ return self.registration.showNotification(
1234
+ /* title= */ (_a = notificationPayloadInternal.title) !== null && _a !== void 0 ? _a : '', notificationPayloadInternal);
1235
+ }
1236
+ function getLink(payload) {
1237
+ var _a, _b, _c;
1238
+ // eslint-disable-next-line camelcase
1239
+ var link = (_b = (_a = payload.fcmOptions) === null || _a === void 0 ? void 0 : _a.link) !== null && _b !== void 0 ? _b : (_c = payload.notification) === null || _c === void 0 ? void 0 : _c.click_action;
1240
+ if (link) {
1241
+ return link;
1242
+ }
1243
+ if (isConsoleMessage(payload.data)) {
1244
+ // Notification created in the Firebase Console. Redirect to origin.
1245
+ return self.location.origin;
1246
+ }
1247
+ else {
1248
+ return null;
1249
+ }
1250
+ }
1251
+
1252
+ /**
1253
+ * @license
1254
+ * Copyright 2019 Google LLC
1255
+ *
1256
+ * Licensed under the Apache License, Version 2.0 (the "License");
1257
+ * you may not use this file except in compliance with the License.
1258
+ * You may obtain a copy of the License at
1259
+ *
1260
+ * http://www.apache.org/licenses/LICENSE-2.0
1261
+ *
1262
+ * Unless required by applicable law or agreed to in writing, software
1263
+ * distributed under the License is distributed on an "AS IS" BASIS,
1264
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1265
+ * See the License for the specific language governing permissions and
1266
+ * limitations under the License.
1267
+ */
1268
+ function extractAppConfig(app) {
1269
+ var e_1, _a;
1270
+ if (!app || !app.options) {
1271
+ throw getMissingValueError('App Configuration Object');
1272
+ }
1273
+ if (!app.name) {
1274
+ throw getMissingValueError('App Name');
1275
+ }
1276
+ // Required app config keys
1277
+ var configKeys = [
1278
+ 'projectId',
1279
+ 'apiKey',
1280
+ 'appId',
1281
+ 'messagingSenderId'
1282
+ ];
1283
+ var options = app.options;
1284
+ try {
1285
+ for (var configKeys_1 = tslib.__values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {
1286
+ var keyName = configKeys_1_1.value;
1287
+ if (!options[keyName]) {
1288
+ throw getMissingValueError(keyName);
1289
+ }
1290
+ }
1291
+ }
1292
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1293
+ finally {
1294
+ try {
1295
+ if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);
1296
+ }
1297
+ finally { if (e_1) throw e_1.error; }
1298
+ }
1299
+ return {
1300
+ appName: app.name,
1301
+ projectId: options.projectId,
1302
+ apiKey: options.apiKey,
1303
+ appId: options.appId,
1304
+ senderId: options.messagingSenderId
1305
+ };
1306
+ }
1307
+ function getMissingValueError(valueName) {
1308
+ return ERROR_FACTORY.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, {
1309
+ valueName: valueName
1310
+ });
1311
+ }
1312
+
1313
+ /**
1314
+ * @license
1315
+ * Copyright 2020 Google LLC
1316
+ *
1317
+ * Licensed under the Apache License, Version 2.0 (the "License");
1318
+ * you may not use this file except in compliance with the License.
1319
+ * You may obtain a copy of the License at
1320
+ *
1321
+ * http://www.apache.org/licenses/LICENSE-2.0
1322
+ *
1323
+ * Unless required by applicable law or agreed to in writing, software
1324
+ * distributed under the License is distributed on an "AS IS" BASIS,
1325
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1326
+ * See the License for the specific language governing permissions and
1327
+ * limitations under the License.
1328
+ */
1329
+ var MessagingService = /** @class */ (function () {
1330
+ function MessagingService(app, installations, analyticsProvider) {
1331
+ // logging is only done with end user consent. Default to false.
1332
+ this.deliveryMetricsExportedToBigQueryEnabled = false;
1333
+ this.onBackgroundMessageHandler = null;
1334
+ this.onMessageHandler = null;
1335
+ this.logEvents = [];
1336
+ this.isLogServiceStarted = false;
1337
+ var appConfig = extractAppConfig(app);
1338
+ this.firebaseDependencies = {
1339
+ app: app,
1340
+ appConfig: appConfig,
1341
+ installations: installations,
1342
+ analyticsProvider: analyticsProvider
1343
+ };
1344
+ }
1345
+ MessagingService.prototype._delete = function () {
1346
+ return Promise.resolve();
1347
+ };
1348
+ return MessagingService;
1349
+ }());
1350
+
1351
+ /**
1352
+ * @license
1353
+ * Copyright 2020 Google LLC
1354
+ *
1355
+ * Licensed under the Apache License, Version 2.0 (the "License");
1356
+ * you may not use this file except in compliance with the License.
1357
+ * You may obtain a copy of the License at
1358
+ *
1359
+ * http://www.apache.org/licenses/LICENSE-2.0
1360
+ *
1361
+ * Unless required by applicable law or agreed to in writing, software
1362
+ * distributed under the License is distributed on an "AS IS" BASIS,
1363
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1364
+ * See the License for the specific language governing permissions and
1365
+ * limitations under the License.
1366
+ */
1367
+ var SwMessagingFactory = function (container) {
1368
+ var messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));
1369
+ self.addEventListener('push', function (e) {
1370
+ e.waitUntil(onPush(e, messaging));
1371
+ });
1372
+ self.addEventListener('pushsubscriptionchange', function (e) {
1373
+ e.waitUntil(onSubChange(e, messaging));
1374
+ });
1375
+ self.addEventListener('notificationclick', function (e) {
1376
+ e.waitUntil(onNotificationClick(e));
1377
+ });
1378
+ return messaging;
1379
+ };
1380
+ /**
1381
+ * The messaging instance registered in sw is named differently than that of in client. This is
1382
+ * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in
1383
+ * `messaging-compat` and component with the same name can only be registered once.
1384
+ */
1385
+ function registerMessagingInSw() {
1386
+ app._registerComponent(new component.Component('messaging-sw', SwMessagingFactory, "PUBLIC" /* PUBLIC */));
1387
+ }
1388
+
1389
+ /**
1390
+ * @license
1391
+ * Copyright 2020 Google LLC
1392
+ *
1393
+ * Licensed under the Apache License, Version 2.0 (the "License");
1394
+ * you may not use this file except in compliance with the License.
1395
+ * You may obtain a copy of the License at
1396
+ *
1397
+ * http://www.apache.org/licenses/LICENSE-2.0
1398
+ *
1399
+ * Unless required by applicable law or agreed to in writing, software
1400
+ * distributed under the License is distributed on an "AS IS" BASIS,
1401
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1402
+ * See the License for the specific language governing permissions and
1403
+ * limitations under the License.
1404
+ */
1405
+ /**
1406
+ * Checks whether all required APIs exist within SW Context
1407
+ * @returns a Promise that resolves to a boolean.
1408
+ *
1409
+ * @public
1410
+ */
1411
+ function isSwSupported() {
1412
+ return tslib.__awaiter(this, void 0, void 0, function () {
1413
+ var _a;
1414
+ return tslib.__generator(this, function (_b) {
1415
+ switch (_b.label) {
1416
+ case 0:
1417
+ _a = util.isIndexedDBAvailable();
1418
+ if (!_a) return [3 /*break*/, 2];
1419
+ return [4 /*yield*/, util.validateIndexedDBOpenable()];
1420
+ case 1:
1421
+ _a = (_b.sent());
1422
+ _b.label = 2;
1423
+ case 2:
1424
+ // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing
1425
+ // might be prohibited to run. In these contexts, an error would be thrown during the messaging
1426
+ // instantiating phase, informing the developers to import/call isSupported for special handling.
1427
+ return [2 /*return*/, (_a &&
1428
+ 'PushManager' in self &&
1429
+ 'Notification' in self &&
1430
+ ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
1431
+ PushSubscription.prototype.hasOwnProperty('getKey'))];
1432
+ }
1433
+ });
1434
+ });
1435
+ }
1436
+
1437
+ /**
1438
+ * @license
1439
+ * Copyright 2020 Google LLC
1440
+ *
1441
+ * Licensed under the Apache License, Version 2.0 (the "License");
1442
+ * you may not use this file except in compliance with the License.
1443
+ * You may obtain a copy of the License at
1444
+ *
1445
+ * http://www.apache.org/licenses/LICENSE-2.0
1446
+ *
1447
+ * Unless required by applicable law or agreed to in writing, software
1448
+ * distributed under the License is distributed on an "AS IS" BASIS,
1449
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1450
+ * See the License for the specific language governing permissions and
1451
+ * limitations under the License.
1452
+ */
1453
+ function onBackgroundMessage$1(messaging, nextOrObserver) {
1454
+ if (self.document !== undefined) {
1455
+ throw ERROR_FACTORY.create("only-available-in-sw" /* AVAILABLE_IN_SW */);
1456
+ }
1457
+ messaging.onBackgroundMessageHandler = nextOrObserver;
1458
+ return function () {
1459
+ messaging.onBackgroundMessageHandler = null;
1460
+ };
1461
+ }
1462
+
1463
+ /**
1464
+ * @license
1465
+ * Copyright 2020 Google LLC
1466
+ *
1467
+ * Licensed under the Apache License, Version 2.0 (the "License");
1468
+ * you may not use this file except in compliance with the License.
1469
+ * You may obtain a copy of the License at
1470
+ *
1471
+ * http://www.apache.org/licenses/LICENSE-2.0
1472
+ *
1473
+ * Unless required by applicable law or agreed to in writing, software
1474
+ * distributed under the License is distributed on an "AS IS" BASIS,
1475
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1476
+ * See the License for the specific language governing permissions and
1477
+ * limitations under the License.
1478
+ */
1479
+ function _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable) {
1480
+ messaging.deliveryMetricsExportedToBigQueryEnabled =
1481
+ enable;
1482
+ }
1483
+
1484
+ /**
1485
+ * @license
1486
+ * Copyright 2017 Google LLC
1487
+ *
1488
+ * Licensed under the Apache License, Version 2.0 (the "License");
1489
+ * you may not use this file except in compliance with the License.
1490
+ * You may obtain a copy of the License at
1491
+ *
1492
+ * http://www.apache.org/licenses/LICENSE-2.0
1493
+ *
1494
+ * Unless required by applicable law or agreed to in writing, software
1495
+ * distributed under the License is distributed on an "AS IS" BASIS,
1496
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1497
+ * See the License for the specific language governing permissions and
1498
+ * limitations under the License.
1499
+ */
1500
+ /**
1501
+ * Retrieves a Firebase Cloud Messaging instance.
1502
+ *
1503
+ * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
1504
+ *
1505
+ * @public
1506
+ */
1507
+ function getMessagingInSw(app$1) {
1508
+ if (app$1 === void 0) { app$1 = app.getApp(); }
1509
+ // Conscious decision to make this async check non-blocking during the messaging instance
1510
+ // initialization phase for performance consideration. An error would be thrown latter for
1511
+ // developer's information. Developers can then choose to import and call `isSupported` for
1512
+ // special handling.
1513
+ isSwSupported().then(function (isSupported) {
1514
+ // If `isSwSupported()` resolved, but returned false.
1515
+ if (!isSupported) {
1516
+ throw ERROR_FACTORY.create("unsupported-browser" /* UNSUPPORTED_BROWSER */);
1517
+ }
1518
+ }, function (_) {
1519
+ // If `isSwSupported()` rejected.
1520
+ throw ERROR_FACTORY.create("indexed-db-unsupported" /* INDEXED_DB_UNSUPPORTED */);
1521
+ });
1522
+ return app._getProvider(util.getModularInstance(app$1), 'messaging-sw').getImmediate();
1523
+ }
1524
+ /**
1525
+ * Called when a message is received while the app is in the background. An app is considered to be
1526
+ * in the background if no active window is displayed.
1527
+ *
1528
+ * @param messaging - The {@link Messaging} instance.
1529
+ * @param nextOrObserver - This function, or observer object with `next` defined, is called when a
1530
+ * message is received and the app is currently in the background.
1531
+ *
1532
+ * @returns To stop listening for messages execute this returned function
1533
+ *
1534
+ * @public
1535
+ */
1536
+ function onBackgroundMessage(messaging, nextOrObserver) {
1537
+ messaging = util.getModularInstance(messaging);
1538
+ return onBackgroundMessage$1(messaging, nextOrObserver);
1539
+ }
1540
+ /**
1541
+ * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By
1542
+ * default, message delivery metrics are not exported to BigQuery. Use this method to enable or
1543
+ * disable the export at runtime.
1544
+ *
1545
+ * @param messaging - The `FirebaseMessaging` instance.
1546
+ * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to
1547
+ * BigQuery.
1548
+ *
1549
+ * @public
1550
+ */
1551
+ function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(messaging, enable) {
1552
+ messaging = util.getModularInstance(messaging);
1553
+ return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);
1554
+ }
1555
+
1556
+ /**
1557
+ * @license
1558
+ * Copyright 2017 Google LLC
1559
+ *
1560
+ * Licensed under the Apache License, Version 2.0 (the "License");
1561
+ * you may not use this file except in compliance with the License.
1562
+ * You may obtain a copy of the License at
1563
+ *
1564
+ * http://www.apache.org/licenses/LICENSE-2.0
1565
+ *
1566
+ * Unless required by applicable law or agreed to in writing, software
1567
+ * distributed under the License is distributed on an "AS IS" BASIS,
1568
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1569
+ * See the License for the specific language governing permissions and
1570
+ * limitations under the License.
1571
+ */
1572
+ registerMessagingInSw();
1573
+
1574
+ exports.experimentalSetDeliveryMetricsExportedToBigQueryEnabled = experimentalSetDeliveryMetricsExportedToBigQueryEnabled;
1575
+ exports.getMessaging = getMessagingInSw;
1576
+ exports.isSupported = isSwSupported;
1577
+ exports.onBackgroundMessage = onBackgroundMessage;
1578
+ //# sourceMappingURL=index.sw.cjs.map