@firebase/messaging 0.12.12 → 0.12.13

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