@firebase/app 0.10.15 → 0.10.16

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 (52) hide show
  1. package/dist/app/src/api.d.ts +207 -207
  2. package/dist/app/src/api.test.d.ts +22 -22
  3. package/dist/app/src/constants.d.ts +26 -26
  4. package/dist/app/src/errors.d.ts +67 -67
  5. package/dist/app/src/firebaseApp.d.ts +46 -46
  6. package/dist/app/src/firebaseApp.test.d.ts +17 -17
  7. package/dist/app/src/firebaseServerApp.d.ts +36 -36
  8. package/dist/app/src/firebaseServerApp.test.d.ts +17 -17
  9. package/dist/app/src/global_index.d.ts +868 -868
  10. package/dist/app/src/heartbeatService.d.ts +83 -83
  11. package/dist/app/src/heartbeatService.test.d.ts +23 -23
  12. package/dist/app/src/index.d.ts +9 -9
  13. package/dist/app/src/indexeddb.d.ts +20 -20
  14. package/dist/app/src/indexeddb.test.d.ts +17 -17
  15. package/dist/app/src/internal.d.ts +99 -99
  16. package/dist/app/src/internal.test.d.ts +23 -23
  17. package/dist/app/src/logger.d.ts +18 -18
  18. package/dist/app/src/platformLoggerService.d.ts +23 -23
  19. package/dist/app/src/platformLoggerService.test.d.ts +24 -24
  20. package/dist/app/src/public-types.d.ts +231 -231
  21. package/dist/app/src/registerCoreComponents.d.ts +17 -17
  22. package/dist/app/src/types.d.ts +55 -55
  23. package/dist/app/test/setup.d.ts +17 -17
  24. package/dist/app/test/util.d.ts +26 -26
  25. package/dist/esm/app/src/api.d.ts +207 -207
  26. package/dist/esm/app/src/api.test.d.ts +22 -22
  27. package/dist/esm/app/src/constants.d.ts +26 -26
  28. package/dist/esm/app/src/errors.d.ts +67 -67
  29. package/dist/esm/app/src/firebaseApp.d.ts +46 -46
  30. package/dist/esm/app/src/firebaseApp.test.d.ts +17 -17
  31. package/dist/esm/app/src/firebaseServerApp.d.ts +36 -36
  32. package/dist/esm/app/src/firebaseServerApp.test.d.ts +17 -17
  33. package/dist/esm/app/src/heartbeatService.d.ts +83 -83
  34. package/dist/esm/app/src/heartbeatService.test.d.ts +23 -23
  35. package/dist/esm/app/src/index.d.ts +9 -9
  36. package/dist/esm/app/src/indexeddb.d.ts +20 -20
  37. package/dist/esm/app/src/indexeddb.test.d.ts +17 -17
  38. package/dist/esm/app/src/internal.d.ts +99 -99
  39. package/dist/esm/app/src/internal.test.d.ts +23 -23
  40. package/dist/esm/app/src/logger.d.ts +18 -18
  41. package/dist/esm/app/src/platformLoggerService.d.ts +23 -23
  42. package/dist/esm/app/src/platformLoggerService.test.d.ts +24 -24
  43. package/dist/esm/app/src/public-types.d.ts +231 -231
  44. package/dist/esm/app/src/registerCoreComponents.d.ts +17 -17
  45. package/dist/esm/app/src/types.d.ts +55 -55
  46. package/dist/esm/app/test/setup.d.ts +17 -17
  47. package/dist/esm/app/test/util.d.ts +26 -26
  48. package/dist/esm/index.esm2017.js +1069 -1069
  49. package/dist/esm/index.esm2017.js.map +1 -1
  50. package/dist/index.cjs.js +1069 -1069
  51. package/dist/index.cjs.js.map +1 -1
  52. package/package.json +5 -5
