No Description
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.

index.esm2017.js 48KB

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