@firebase/messaging 0.12.13 → 0.12.14-canary.ffbf5a60a

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