@@ -4,78 +4,78 @@ import { ErrorFactory, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, F
4
4
  export { FirebaseError } from '@firebase/util';
5
5
  import { openDB } from 'idb';
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
- class PlatformLoggerServiceImpl {
24
- constructor(container) {
25
- this.container = container;
26
- }
27
- // In initial implementation, this will be called by installations on
28
- // auth token refresh, and installations will send this string.
29
- getPlatformInfoString() {
30
- const providers = this.container.getProviders();
31
- // Loop through providers and get library/version pairs from any that are
32
- // version components.
33
- return providers
34
- .map(provider => {
35
- if (isVersionServiceProvider(provider)) {
36
- const service = provider.getImmediate();
37
- return `${service.library}/${service.version}`;
38
- }
39
- else {
40
- return null;
41
- }
42
- })
43
- .filter(logString => logString)
44
- .join(' ');
45
- }
46
- }
47
- /**
48
- *
49
- * @param provider check if this provider provides a VersionService
50
- *
51
- * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
52
- * provides VersionService. The provider is not necessarily a 'app-version'
53
- * provider.
54
- */
55
- function isVersionServiceProvider(provider) {
56
- const component = provider.getComponent();
57
- return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */;
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
+ class PlatformLoggerServiceImpl {
24
+ constructor(container) {
25
+ this.container = container;
26
+ }
27
+ // In initial implementation, this will be called by installations on
28
+ // auth token refresh, and installations will send this string.
29
+ getPlatformInfoString() {
30
+ const providers = this.container.getProviders();
31
+ // Loop through providers and get library/version pairs from any that are
32
+ // version components.
33
+ return providers
34
+ .map(provider => {
35
+ if (isVersionServiceProvider(provider)) {
36
+ const service = provider.getImmediate();
37
+ return `${service.library}/${service.version}`;
38
+ }
39
+ else {
40
+ return null;
41
+ }
42
+ })
43
+ .filter(logString => logString)
44
+ .join(' ');
45
+ }
46
+ }
47
+ /**
48
+ *
49
+ * @param provider check if this provider provides a VersionService
50
+ *
51
+ * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
52
+ * provides VersionService. The provider is not necessarily a 'app-version'
53
+ * provider.
54
+ */
55
+ function isVersionServiceProvider(provider) {
56
+ const component = provider.getComponent();
57
+ return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */;
58
58
  }
59
59
 
60
60
  const name$q = "@firebase/app";
61
- const version$1 = "0.10.15";
61
+ const version$1 = "0.10.16";
62
62
 
63
- /**
64
- * @license
65
- * Copyright 2019 Google LLC
66
- *
67
- * Licensed under the Apache License, Version 2.0 (the "License");
68
- * you may not use this file except in compliance with the License.
69
- * You may obtain a copy of the License at
70
- *
71
- * http://www.apache.org/licenses/LICENSE-2.0
72
- *
73
- * Unless required by applicable law or agreed to in writing, software
74
- * distributed under the License is distributed on an "AS IS" BASIS,
75
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
- * See the License for the specific language governing permissions and
77
- * limitations under the License.
78
- */
63
+ /**
64
+ * @license
65
+ * Copyright 2019 Google LLC
66
+ *
67
+ * Licensed under the Apache License, Version 2.0 (the "License");
68
+ * you may not use this file except in compliance with the License.
69
+ * You may obtain a copy of the License at
70
+ *
71
+ * http://www.apache.org/licenses/LICENSE-2.0
72
+ *
73
+ * Unless required by applicable law or agreed to in writing, software
74
+ * distributed under the License is distributed on an "AS IS" BASIS,
75
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
+ * See the License for the specific language governing permissions and
77
+ * limitations under the License.
78
+ */
79
79
  const logger = new Logger('@firebase/app');
80
80
 
81
81
  const name$p = "@firebase/app-compat";
@@ -129,1026 +129,1026 @@ const name$2 = "@firebase/vertexai";
129
129
  const name$1 = "@firebase/firestore-compat";
130
130
 
131
131
  const name = "firebase";
132
- const version = "11.0.1";
132
+ const version = "11.0.2";
133
133
 
134
- /**
135
- * @license
136
- * Copyright 2019 Google LLC
137
- *
138
- * Licensed under the Apache License, Version 2.0 (the "License");
139
- * you may not use this file except in compliance with the License.
140
- * You may obtain a copy of the License at
141
- *
142
- * http://www.apache.org/licenses/LICENSE-2.0
143
- *
144
- * Unless required by applicable law or agreed to in writing, software
145
- * distributed under the License is distributed on an "AS IS" BASIS,
146
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147
- * See the License for the specific language governing permissions and
148
- * limitations under the License.
149
- */
150
- /**
151
- * The default app name
152
- *
153
- * @internal
154
- */
155
- const DEFAULT_ENTRY_NAME = '[DEFAULT]';
156
- const PLATFORM_LOG_STRING = {
157
- [name$q]: 'fire-core',
158
- [name$p]: 'fire-core-compat',
159
- [name$n]: 'fire-analytics',
160
- [name$o]: 'fire-analytics-compat',
161
- [name$l]: 'fire-app-check',
162
- [name$m]: 'fire-app-check-compat',
163
- [name$k]: 'fire-auth',
164
- [name$j]: 'fire-auth-compat',
165
- [name$i]: 'fire-rtdb',
166
- [name$h]: 'fire-data-connect',
167
- [name$g]: 'fire-rtdb-compat',
168
- [name$f]: 'fire-fn',
169
- [name$e]: 'fire-fn-compat',
170
- [name$d]: 'fire-iid',
171
- [name$c]: 'fire-iid-compat',
172
- [name$b]: 'fire-fcm',
173
- [name$a]: 'fire-fcm-compat',
174
- [name$9]: 'fire-perf',
175
- [name$8]: 'fire-perf-compat',
176
- [name$7]: 'fire-rc',
177
- [name$6]: 'fire-rc-compat',
178
- [name$5]: 'fire-gcs',
179
- [name$4]: 'fire-gcs-compat',
180
- [name$3]: 'fire-fst',
181
- [name$1]: 'fire-fst-compat',
182
- [name$2]: 'fire-vertex',
183
- 'fire-js': 'fire-js',
184
- [name]: 'fire-js-all'
134
+ /**
135
+ * @license
136
+ * Copyright 2019 Google LLC
137
+ *
138
+ * Licensed under the Apache License, Version 2.0 (the "License");
139
+ * you may not use this file except in compliance with the License.
140
+ * You may obtain a copy of the License at
141
+ *
142
+ * http://www.apache.org/licenses/LICENSE-2.0
143
+ *
144
+ * Unless required by applicable law or agreed to in writing, software
145
+ * distributed under the License is distributed on an "AS IS" BASIS,
146
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147
+ * See the License for the specific language governing permissions and
148
+ * limitations under the License.
149
+ */
150
+ /**
151
+ * The default app name
152
+ *
153
+ * @internal
154
+ */
155
+ const DEFAULT_ENTRY_NAME = '[DEFAULT]';
156
+ const PLATFORM_LOG_STRING = {
157
+ [name$q]: 'fire-core',
158
+ [name$p]: 'fire-core-compat',
159
+ [name$n]: 'fire-analytics',
160
+ [name$o]: 'fire-analytics-compat',
161
+ [name$l]: 'fire-app-check',
162
+ [name$m]: 'fire-app-check-compat',
163
+ [name$k]: 'fire-auth',
164
+ [name$j]: 'fire-auth-compat',
165
+ [name$i]: 'fire-rtdb',
166
+ [name$h]: 'fire-data-connect',
167
+ [name$g]: 'fire-rtdb-compat',
168
+ [name$f]: 'fire-fn',
169
+ [name$e]: 'fire-fn-compat',
170
+ [name$d]: 'fire-iid',
171
+ [name$c]: 'fire-iid-compat',
172
+ [name$b]: 'fire-fcm',
173
+ [name$a]: 'fire-fcm-compat',
174
+ [name$9]: 'fire-perf',
175
+ [name$8]: 'fire-perf-compat',
176
+ [name$7]: 'fire-rc',
177
+ [name$6]: 'fire-rc-compat',
178
+ [name$5]: 'fire-gcs',
179
+ [name$4]: 'fire-gcs-compat',
180
+ [name$3]: 'fire-fst',
181
+ [name$1]: 'fire-fst-compat',
182
+ [name$2]: 'fire-vertex',
183
+ 'fire-js': 'fire-js', // Platform identifier for JS SDK.
184
+ [name]: 'fire-js-all'
185
185
  };
186
186
 
187
- /**
188
- * @license
189
- * Copyright 2019 Google LLC
190
- *
191
- * Licensed under the Apache License, Version 2.0 (the "License");
192
- * you may not use this file except in compliance with the License.
193
- * You may obtain a copy of the License at
194
- *
195
- * http://www.apache.org/licenses/LICENSE-2.0
196
- *
197
- * Unless required by applicable law or agreed to in writing, software
198
- * distributed under the License is distributed on an "AS IS" BASIS,
199
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- * See the License for the specific language governing permissions and
201
- * limitations under the License.
202
- */
203
- /**
204
- * @internal
205
- */
206
- const _apps = new Map();
207
- /**
208
- * @internal
209
- */
210
- const _serverApps = new Map();
211
- /**
212
- * Registered components.
213
- *
214
- * @internal
215
- */
216
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
- const _components = new Map();
218
- /**
219
- * @param component - the component being added to this app's container
220
- *
221
- * @internal
222
- */
223
- function _addComponent(app, component) {
224
- try {
225
- app.container.addComponent(component);
226
- }
227
- catch (e) {
228
- logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
229
- }
230
- }
231
- /**
232
- *
233
- * @internal
234
- */
235
- function _addOrOverwriteComponent(app, component) {
236
- app.container.addOrOverwriteComponent(component);
237
- }
238
- /**
239
- *
240
- * @param component - the component to register
241
- * @returns whether or not the component is registered successfully
242
- *
243
- * @internal
244
- */
245
- function _registerComponent(component) {
246
- const componentName = component.name;
247
- if (_components.has(componentName)) {
248
- logger.debug(`There were multiple attempts to register component ${componentName}.`);
249
- return false;
250
- }
251
- _components.set(componentName, component);
252
- // add the component to existing app instances
253
- for (const app of _apps.values()) {
254
- _addComponent(app, component);
255
- }
256
- for (const serverApp of _serverApps.values()) {
257
- _addComponent(serverApp, component);
258
- }
259
- return true;
260
- }
261
- /**
262
- *
263
- * @param app - FirebaseApp instance
264
- * @param name - service name
265
- *
266
- * @returns the provider for the service with the matching name
267
- *
268
- * @internal
269
- */
270
- function _getProvider(app, name) {
271
- const heartbeatController = app.container
272
- .getProvider('heartbeat')
273
- .getImmediate({ optional: true });
274
- if (heartbeatController) {
275
- void heartbeatController.triggerHeartbeat();
276
- }
277
- return app.container.getProvider(name);
278
- }
279
- /**
280
- *
281
- * @param app - FirebaseApp instance
282
- * @param name - service name
283
- * @param instanceIdentifier - service instance identifier in case the service supports multiple instances
284
- *
285
- * @internal
286
- */
287
- function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {
288
- _getProvider(app, name).clearInstance(instanceIdentifier);
289
- }
290
- /**
291
- *
292
- * @param obj - an object of type FirebaseApp or FirebaseOptions.
293
- *
294
- * @returns true if the provide object is of type FirebaseApp.
295
- *
296
- * @internal
297
- */
298
- function _isFirebaseApp(obj) {
299
- return obj.options !== undefined;
300
- }
301
- /**
302
- *
303
- * @param obj - an object of type FirebaseApp.
304
- *
305
- * @returns true if the provided object is of type FirebaseServerAppImpl.
306
- *
307
- * @internal
308
- */
309
- function _isFirebaseServerApp(obj) {
310
- return obj.settings !== undefined;
311
- }
312
- /**
313
- * Test only
314
- *
315
- * @internal
316
- */
317
- function _clearComponents() {
318
- _components.clear();
187
+ /**
188
+ * @license
189
+ * Copyright 2019 Google LLC
190
+ *
191
+ * Licensed under the Apache License, Version 2.0 (the "License");
192
+ * you may not use this file except in compliance with the License.
193
+ * You may obtain a copy of the License at
194
+ *
195
+ * http://www.apache.org/licenses/LICENSE-2.0
196
+ *
197
+ * Unless required by applicable law or agreed to in writing, software
198
+ * distributed under the License is distributed on an "AS IS" BASIS,
199
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ * See the License for the specific language governing permissions and
201
+ * limitations under the License.
202
+ */
203
+ /**
204
+ * @internal
205
+ */
206
+ const _apps = new Map();
207
+ /**
208
+ * @internal
209
+ */
210
+ const _serverApps = new Map();
211
+ /**
212
+ * Registered components.
213
+ *
214
+ * @internal
215
+ */
216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
+ const _components = new Map();
218
+ /**
219
+ * @param component - the component being added to this app's container
220
+ *
221
+ * @internal
222
+ */
223
+ function _addComponent(app, component) {
224
+ try {
225
+ app.container.addComponent(component);
226
+ }
227
+ catch (e) {
228
+ logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
229
+ }
230
+ }
231
+ /**
232
+ *
233
+ * @internal
234
+ */
235
+ function _addOrOverwriteComponent(app, component) {
236
+ app.container.addOrOverwriteComponent(component);
237
+ }
238
+ /**
239
+ *
240
+ * @param component - the component to register
241
+ * @returns whether or not the component is registered successfully
242
+ *
243
+ * @internal
244
+ */
245
+ function _registerComponent(component) {
246
+ const componentName = component.name;
247
+ if (_components.has(componentName)) {
248
+ logger.debug(`There were multiple attempts to register component ${componentName}.`);
249
+ return false;
250
+ }
251
+ _components.set(componentName, component);
252
+ // add the component to existing app instances
253
+ for (const app of _apps.values()) {
254
+ _addComponent(app, component);
255
+ }
256
+ for (const serverApp of _serverApps.values()) {
257
+ _addComponent(serverApp, component);
258
+ }
259
+ return true;
260
+ }
261
+ /**
262
+ *
263
+ * @param app - FirebaseApp instance
264
+ * @param name - service name
265
+ *
266
+ * @returns the provider for the service with the matching name
267
+ *
268
+ * @internal
269
+ */
270
+ function _getProvider(app, name) {
271
+ const heartbeatController = app.container
272
+ .getProvider('heartbeat')
273
+ .getImmediate({ optional: true });
274
+ if (heartbeatController) {
275
+ void heartbeatController.triggerHeartbeat();
276
+ }
277
+ return app.container.getProvider(name);
278
+ }
279
+ /**
280
+ *
281
+ * @param app - FirebaseApp instance
282
+ * @param name - service name
283
+ * @param instanceIdentifier - service instance identifier in case the service supports multiple instances
284
+ *
285
+ * @internal
286
+ */
287
+ function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {
288
+ _getProvider(app, name).clearInstance(instanceIdentifier);
289
+ }
290
+ /**
291
+ *
292
+ * @param obj - an object of type FirebaseApp or FirebaseOptions.
293
+ *
294
+ * @returns true if the provide object is of type FirebaseApp.
295
+ *
296
+ * @internal
297
+ */
298
+ function _isFirebaseApp(obj) {
299
+ return obj.options !== undefined;
300
+ }
301
+ /**
302
+ *
303
+ * @param obj - an object of type FirebaseApp.
304
+ *
305
+ * @returns true if the provided object is of type FirebaseServerAppImpl.
306
+ *
307
+ * @internal
308
+ */
309
+ function _isFirebaseServerApp(obj) {
310
+ return obj.settings !== undefined;
311
+ }
312
+ /**
313
+ * Test only
314
+ *
315
+ * @internal
316
+ */
317
+ function _clearComponents() {
318
+ _components.clear();
319
319
  }
320
320
 
321
- /**
322
- * @license
323
- * Copyright 2019 Google LLC
324
- *
325
- * Licensed under the Apache License, Version 2.0 (the "License");
326
- * you may not use this file except in compliance with the License.
327
- * You may obtain a copy of the License at
328
- *
329
- * http://www.apache.org/licenses/LICENSE-2.0
330
- *
331
- * Unless required by applicable law or agreed to in writing, software
332
- * distributed under the License is distributed on an "AS IS" BASIS,
333
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
334
- * See the License for the specific language governing permissions and
335
- * limitations under the License.
336
- */
337
- const ERRORS = {
338
- ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " +
339
- 'call initializeApp() first',
340
- ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'",
341
- ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config",
342
- ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted",
343
- ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',
344
- ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',
345
- ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +
346
- 'Firebase App instance.',
347
- ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',
348
- ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
349
- ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
350
- ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
351
- ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
352
- ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',
353
- ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'
354
- };
321
+ /**
322
+ * @license
323
+ * Copyright 2019 Google LLC
324
+ *
325
+ * Licensed under the Apache License, Version 2.0 (the "License");
326
+ * you may not use this file except in compliance with the License.
327
+ * You may obtain a copy of the License at
328
+ *
329
+ * http://www.apache.org/licenses/LICENSE-2.0
330
+ *
331
+ * Unless required by applicable law or agreed to in writing, software
332
+ * distributed under the License is distributed on an "AS IS" BASIS,
333
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
334
+ * See the License for the specific language governing permissions and
335
+ * limitations under the License.
336
+ */
337
+ const ERRORS = {
338
+ ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " +
339
+ 'call initializeApp() first',
340
+ ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'",
341
+ ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config",
342
+ ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted",
343
+ ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',
344
+ ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',
345
+ ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +
346
+ 'Firebase App instance.',
347
+ ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',
348
+ ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
349
+ ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
350
+ ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
351
+ ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
352
+ ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',
353
+ ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'
354
+ };
355
355
  const ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);
356
356
 
357
- /**
358
- * @license
359
- * Copyright 2019 Google LLC
360
- *
361
- * Licensed under the Apache License, Version 2.0 (the "License");
362
- * you may not use this file except in compliance with the License.
363
- * You may obtain a copy of the License at
364
- *
365
- * http://www.apache.org/licenses/LICENSE-2.0
366
- *
367
- * Unless required by applicable law or agreed to in writing, software
368
- * distributed under the License is distributed on an "AS IS" BASIS,
369
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
370
- * See the License for the specific language governing permissions and
371
- * limitations under the License.
372
- */
373
- class FirebaseAppImpl {
374
- constructor(options, config, container) {
375
- this._isDeleted = false;
376
- this._options = Object.assign({}, options);
377
- this._config = Object.assign({}, config);
378
- this._name = config.name;
379
- this._automaticDataCollectionEnabled =
380
- config.automaticDataCollectionEnabled;
381
- this._container = container;
382
- this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */));
383
- }
384
- get automaticDataCollectionEnabled() {
385
- this.checkDestroyed();
386
- return this._automaticDataCollectionEnabled;
387
- }
388
- set automaticDataCollectionEnabled(val) {
389
- this.checkDestroyed();
390
- this._automaticDataCollectionEnabled = val;
391
- }
392
- get name() {
393
- this.checkDestroyed();
394
- return this._name;
395
- }
396
- get options() {
397
- this.checkDestroyed();
398
- return this._options;
399
- }
400
- get config() {
401
- this.checkDestroyed();
402
- return this._config;
403
- }
404
- get container() {
405
- return this._container;
406
- }
407
- get isDeleted() {
408
- return this._isDeleted;
409
- }
410
- set isDeleted(val) {
411
- this._isDeleted = val;
412
- }
413
- /**
414
- * This function will throw an Error if the App has already been deleted -
415
- * use before performing API actions on the App.
416
- */
417
- checkDestroyed() {
418
- if (this.isDeleted) {
419
- throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
420
- }
421
- }
357
+ /**
358
+ * @license
359
+ * Copyright 2019 Google LLC
360
+ *
361
+ * Licensed under the Apache License, Version 2.0 (the "License");
362
+ * you may not use this file except in compliance with the License.
363
+ * You may obtain a copy of the License at
364
+ *
365
+ * http://www.apache.org/licenses/LICENSE-2.0
366
+ *
367
+ * Unless required by applicable law or agreed to in writing, software
368
+ * distributed under the License is distributed on an "AS IS" BASIS,
369
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
370
+ * See the License for the specific language governing permissions and
371
+ * limitations under the License.
372
+ */
373
+ class FirebaseAppImpl {
374
+ constructor(options, config, container) {
375
+ this._isDeleted = false;
376
+ this._options = Object.assign({}, options);
377
+ this._config = Object.assign({}, config);
378
+ this._name = config.name;
379
+ this._automaticDataCollectionEnabled =
380
+ config.automaticDataCollectionEnabled;
381
+ this._container = container;
382
+ this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */));
383
+ }
384
+ get automaticDataCollectionEnabled() {
385
+ this.checkDestroyed();
386
+ return this._automaticDataCollectionEnabled;
387
+ }
388
+ set automaticDataCollectionEnabled(val) {
389
+ this.checkDestroyed();
390
+ this._automaticDataCollectionEnabled = val;
391
+ }
392
+ get name() {
393
+ this.checkDestroyed();
394
+ return this._name;
395
+ }
396
+ get options() {
397
+ this.checkDestroyed();
398
+ return this._options;
399
+ }
400
+ get config() {
401
+ this.checkDestroyed();
402
+ return this._config;
403
+ }
404
+ get container() {
405
+ return this._container;
406
+ }
407
+ get isDeleted() {
408
+ return this._isDeleted;
409
+ }
410
+ set isDeleted(val) {
411
+ this._isDeleted = val;
412
+ }
413
+ /**
414
+ * This function will throw an Error if the App has already been deleted -
415
+ * use before performing API actions on the App.
416
+ */
417
+ checkDestroyed() {
418
+ if (this.isDeleted) {
419
+ throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
420
+ }
421
+ }
422
422
  }
