GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1533 lines
66 KiB

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