@firebase/messaging 0.12.13 → 0.12.14-canary.1294e64c8

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