423
423
 
424
- /**
425
- * @license
426
- * Copyright 2023 Google LLC
427
- *
428
- * Licensed under the Apache License, Version 2.0 (the "License");
429
- * you may not use this file except in compliance with the License.
430
- * You may obtain a copy of the License at
431
- *
432
- * http://www.apache.org/licenses/LICENSE-2.0
433
- *
434
- * Unless required by applicable law or agreed to in writing, software
435
- * distributed under the License is distributed on an "AS IS" BASIS,
436
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
437
- * See the License for the specific language governing permissions and
438
- * limitations under the License.
439
- */
440
- class FirebaseServerAppImpl extends FirebaseAppImpl {
441
- constructor(options, serverConfig, name, container) {
442
- // Build configuration parameters for the FirebaseAppImpl base class.
443
- const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined
444
- ? serverConfig.automaticDataCollectionEnabled
445
- : false;
446
- // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.
447
- const config = {
448
- name,
449
- automaticDataCollectionEnabled
450
- };
451
- if (options.apiKey !== undefined) {
452
- // Construct the parent FirebaseAppImp object.
453
- super(options, config, container);
454
- }
455
- else {
456
- const appImpl = options;
457
- super(appImpl.options, config, container);
458
- }
459
- // Now construct the data for the FirebaseServerAppImpl.
460
- this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);
461
- this._finalizationRegistry = null;
462
- if (typeof FinalizationRegistry !== 'undefined') {
463
- this._finalizationRegistry = new FinalizationRegistry(() => {
464
- this.automaticCleanup();
465
- });
466
- }
467
- this._refCount = 0;
468
- this.incRefCount(this._serverConfig.releaseOnDeref);
469
- // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry
470
- // will never trigger.
471
- this._serverConfig.releaseOnDeref = undefined;
472
- serverConfig.releaseOnDeref = undefined;
473
- registerVersion(name$q, version$1, 'serverapp');
474
- }
475
- toJSON() {
476
- return undefined;
477
- }
478
- get refCount() {
479
- return this._refCount;
480
- }
481
- // Increment the reference count of this server app. If an object is provided, register it
482
- // with the finalization registry.
483
- incRefCount(obj) {
484
- if (this.isDeleted) {
485
- return;
486
- }
487
- this._refCount++;
488
- if (obj !== undefined && this._finalizationRegistry !== null) {
489
- this._finalizationRegistry.register(obj, this);
490
- }
491
- }
492
- // Decrement the reference count.
493
- decRefCount() {
494
- if (this.isDeleted) {
495
- return 0;
496
- }
497
- return --this._refCount;
498
- }
499
- // Invoked by the FinalizationRegistry callback to note that this app should go through its
500
- // reference counts and delete itself if no reference count remain. The coordinating logic that
501
- // handles this is in deleteApp(...).
502
- automaticCleanup() {
503
- void deleteApp(this);
504
- }
505
- get settings() {
506
- this.checkDestroyed();
507
- return this._serverConfig;
508
- }
509
- /**
510
- * This function will throw an Error if the App has already been deleted -
511
- * use before performing API actions on the App.
512
- */
513
- checkDestroyed() {
514
- if (this.isDeleted) {
515
- throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */);
516
- }
517
- }
424
+ /**
425
+ * @license
426
+ * Copyright 2023 Google LLC
427
+ *
428
+ * Licensed under the Apache License, Version 2.0 (the "License");
429
+ * you may not use this file except in compliance with the License.
430
+ * You may obtain a copy of the License at
431
+ *
432
+ * http://www.apache.org/licenses/LICENSE-2.0
433
+ *
434
+ * Unless required by applicable law or agreed to in writing, software
435
+ * distributed under the License is distributed on an "AS IS" BASIS,
436
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
437
+ * See the License for the specific language governing permissions and
438
+ * limitations under the License.
439
+ */
440
+ class FirebaseServerAppImpl extends FirebaseAppImpl {
441
+ constructor(options, serverConfig, name, container) {
442
+ // Build configuration parameters for the FirebaseAppImpl base class.
443
+ const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined
444
+ ? serverConfig.automaticDataCollectionEnabled
445
+ : false;
446
+ // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.
447
+ const config = {
448
+ name,
449
+ automaticDataCollectionEnabled
450
+ };
451
+ if (options.apiKey !== undefined) {
452
+ // Construct the parent FirebaseAppImp object.
453
+ super(options, config, container);
454
+ }
455
+ else {
456
+ const appImpl = options;
457
+ super(appImpl.options, config, container);
458
+ }
459
+ // Now construct the data for the FirebaseServerAppImpl.
460
+ this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);
461
+ this._finalizationRegistry = null;
462
+ if (typeof FinalizationRegistry !== 'undefined') {
463
+ this._finalizationRegistry = new FinalizationRegistry(() => {
464
+ this.automaticCleanup();
465
+ });
466
+ }
467
+ this._refCount = 0;
468
+ this.incRefCount(this._serverConfig.releaseOnDeref);
469
+ // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry
470
+ // will never trigger.
471
+ this._serverConfig.releaseOnDeref = undefined;
472
+ serverConfig.releaseOnDeref = undefined;
473
+ registerVersion(name$q, version$1, 'serverapp');
474
+ }
475
+ toJSON() {
476
+ return undefined;
477
+ }
478
+ get refCount() {
479
+ return this._refCount;
480
+ }
481
+ // Increment the reference count of this server app. If an object is provided, register it
482
+ // with the finalization registry.
483
+ incRefCount(obj) {
484
+ if (this.isDeleted) {
485
+ return;
486
+ }
487
+ this._refCount++;
488
+ if (obj !== undefined && this._finalizationRegistry !== null) {
489
+ this._finalizationRegistry.register(obj, this);
490
+ }
491
+ }
492
+ // Decrement the reference count.
493
+ decRefCount() {
494
+ if (this.isDeleted) {
495
+ return 0;
496
+ }
497
+ return --this._refCount;
498
+ }
499
+ // Invoked by the FinalizationRegistry callback to note that this app should go through its
500
+ // reference counts and delete itself if no reference count remain. The coordinating logic that
501
+ // handles this is in deleteApp(...).
502
+ automaticCleanup() {
503
+ void deleteApp(this);
504
+ }
505
+ get settings() {
506
+ this.checkDestroyed();
507
+ return this._serverConfig;
508
+ }
509
+ /**
510
+ * This function will throw an Error if the App has already been deleted -
511
+ * use before performing API actions on the App.
512
+ */
513
+ checkDestroyed() {
514
+ if (this.isDeleted) {
515
+ throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */);
516
+ }
517
+ }
518
518
  }
519
519
 
520
- /**
521
- * @license
522
- * Copyright 2019 Google LLC
523
- *
524
- * Licensed under the Apache License, Version 2.0 (the "License");
525
- * you may not use this file except in compliance with the License.
526
- * You may obtain a copy of the License at
527
- *
528
- * http://www.apache.org/licenses/LICENSE-2.0
529
- *
530
- * Unless required by applicable law or agreed to in writing, software
531
- * distributed under the License is distributed on an "AS IS" BASIS,
532
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
533
- * See the License for the specific language governing permissions and
534
- * limitations under the License.
535
- */
536
- /**
537
- * The current SDK version.
538
- *
539
- * @public
540
- */
541
- const SDK_VERSION = version;
542
- function initializeApp(_options, rawConfig = {}) {
543
- let options = _options;
544
- if (typeof rawConfig !== 'object') {
545
- const name = rawConfig;
546
- rawConfig = { name };
547
- }
548
- const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
549
- const name = config.name;
550
- if (typeof name !== 'string' || !name) {
551
- throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
552
- appName: String(name)
553
- });
554
- }
555
- options || (options = getDefaultAppConfig());
556
- if (!options) {
557
- throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */);
558
- }
559
- const existingApp = _apps.get(name);
560
- if (existingApp) {
561
- // return the existing app if options and config deep equal the ones in the existing app.
562
- if (deepEqual(options, existingApp.options) &&
563
- deepEqual(config, existingApp.config)) {
564
- return existingApp;
565
- }
566
- else {
567
- throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
568
- }
569
- }
570
- const container = new ComponentContainer(name);
571
- for (const component of _components.values()) {
572
- container.addComponent(component);
573
- }
574
- const newApp = new FirebaseAppImpl(options, config, container);
575
- _apps.set(name, newApp);
576
- return newApp;
577
- }
578
- function initializeServerApp(_options, _serverAppConfig) {
579
- if (isBrowser() && !isWebWorker()) {
580
- // FirebaseServerApp isn't designed to be run in browsers.
581
- throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);
582
- }
583
- if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {
584
- _serverAppConfig.automaticDataCollectionEnabled = false;
585
- }
586
- let appOptions;
587
- if (_isFirebaseApp(_options)) {
588
- appOptions = _options.options;
589
- }
590
- else {
591
- appOptions = _options;
592
- }
593
- // Build an app name based on a hash of the configuration options.
594
- const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);
595
- // However, Do not mangle the name based on releaseOnDeref, since it will vary between the
596
- // construction of FirebaseServerApp instances. For example, if the object is the request headers.
597
- if (nameObj.releaseOnDeref !== undefined) {
598
- delete nameObj.releaseOnDeref;
599
- }
600
- const hashCode = (s) => {
601
- return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);
602
- };
603
- if (_serverAppConfig.releaseOnDeref !== undefined) {
604
- if (typeof FinalizationRegistry === 'undefined') {
605
- throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});
606
- }
607
- }
608
- const nameString = '' + hashCode(JSON.stringify(nameObj));
609
- const existingApp = _serverApps.get(nameString);
610
- if (existingApp) {
611
- existingApp.incRefCount(_serverAppConfig.releaseOnDeref);
612
- return existingApp;
613
- }
614
- const container = new ComponentContainer(nameString);
615
- for (const component of _components.values()) {
616
- container.addComponent(component);
617
- }
618
- const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);
619
- _serverApps.set(nameString, newApp);
620
- return newApp;
621
- }
622
- /**
623
- * Retrieves a {@link @firebase/app#FirebaseApp} instance.
624
- *
625
- * When called with no arguments, the default app is returned. When an app name
626
- * is provided, the app corresponding to that name is returned.
627
- *
628
- * An exception is thrown if the app being retrieved has not yet been
629
- * initialized.
630
- *
631
- * @example
632
- * ```javascript
633
- * // Return the default app
634
- * const app = getApp();
635
- * ```
636
- *
637
- * @example
638
- * ```javascript
639
- * // Return a named app
640
- * const otherApp = getApp("otherApp");
641
- * ```
642
- *
643
- * @param name - Optional name of the app to return. If no name is
644
- * provided, the default is `"[DEFAULT]"`.
645
- *
646
- * @returns The app corresponding to the provided app name.
647
- * If no app name is provided, the default app is returned.
648
- *
649
- * @public
650
- */
651
- function getApp(name = DEFAULT_ENTRY_NAME) {
652
- const app = _apps.get(name);
653
- if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
654
- return initializeApp();
655
- }
656
- if (!app) {
657
- throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name });
658
- }
659
- return app;
660
- }
661
- /**
662
- * A (read-only) array of all initialized apps.
663
- * @public
664
- */
665
- function getApps() {
666
- return Array.from(_apps.values());
667
- }
668
- /**
669
- * Renders this app unusable and frees the resources of all associated
670
- * services.
671
- *
672
- * @example
673
- * ```javascript
674
- * deleteApp(app)
675
- * .then(function() {
676
- * console.log("App deleted successfully");
677
- * })
678
- * .catch(function(error) {
679
- * console.log("Error deleting app:", error);
680
- * });
681
- * ```
682
- *
683
- * @public
684
- */
685
- async function deleteApp(app) {
686
- let cleanupProviders = false;
687
- const name = app.name;
688
- if (_apps.has(name)) {
689
- cleanupProviders = true;
690
- _apps.delete(name);
691
- }
692
- else if (_serverApps.has(name)) {
693
- const firebaseServerApp = app;
694
- if (firebaseServerApp.decRefCount() <= 0) {
695
- _serverApps.delete(name);
696
- cleanupProviders = true;
697
- }
698
- }
699
- if (cleanupProviders) {
700
- await Promise.all(app.container
701
- .getProviders()
702
- .map(provider => provider.delete()));
703
- app.isDeleted = true;
704
- }
705
- }
706
- /**
707
- * Registers a library's name and version for platform logging purposes.
708
- * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
709
- * @param version - Current version of that library.
710
- * @param variant - Bundle variant, e.g., node, rn, etc.
711
- *
712
- * @public
713
- */
714
- function registerVersion(libraryKeyOrName, version, variant) {
715
- var _a;
716
- // TODO: We can use this check to whitelist strings when/if we set up
717
- // a good whitelist system.
718
- let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;
719
- if (variant) {
720
- library += `-${variant}`;
721
- }
722
- const libraryMismatch = library.match(/\s|\//);
723
- const versionMismatch = version.match(/\s|\//);
724
- if (libraryMismatch || versionMismatch) {
725
- const warning = [
726
- `Unable to register library "${library}" with version "${version}":`
727
- ];
728
- if (libraryMismatch) {
729
- warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
730
- }
731
- if (libraryMismatch && versionMismatch) {
732
- warning.push('and');
733
- }
734
- if (versionMismatch) {
735
- warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`);
736
- }
737
- logger.warn(warning.join(' '));
738
- return;
739
- }
740
- _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */));
741
- }
742
- /**
743
- * Sets log handler for all Firebase SDKs.
744
- * @param logCallback - An optional custom log handler that executes user code whenever
745
- * the Firebase SDK makes a logging call.
746
- *
747
- * @public
748
- */
749
- function onLog(logCallback, options) {
750
- if (logCallback !== null && typeof logCallback !== 'function') {
751
- throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */);
752
- }
753
- setUserLogHandler(logCallback, options);
754
- }
755
- /**
756
- * Sets log level for all Firebase SDKs.
757
- *
758
- * All of the log types above the current log level are captured (i.e. if
759
- * you set the log level to `info`, errors are logged, but `debug` and
760
- * `verbose` logs are not).
761
- *
762
- * @public
763
- */
764
- function setLogLevel(logLevel) {
765
- setLogLevel$1(logLevel);
520
+ /**
521
+ * @license
522
+ * Copyright 2019 Google LLC
523
+ *
524
+ * Licensed under the Apache License, Version 2.0 (the "License");
525
+ * you may not use this file except in compliance with the License.
526
+ * You may obtain a copy of the License at
527
+ *
528
+ * http://www.apache.org/licenses/LICENSE-2.0
529
+ *
530
+ * Unless required by applicable law or agreed to in writing, software
531
+ * distributed under the License is distributed on an "AS IS" BASIS,
532
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
533
+ * See the License for the specific language governing permissions and
534
+ * limitations under the License.
535
+ */
536
+ /**
537
+ * The current SDK version.
538
+ *
539
+ * @public
540
+ */
541
+ const SDK_VERSION = version;
542
+ function initializeApp(_options, rawConfig = {}) {
543
+ let options = _options;
544
+ if (typeof rawConfig !== 'object') {
545
+ const name = rawConfig;
546
+ rawConfig = { name };
547
+ }
548
+ const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
549
+ const name = config.name;
550
+ if (typeof name !== 'string' || !name) {
551
+ throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
552
+ appName: String(name)
553
+ });
554
+ }
555
+ options || (options = getDefaultAppConfig());
556
+ if (!options) {
557
+ throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */);
558
+ }
559
+ const existingApp = _apps.get(name);
560
+ if (existingApp) {
561
+ // return the existing app if options and config deep equal the ones in the existing app.
562
+ if (deepEqual(options, existingApp.options) &&
563
+ deepEqual(config, existingApp.config)) {
564
+ return existingApp;
565
+ }
566
+ else {
567
+ throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
568
+ }
569
+ }
570
+ const container = new ComponentContainer(name);
571
+ for (const component of _components.values()) {
572
+ container.addComponent(component);
573
+ }
574
+ const newApp = new FirebaseAppImpl(options, config, container);
575
+ _apps.set(name, newApp);
576
+ return newApp;
577
+ }
578
+ function initializeServerApp(_options, _serverAppConfig) {
579
+ if (isBrowser() && !isWebWorker()) {
580
+ // FirebaseServerApp isn't designed to be run in browsers.
581
+ throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);
582
+ }
583
+ if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {
584
+ _serverAppConfig.automaticDataCollectionEnabled = false;
585
+ }
586
+ let appOptions;
587
+ if (_isFirebaseApp(_options)) {
588
+ appOptions = _options.options;
589
+ }
590
+ else {
591
+ appOptions = _options;
592
+ }
593
+ // Build an app name based on a hash of the configuration options.
594
+ const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);
595
+ // However, Do not mangle the name based on releaseOnDeref, since it will vary between the
596
+ // construction of FirebaseServerApp instances. For example, if the object is the request headers.
597
+ if (nameObj.releaseOnDeref !== undefined) {
598
+ delete nameObj.releaseOnDeref;
599
+ }
600
+ const hashCode = (s) => {
601
+ return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);
602
+ };
603
+ if (_serverAppConfig.releaseOnDeref !== undefined) {
604
+ if (typeof FinalizationRegistry === 'undefined') {
605
+ throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});
606
+ }
607
+ }
608
+ const nameString = '' + hashCode(JSON.stringify(nameObj));
609
+ const existingApp = _serverApps.get(nameString);
610
+ if (existingApp) {
611
+ existingApp.incRefCount(_serverAppConfig.releaseOnDeref);
612
+ return existingApp;
613
+ }
614
+ const container = new ComponentContainer(nameString);
615
+ for (const component of _components.values()) {
616
+ container.addComponent(component);
617
+ }
618
+ const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);
619
+ _serverApps.set(nameString, newApp);
620
+ return newApp;
621
+ }
622
+ /**
623
+ * Retrieves a {@link @firebase/app#FirebaseApp} instance.
624
+ *
625
+ * When called with no arguments, the default app is returned. When an app name
626
+ * is provided, the app corresponding to that name is returned.
627
+ *
628
+ * An exception is thrown if the app being retrieved has not yet been
629
+ * initialized.
630
+ *
631
+ * @example
632
+ * ```javascript
633
+ * // Return the default app
634
+ * const app = getApp();
635
+ * ```
636
+ *
637
+ * @example
638
+ * ```javascript
639
+ * // Return a named app
640
+ * const otherApp = getApp("otherApp");
641
+ * ```
642
+ *
643
+ * @param name - Optional name of the app to return. If no name is
644
+ * provided, the default is `"[DEFAULT]"`.
645
+ *
646
+ * @returns The app corresponding to the provided app name.
647
+ * If no app name is provided, the default app is returned.
648
+ *
649
+ * @public
650
+ */
651
+ function getApp(name = DEFAULT_ENTRY_NAME) {
652
+ const app = _apps.get(name);
653
+ if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
654
+ return initializeApp();
655
+ }
656
+ if (!app) {
657
+ throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name });
658
+ }
659
+ return app;
660
+ }
661
+ /**
662
+ * A (read-only) array of all initialized apps.
663
+ * @public
664
+ */
665
+ function getApps() {
666
+ return Array.from(_apps.values());
667
+ }
668
+ /**
669
+ * Renders this app unusable and frees the resources of all associated
670
+ * services.
671
+ *
672
+ * @example
673
+ * ```javascript
674
+ * deleteApp(app)
675
+ * .then(function() {
676
+ * console.log("App deleted successfully");
677
+ * })
678
+ * .catch(function(error) {
679
+ * console.log("Error deleting app:", error);
680
+ * });
681
+ * ```
682
+ *
683
+ * @public
684
+ */
685
+ async function deleteApp(app) {
686
+ let cleanupProviders = false;
687
+ const name = app.name;
688
+ if (_apps.has(name)) {
689
+ cleanupProviders = true;
690
+ _apps.delete(name);
691
+ }
692
+ else if (_serverApps.has(name)) {
693
+ const firebaseServerApp = app;
694
+ if (firebaseServerApp.decRefCount() <= 0) {
695
+ _serverApps.delete(name);
696
+ cleanupProviders = true;
697
+ }
698
+ }
699
+ if (cleanupProviders) {
700
+ await Promise.all(app.container
701
+ .getProviders()
702
+ .map(provider => provider.delete()));
703
+ app.isDeleted = true;
704
+ }
705
+ }
706
+ /**
707
+ * Registers a library's name and version for platform logging purposes.
708
+ * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
709
+ * @param version - Current version of that library.
710
+ * @param variant - Bundle variant, e.g., node, rn, etc.
711
+ *
712
+ * @public
713
+ */
714
+ function registerVersion(libraryKeyOrName, version, variant) {
715
+ var _a;
716
+ // TODO: We can use this check to whitelist strings when/if we set up
717
+ // a good whitelist system.
718
+ let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;
719
+ if (variant) {
720
+ library += `-${variant}`;
721
+ }
722
+ const libraryMismatch = library.match(/\s|\//);
723
+ const versionMismatch = version.match(/\s|\//);
724
+ if (libraryMismatch || versionMismatch) {
725
+ const warning = [
726
+ `Unable to register library "${library}" with version "${version}":`
727
+ ];
728
+ if (libraryMismatch) {
729
+ warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
730
+ }
731
+ if (libraryMismatch && versionMismatch) {
732
+ warning.push('and');
733
+ }
734
+ if (versionMismatch) {
735
+ warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`);
736
+ }
737
+ logger.warn(warning.join(' '));
738
+ return;
739
+ }
740
+ _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */));
741
+ }
742
+ /**
743
+ * Sets log handler for all Firebase SDKs.
744
+ * @param logCallback - An optional custom log handler that executes user code whenever
745
+ * the Firebase SDK makes a logging call.
746
+ *
747
+ * @public
748
+ */
749
+ function onLog(logCallback, options) {
750
+ if (logCallback !== null && typeof logCallback !== 'function') {
751
+ throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */);
752
+ }
753
+ setUserLogHandler(logCallback, options);
754
+ }
755
+ /**
756
+ * Sets log level for all Firebase SDKs.
757
+ *
758
+ * All of the log types above the current log level are captured (i.e. if
759
+ * you set the log level to `info`, errors are logged, but `debug` and
760
+ * `verbose` logs are not).
761
+ *
762
+ * @public
763
+ */
764
+ function setLogLevel(logLevel) {
765
+ setLogLevel$1(logLevel);
766
766
  }
767
767
 
768
- /**
769
- * @license
770
- * Copyright 2021 Google LLC
771
- *
772
- * Licensed under the Apache License, Version 2.0 (the "License");
773
- * you may not use this file except in compliance with the License.
774
- * You may obtain a copy of the License at
775
- *
776
- * http://www.apache.org/licenses/LICENSE-2.0
777
- *
778
- * Unless required by applicable law or agreed to in writing, software
779
- * distributed under the License is distributed on an "AS IS" BASIS,
780
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
781
- * See the License for the specific language governing permissions and
782
- * limitations under the License.
783
- */
784
- const DB_NAME = 'firebase-heartbeat-database';
785
- const DB_VERSION = 1;
786
- const STORE_NAME = 'firebase-heartbeat-store';
787
- let dbPromise = null;
788
- function getDbPromise() {
789
- if (!dbPromise) {
790
- dbPromise = openDB(DB_NAME, DB_VERSION, {
791
- upgrade: (db, oldVersion) => {
792
- // We don't use 'break' in this switch statement, the fall-through
793
- // behavior is what we want, because if there are multiple versions between
794
- // the old version and the current version, we want ALL the migrations
795
- // that correspond to those versions to run, not only the last one.
796
- // eslint-disable-next-line default-case
797
- switch (oldVersion) {
798
- case 0:
799
- try {
800
- db.createObjectStore(STORE_NAME);
801
- }
802
- catch (e) {
803
- // Safari/iOS browsers throw occasional exceptions on
804
- // db.createObjectStore() that may be a bug. Avoid blocking
805
- // the rest of the app functionality.
806
- console.warn(e);
807
- }
808
- }
809
- }
810
- }).catch(e => {
811
- throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, {
812
- originalErrorMessage: e.message
813
- });
814
- });
815
- }
816
- return dbPromise;
817
- }
818
- async function readHeartbeatsFromIndexedDB(app) {
819
- try {
820
- const db = await getDbPromise();
821
- const tx = db.transaction(STORE_NAME);
822
- const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
823
- // We already have the value but tx.done can throw,
824
- // so we need to await it here to catch errors
825
- await tx.done;
826
- return result;
827
- }
828
- catch (e) {
829
- if (e instanceof FirebaseError) {
830
- logger.warn(e.message);
831
- }
832
- else {
833
- const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, {
834
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
835
- });
836
- logger.warn(idbGetError.message);
837
- }
838
- }
839
- }
840
- async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
841
- try {
842
- const db = await getDbPromise();
843
- const tx = db.transaction(STORE_NAME, 'readwrite');
844
- const objectStore = tx.objectStore(STORE_NAME);
845
- await objectStore.put(heartbeatObject, computeKey(app));
846
- await tx.done;
847
- }
848
- catch (e) {
849
- if (e instanceof FirebaseError) {
850
- logger.warn(e.message);
851
- }
852
- else {
853
- const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, {
854
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
855
- });
856
- logger.warn(idbGetError.message);
857
- }
858
- }
859
- }
860
- function computeKey(app) {
861
- return `${app.name}!${app.options.appId}`;
768
+ /**
769
+ * @license
770
+ * Copyright 2021 Google LLC
771
+ *
772
+ * Licensed under the Apache License, Version 2.0 (the "License");
773
+ * you may not use this file except in compliance with the License.
774
+ * You may obtain a copy of the License at
775
+ *
776
+ * http://www.apache.org/licenses/LICENSE-2.0
777
+ *
778
+ * Unless required by applicable law or agreed to in writing, software
779
+ * distributed under the License is distributed on an "AS IS" BASIS,
780
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
781
+ * See the License for the specific language governing permissions and
782
+ * limitations under the License.
783
+ */
784
+ const DB_NAME = 'firebase-heartbeat-database';
785
+ const DB_VERSION = 1;
786
+ const STORE_NAME = 'firebase-heartbeat-store';
787
+ let dbPromise = null;
788
+ function getDbPromise() {
789
+ if (!dbPromise) {
790
+ dbPromise = openDB(DB_NAME, DB_VERSION, {
791
+ upgrade: (db, oldVersion) => {
792
+ // We don't use 'break' in this switch statement, the fall-through
793
+ // behavior is what we want, because if there are multiple versions between
794
+ // the old version and the current version, we want ALL the migrations
795
+ // that correspond to those versions to run, not only the last one.
796
+ // eslint-disable-next-line default-case
797
+ switch (oldVersion) {
798
+ case 0:
799
+ try {
800
+ db.createObjectStore(STORE_NAME);
801
+ }
802
+ catch (e) {
803
+ // Safari/iOS browsers throw occasional exceptions on
804
+ // db.createObjectStore() that may be a bug. Avoid blocking
805
+ // the rest of the app functionality.
806
+ console.warn(e);
807
+ }
808
+ }
809
+ }
810
+ }).catch(e => {
811
+ throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, {
812
+ originalErrorMessage: e.message
813
+ });
814
+ });
815
+ }
816
+ return dbPromise;
817
+ }
818
+ async function readHeartbeatsFromIndexedDB(app) {
819
+ try {
820
+ const db = await getDbPromise();
821
+ const tx = db.transaction(STORE_NAME);
822
+ const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
823
+ // We already have the value but tx.done can throw,
824
+ // so we need to await it here to catch errors
825
+ await tx.done;
826
+ return result;
827
+ }
828
+ catch (e) {
829
+ if (e instanceof FirebaseError) {
830
+ logger.warn(e.message);
831
+ }
832
+ else {
833
+ const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, {
834
+ originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
835
+ });
836
+ logger.warn(idbGetError.message);
837
+ }
838
+ }
839
+ }
840
+ async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
841
+ try {
842
+ const db = await getDbPromise();
843
+ const tx = db.transaction(STORE_NAME, 'readwrite');
844
+ const objectStore = tx.objectStore(STORE_NAME);
845
+ await objectStore.put(heartbeatObject, computeKey(app));
846
+ await tx.done;
847
+ }
848
+ catch (e) {
849
+ if (e instanceof FirebaseError) {
850
+ logger.warn(e.message);
851
+ }
852
+ else {
853
+ const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, {
854
+ originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
855
+ });
856
+ logger.warn(idbGetError.message);
857
+ }
858
+ }
859
+ }
860
+ function computeKey(app) {
861
+ return `${app.name}!${app.options.appId}`;
862
862
  }
863
863
 
864
- /**
865
- * @license
866
- * Copyright 2021 Google LLC
867
- *
868
- * Licensed under the Apache License, Version 2.0 (the "License");
869
- * you may not use this file except in compliance with the License.
870
- * You may obtain a copy of the License at
871
- *
872
- * http://www.apache.org/licenses/LICENSE-2.0
873
- *
874
- * Unless required by applicable law or agreed to in writing, software
875
- * distributed under the License is distributed on an "AS IS" BASIS,
876
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
877
- * See the License for the specific language governing permissions and
878
- * limitations under the License.
879
- */
880
- const MAX_HEADER_BYTES = 1024;
881
- // 30 days
882
- const STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;
883
- class HeartbeatServiceImpl {
884
- constructor(container) {
885
- this.container = container;
886
- /**
887
- * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
888
- * the header string.
889
- * Stores one record per date. This will be consolidated into the standard
890
- * format of one record per user agent string before being sent as a header.
891
- * Populated from indexedDB when the controller is instantiated and should
892
- * be kept in sync with indexedDB.
893
- * Leave public for easier testing.
894
- */
895
- this._heartbeatsCache = null;
896
- const app = this.container.getProvider('app').getImmediate();
897
- this._storage = new HeartbeatStorageImpl(app);
898
- this._heartbeatsCachePromise = this._storage.read().then(result => {
899
- this._heartbeatsCache = result;
900
- return result;
901
- });
902
- }
903
- /**
904
- * Called to report a heartbeat. The function will generate
905
- * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
906
- * to IndexedDB.
907
- * Note that we only store one heartbeat per day. So if a heartbeat for today is
908
- * already logged, subsequent calls to this function in the same day will be ignored.
909
- */
910
- async triggerHeartbeat() {
911
- var _a, _b;
912
- try {
913
- const platformLogger = this.container
914
- .getProvider('platform-logger')
915
- .getImmediate();
916
- // This is the "Firebase user agent" string from the platform logger
917
- // service, not the browser user agent.
918
- const agent = platformLogger.getPlatformInfoString();
919
- const date = getUTCDateString();
920
- if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {
921
- this._heartbeatsCache = await this._heartbeatsCachePromise;
922
- // If we failed to construct a heartbeats cache, then return immediately.
923
- if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {
924
- return;
925
- }
926
- }
927
- // Do not store a heartbeat if one is already stored for this day
928
- // or if a header has already been sent today.
929
- if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
930
- this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
931
- return;
932
- }
933
- else {
934
- // There is no entry for this date. Create one.
935
- this._heartbeatsCache.heartbeats.push({ date, agent });
936
- }
937
- // Remove entries older than 30 days.
938
- this._heartbeatsCache.heartbeats =
939
- this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {
940
- const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
941
- const now = Date.now();
942
- return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
943
- });
944
- return this._storage.overwrite(this._heartbeatsCache);
945
- }
946
- catch (e) {
947
- logger.warn(e);
948
- }
949
- }
950
- /**
951
- * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
952
- * It also clears all heartbeats from memory as well as in IndexedDB.
953
- *
954
- * NOTE: Consuming product SDKs should not send the header if this method
955
- * returns an empty string.
956
- */
957
- async getHeartbeatsHeader() {
958
- var _a;
959
- try {
960
- if (this._heartbeatsCache === null) {
961
- await this._heartbeatsCachePromise;
962
- }
963
- // If it's still null or the array is empty, there is no data to send.
964
- if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||
965
- this._heartbeatsCache.heartbeats.length === 0) {
966
- return '';
967
- }
968
- const date = getUTCDateString();
969
- // Extract as many heartbeats from the cache as will fit under the size limit.
970
- const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
971
- const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
972
- // Store last sent date to prevent another being logged/sent for the same day.
973
- this._heartbeatsCache.lastSentHeartbeatDate = date;
974
- if (unsentEntries.length > 0) {
975
- // Store any unsent entries if they exist.
976
- this._heartbeatsCache.heartbeats = unsentEntries;
977
- // This seems more likely than emptying the array (below) to lead to some odd state
978
- // since the cache isn't empty and this will be called again on the next request,
979
- // and is probably safest if we await it.
980
- await this._storage.overwrite(this._heartbeatsCache);
981
- }
982
- else {
983
- this._heartbeatsCache.heartbeats = [];
984
- // Do not wait for this, to reduce latency.
985
- void this._storage.overwrite(this._heartbeatsCache);
986
- }
987
- return headerString;
988
- }
989
- catch (e) {
990
- logger.warn(e);
991
- return '';
992
- }
993
- }
994
- }
995
- function getUTCDateString() {
996
- const today = new Date();
997
- // Returns date format 'YYYY-MM-DD'
998
- return today.toISOString().substring(0, 10);
999
- }
1000
- function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
1001
- // Heartbeats grouped by user agent in the standard format to be sent in
1002
- // the header.
1003
- const heartbeatsToSend = [];
1004
- // Single date format heartbeats that are not sent.
1005
- let unsentEntries = heartbeatsCache.slice();
1006
- for (const singleDateHeartbeat of heartbeatsCache) {
1007
- // Look for an existing entry with the same user agent.
1008
- const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
1009
- if (!heartbeatEntry) {
1010
- // If no entry for this user agent exists, create one.
1011
- heartbeatsToSend.push({
1012
- agent: singleDateHeartbeat.agent,
1013
- dates: [singleDateHeartbeat.date]
1014
- });
1015
- if (countBytes(heartbeatsToSend) > maxSize) {
1016
- // If the header would exceed max size, remove the added heartbeat
1017
- // entry and stop adding to the header.
1018
- heartbeatsToSend.pop();
1019
- break;
1020
- }
1021
- }
1022
- else {
1023
- heartbeatEntry.dates.push(singleDateHeartbeat.date);
1024
- // If the header would exceed max size, remove the added date
1025
- // and stop adding to the header.
1026
- if (countBytes(heartbeatsToSend) > maxSize) {
1027
- heartbeatEntry.dates.pop();
1028
- break;
1029
- }
1030
- }
1031
- // Pop unsent entry from queue. (Skipped if adding the entry exceeded
1032
- // quota and the loop breaks early.)
1033
- unsentEntries = unsentEntries.slice(1);
1034
- }
1035
- return {
1036
- heartbeatsToSend,
1037
- unsentEntries
1038
- };
1039
- }
1040
- class HeartbeatStorageImpl {
1041
- constructor(app) {
1042
- this.app = app;
1043
- this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
1044
- }
1045
- async runIndexedDBEnvironmentCheck() {
1046
- if (!isIndexedDBAvailable()) {
1047
- return false;
1048
- }
1049
- else {
1050
- return validateIndexedDBOpenable()
1051
- .then(() => true)
1052
- .catch(() => false);
1053
- }
1054
- }
1055
- /**
1056
- * Read all heartbeats.
1057
- */
1058
- async read() {
1059
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
1060
- if (!canUseIndexedDB) {
1061
- return { heartbeats: [] };
1062
- }
1063
- else {
1064
- const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
1065
- if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {
1066
- return idbHeartbeatObject;
1067
- }
1068
- else {
1069
- return { heartbeats: [] };
1070
- }
1071
- }
1072
- }
1073
- // overwrite the storage with the provided heartbeats
1074
- async overwrite(heartbeatsObject) {
1075
- var _a;
1076
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
1077
- if (!canUseIndexedDB) {
1078
- return;
1079
- }
1080
- else {
1081
- const existingHeartbeatsObject = await this.read();
1082
- return writeHeartbeatsToIndexedDB(this.app, {
1083
- lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
1084
- heartbeats: heartbeatsObject.heartbeats
1085
- });
1086
- }
1087
- }
1088
- // add heartbeats
1089
- async add(heartbeatsObject) {
1090
- var _a;
1091
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
1092
- if (!canUseIndexedDB) {
1093
- return;
1094
- }
1095
- else {
1096
- const existingHeartbeatsObject = await this.read();
1097
- return writeHeartbeatsToIndexedDB(this.app, {
1098
- lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
1099
- heartbeats: [
1100
- ...existingHeartbeatsObject.heartbeats,
1101
- ...heartbeatsObject.heartbeats
1102
- ]
1103
- });
1104
- }
1105
- }
1106
- }
1107
- /**
1108
- * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
1109
- * in a platform logging header JSON object, stringified, and converted
1110
- * to base 64.
1111
- */
1112
- function countBytes(heartbeatsCache) {
1113
- // base64 has a restricted set of characters, all of which should be 1 byte.
1114
- return base64urlEncodeWithoutPadding(
1115
- // heartbeatsCache wrapper properties
1116
- JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
864
+ /**
865
+ * @license
866
+ * Copyright 2021 Google LLC
867
+ *
868
+ * Licensed under the Apache License, Version 2.0 (the "License");
869
+ * you may not use this file except in compliance with the License.
870
+ * You may obtain a copy of the License at
871
+ *
872
+ * http://www.apache.org/licenses/LICENSE-2.0
873
+ *
874
+ * Unless required by applicable law or agreed to in writing, software
875
+ * distributed under the License is distributed on an "AS IS" BASIS,
876
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
877
+ * See the License for the specific language governing permissions and
878
+ * limitations under the License.
879
+ */
880
+ const MAX_HEADER_BYTES = 1024;
881
+ // 30 days
882
+ const STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;
883
+ class HeartbeatServiceImpl {
884
+ constructor(container) {
885
+ this.container = container;
886
+ /**
887
+ * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
888
+ * the header string.
889
+ * Stores one record per date. This will be consolidated into the standard
890
+ * format of one record per user agent string before being sent as a header.
891
+ * Populated from indexedDB when the controller is instantiated and should
892
+ * be kept in sync with indexedDB.
893
+ * Leave public for easier testing.
894
+ */
895
+ this._heartbeatsCache = null;
896
+ const app = this.container.getProvider('app').getImmediate();
897
+ this._storage = new HeartbeatStorageImpl(app);
898
+ this._heartbeatsCachePromise = this._storage.read().then(result => {
899
+ this._heartbeatsCache = result;
900
+ return result;
901
+ });
902
+ }
903
+ /**
904
+ * Called to report a heartbeat. The function will generate
905
+ * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
906
+ * to IndexedDB.
907
+ * Note that we only store one heartbeat per day. So if a heartbeat for today is
908
+ * already logged, subsequent calls to this function in the same day will be ignored.
909
+ */
910
+ async triggerHeartbeat() {
911
+ var _a, _b;
912
+ try {
913
+ const platformLogger = this.container
914
+ .getProvider('platform-logger')
915
+ .getImmediate();
916
+ // This is the "Firebase user agent" string from the platform logger
917
+ // service, not the browser user agent.
918
+ const agent = platformLogger.getPlatformInfoString();
919
+ const date = getUTCDateString();
920
+ if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {
921
+ this._heartbeatsCache = await this._heartbeatsCachePromise;
922
+ // If we failed to construct a heartbeats cache, then return immediately.
923
+ if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {
924
+ return;
925
+ }
926
+ }
927
+ // Do not store a heartbeat if one is already stored for this day
928
+ // or if a header has already been sent today.
929
+ if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
930
+ this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
931
+ return;
932
+ }
933
+ else {
934
+ // There is no entry for this date. Create one.
935
+ this._heartbeatsCache.heartbeats.push({ date, agent });
936
+ }
937
+ // Remove entries older than 30 days.
938
+ this._heartbeatsCache.heartbeats =
939
+ this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {
940
+ const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
941
+ const now = Date.now();
942
+ return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
943
+ });
944
+ return this._storage.overwrite(this._heartbeatsCache);
945
+ }
946
+ catch (e) {
947
+ logger.warn(e);
948
+ }
949
+ }
950
+ /**
951
+ * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
952
+ * It also clears all heartbeats from memory as well as in IndexedDB.
953
+ *
954
+ * NOTE: Consuming product SDKs should not send the header if this method
955
+ * returns an empty string.
956
+ */
957
+ async getHeartbeatsHeader() {
958
+ var _a;
959
+ try {
960
+ if (this._heartbeatsCache === null) {
961
+ await this._heartbeatsCachePromise;
962
+ }
963
+ // If it's still null or the array is empty, there is no data to send.
964
+ if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||
965
+ this._heartbeatsCache.heartbeats.length === 0) {
966
+ return '';
967
+ }
968
+ const date = getUTCDateString();
969
+ // Extract as many heartbeats from the cache as will fit under the size limit.
970
+ const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
971
+ const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
972
+ // Store last sent date to prevent another being logged/sent for the same day.
973
+ this._heartbeatsCache.lastSentHeartbeatDate = date;
974
+ if (unsentEntries.length > 0) {
975
+ // Store any unsent entries if they exist.
976
+ this._heartbeatsCache.heartbeats = unsentEntries;
977
+ // This seems more likely than emptying the array (below) to lead to some odd state
978
+ // since the cache isn't empty and this will be called again on the next request,
979
+ // and is probably safest if we await it.
980
+ await this._storage.overwrite(this._heartbeatsCache);
981
+ }
982
+ else {
983
+ this._heartbeatsCache.heartbeats = [];
984
+ // Do not wait for this, to reduce latency.
985
+ void this._storage.overwrite(this._heartbeatsCache);
986
+ }
987
+ return headerString;
988
+ }
989
+ catch (e) {
990
+ logger.warn(e);
991
+ return '';
992
+ }
993
+ }
994
+ }
995
+ function getUTCDateString() {
996
+ const today = new Date();
997
+ // Returns date format 'YYYY-MM-DD'
998
+ return today.toISOString().substring(0, 10);
999
+ }
1000
+ function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
1001
+ // Heartbeats grouped by user agent in the standard format to be sent in
1002
+ // the header.
1003
+ const heartbeatsToSend = [];
1004
+ // Single date format heartbeats that are not sent.
1005
+ let unsentEntries = heartbeatsCache.slice();
1006
+ for (const singleDateHeartbeat of heartbeatsCache) {
1007
+ // Look for an existing entry with the same user agent.
1008
+ const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
1009
+ if (!heartbeatEntry) {
1010
+ // If no entry for this user agent exists, create one.
1011
+ heartbeatsToSend.push({
1012
+ agent: singleDateHeartbeat.agent,
1013
+ dates: [singleDateHeartbeat.date]
1014
+ });
1015
+ if (countBytes(heartbeatsToSend) > maxSize) {
1016
+ // If the header would exceed max size, remove the added heartbeat
1017
+ // entry and stop adding to the header.
1018
+ heartbeatsToSend.pop();
1019
+ break;
1020
+ }
1021
+ }
1022
+ else {
1023
+ heartbeatEntry.dates.push(singleDateHeartbeat.date);
1024
+ // If the header would exceed max size, remove the added date
1025
+ // and stop adding to the header.
1026
+ if (countBytes(heartbeatsToSend) > maxSize) {
1027
+ heartbeatEntry.dates.pop();
1028
+ break;
1029
+ }
1030
+ }
1031
+ // Pop unsent entry from queue. (Skipped if adding the entry exceeded
1032
+ // quota and the loop breaks early.)
1033
+ unsentEntries = unsentEntries.slice(1);
1034
+ }
1035
+ return {
1036
+ heartbeatsToSend,
1037
+ unsentEntries
1038
+ };
1039
+ }
1040
+ class HeartbeatStorageImpl {
1041
+ constructor(app) {
1042
+ this.app = app;
1043
+ this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
1044
+ }
1045
+ async runIndexedDBEnvironmentCheck() {
1046
+ if (!isIndexedDBAvailable()) {
1047
+ return false;
1048
+ }
1049
+ else {
1050
+ return validateIndexedDBOpenable()
1051
+ .then(() => true)
1052
+ .catch(() => false);
1053
+ }
1054
+ }
1055
+ /**
1056
+ * Read all heartbeats.
1057
+ */
1058
+ async read() {
1059
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1060
+ if (!canUseIndexedDB) {
1061
+ return { heartbeats: [] };
1062
+ }
1063
+ else {
1064
+ const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
1065
+ if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {
1066
+ return idbHeartbeatObject;
1067
+ }
1068
+ else {
1069
+ return { heartbeats: [] };
1070
+ }
1071
+ }
1072
+ }
1073
+ // overwrite the storage with the provided heartbeats
1074
+ async overwrite(heartbeatsObject) {
1075
+ var _a;
1076
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1077
+ if (!canUseIndexedDB) {
1078
+ return;
1079
+ }
1080
+ else {
1081
+ const existingHeartbeatsObject = await this.read();
1082
+ return writeHeartbeatsToIndexedDB(this.app, {
1083
+ lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
1084
+ heartbeats: heartbeatsObject.heartbeats
1085
+ });
1086
+ }
1087
+ }
1088
+ // add heartbeats
1089
+ async add(heartbeatsObject) {
1090
+ var _a;
1091
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1092
+ if (!canUseIndexedDB) {
1093
+ return;
1094
+ }
1095
+ else {
1096
+ const existingHeartbeatsObject = await this.read();
1097
+ return writeHeartbeatsToIndexedDB(this.app, {
1098
+ lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
1099
+ heartbeats: [
1100
+ ...existingHeartbeatsObject.heartbeats,
1101
+ ...heartbeatsObject.heartbeats
1102
+ ]
1103
+ });
1104
+ }
1105
+ }
1106
+ }
1107
+ /**
1108
+ * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
1109
+ * in a platform logging header JSON object, stringified, and converted
1110
+ * to base 64.
1111
+ */
1112
+ function countBytes(heartbeatsCache) {
1113
+ // base64 has a restricted set of characters, all of which should be 1 byte.
1114
+ return base64urlEncodeWithoutPadding(
1115
+ // heartbeatsCache wrapper properties
1116
+ JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
1117
1117
  }
1118
1118
 
1119
- /**
1120
- * @license
1121
- * Copyright 2019 Google LLC
1122
- *
1123
- * Licensed under the Apache License, Version 2.0 (the "License");
1124
- * you may not use this file except in compliance with the License.
1125
- * You may obtain a copy of the License at
1126
- *
1127
- * http://www.apache.org/licenses/LICENSE-2.0
1128
- *
1129
- * Unless required by applicable law or agreed to in writing, software
1130
- * distributed under the License is distributed on an "AS IS" BASIS,
1131
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1132
- * See the License for the specific language governing permissions and
1133
- * limitations under the License.
1134
- */
1135
- function registerCoreComponents(variant) {
1136
- _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1137
- _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1138
- // Register `app` package.
1139
- registerVersion(name$q, version$1, variant);
1140
- // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
1141
- registerVersion(name$q, version$1, 'esm2017');
1142
- // Register platform SDK identifier (no version).
1143
- registerVersion('fire-js', '');
1119
+ /**
1120
+ * @license
1121
+ * Copyright 2019 Google LLC
1122
+ *
1123
+ * Licensed under the Apache License, Version 2.0 (the "License");
1124
+ * you may not use this file except in compliance with the License.
1125
+ * You may obtain a copy of the License at
1126
+ *
1127
+ * http://www.apache.org/licenses/LICENSE-2.0
1128
+ *
1129
+ * Unless required by applicable law or agreed to in writing, software
1130
+ * distributed under the License is distributed on an "AS IS" BASIS,
1131
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1132
+ * See the License for the specific language governing permissions and
1133
+ * limitations under the License.
1134
+ */
1135
+ function registerCoreComponents(variant) {
1136
+ _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1137
+ _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1138
+ // Register `app` package.
1139
+ registerVersion(name$q, version$1, variant);
1140
+ // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
1141
+ registerVersion(name$q, version$1, 'esm2017');
1142
+ // Register platform SDK identifier (no version).
1143
+ registerVersion('fire-js', '');
1144
1144
  }
1145
1145
 
1146
- /**
1147
- * Firebase App
1148
- *
1149
- * @remarks This package coordinates the communication between the different Firebase components
1150
- * @packageDocumentation
1151
- */
1146
+ /**
1147
+ * Firebase App
1148
+ *
1149
+ * @remarks This package coordinates the communication between the different Firebase components
1150
+ * @packageDocumentation
1151
+ */
1152
1152
  registerCoreComponents('');
1153
1153
 
1154
1154
  export { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };