@depup/firebase__analytics 0.10.20-depup.0

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 (44) hide show
  1. package/README.md +31 -0
  2. package/changes.json +10 -0
  3. package/dist/analytics-public.d.ts +763 -0
  4. package/dist/analytics.d.ts +763 -0
  5. package/dist/esm/index.esm.js +1272 -0
  6. package/dist/esm/index.esm.js.map +1 -0
  7. package/dist/esm/package.json +1 -0
  8. package/dist/esm/src/api.d.ts +453 -0
  9. package/dist/esm/src/constants.d.ts +32 -0
  10. package/dist/esm/src/errors.d.ts +57 -0
  11. package/dist/esm/src/factory.d.ts +74 -0
  12. package/dist/esm/src/functions.d.ts +85 -0
  13. package/dist/esm/src/get-config.d.ts +72 -0
  14. package/dist/esm/src/helpers.d.ts +70 -0
  15. package/dist/esm/src/index.d.ts +14 -0
  16. package/dist/esm/src/initialize-analytics.d.ts +36 -0
  17. package/dist/esm/src/logger.d.ts +18 -0
  18. package/dist/esm/src/public-types.d.ts +282 -0
  19. package/dist/esm/src/types.d.ts +55 -0
  20. package/dist/esm/testing/get-fake-firebase-services.d.ts +29 -0
  21. package/dist/esm/testing/gtag-script-util.d.ts +1 -0
  22. package/dist/esm/testing/integration-tests/integration.d.ts +18 -0
  23. package/dist/esm/testing/setup.d.ts +17 -0
  24. package/dist/index.cjs.js +1287 -0
  25. package/dist/index.cjs.js.map +1 -0
  26. package/dist/src/api.d.ts +453 -0
  27. package/dist/src/constants.d.ts +32 -0
  28. package/dist/src/errors.d.ts +57 -0
  29. package/dist/src/factory.d.ts +74 -0
  30. package/dist/src/functions.d.ts +85 -0
  31. package/dist/src/get-config.d.ts +72 -0
  32. package/dist/src/global_index.d.ts +1056 -0
  33. package/dist/src/helpers.d.ts +70 -0
  34. package/dist/src/index.d.ts +14 -0
  35. package/dist/src/initialize-analytics.d.ts +36 -0
  36. package/dist/src/logger.d.ts +18 -0
  37. package/dist/src/public-types.d.ts +282 -0
  38. package/dist/src/tsdoc-metadata.json +11 -0
  39. package/dist/src/types.d.ts +55 -0
  40. package/dist/testing/get-fake-firebase-services.d.ts +29 -0
  41. package/dist/testing/gtag-script-util.d.ts +1 -0
  42. package/dist/testing/integration-tests/integration.d.ts +18 -0
  43. package/dist/testing/setup.d.ts +17 -0
  44. package/package.json +95 -0
@@ -0,0 +1,1287 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var app = require('@firebase/app');
6
+ var logger$1 = require('@firebase/logger');
7
+ var util = require('@firebase/util');
8
+ var component = require('@firebase/component');
9
+ require('@firebase/installations');
10
+
11
+ /**
12
+ * @license
13
+ * Copyright 2019 Google LLC
14
+ *
15
+ * Licensed under the Apache License, Version 2.0 (the "License");
16
+ * you may not use this file except in compliance with the License.
17
+ * You may obtain a copy of the License at
18
+ *
19
+ * http://www.apache.org/licenses/LICENSE-2.0
20
+ *
21
+ * Unless required by applicable law or agreed to in writing, software
22
+ * distributed under the License is distributed on an "AS IS" BASIS,
23
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ * See the License for the specific language governing permissions and
25
+ * limitations under the License.
26
+ */
27
+ /**
28
+ * Type constant for Firebase Analytics.
29
+ */
30
+ const ANALYTICS_TYPE = 'analytics';
31
+ // Key to attach FID to in gtag params.
32
+ const GA_FID_KEY = 'firebase_id';
33
+ const ORIGIN_KEY = 'origin';
34
+ const FETCH_TIMEOUT_MILLIS = 60 * 1000;
35
+ const DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';
36
+ const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';
37
+
38
+ /**
39
+ * @license
40
+ * Copyright 2019 Google LLC
41
+ *
42
+ * Licensed under the Apache License, Version 2.0 (the "License");
43
+ * you may not use this file except in compliance with the License.
44
+ * 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
49
+ * distributed under the License is distributed on an "AS IS" BASIS,
50
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
51
+ * See the License for the specific language governing permissions and
52
+ * limitations under the License.
53
+ */
54
+ const logger = new logger$1.Logger('@firebase/analytics');
55
+
56
+ /**
57
+ * @license
58
+ * Copyright 2019 Google LLC
59
+ *
60
+ * Licensed under the Apache License, Version 2.0 (the "License");
61
+ * you may not use this file except in compliance with the License.
62
+ * You may obtain a copy of the License at
63
+ *
64
+ * http://www.apache.org/licenses/LICENSE-2.0
65
+ *
66
+ * Unless required by applicable law or agreed to in writing, software
67
+ * distributed under the License is distributed on an "AS IS" BASIS,
68
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
69
+ * See the License for the specific language governing permissions and
70
+ * limitations under the License.
71
+ */
72
+ const ERRORS = {
73
+ ["already-exists" /* AnalyticsError.ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' +
74
+ ' already exists. ' +
75
+ 'Only one Firebase Analytics instance can be created for each appId.',
76
+ ["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' +
77
+ 'it was initially called with. It can be called again with the same options to ' +
78
+ 'return the existing instance, or getAnalytics() can be used ' +
79
+ 'to get a reference to the already-initialized instance.',
80
+ ["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' +
81
+ 'settings() must be called before initializing any Analytics instance' +
82
+ 'or it will have no effect.',
83
+ ["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
84
+ ["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' +
85
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
86
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
87
+ ["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' +
88
+ 'Wrap initialization of analytics in analytics.isSupported() ' +
89
+ 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
90
+ ["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
91
+ ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
92
+ ["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
93
+ ["no-api-key" /* AnalyticsError.NO_API_KEY */]: 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
94
+ 'contain a valid API key.',
95
+ ["no-app-id" /* AnalyticsError.NO_APP_ID */]: 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
96
+ 'contain a valid app ID.',
97
+ ["no-client-id" /* AnalyticsError.NO_CLIENT_ID */]: 'The "client_id" field is empty.',
98
+ ["invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */]: 'Trusted Types detected an invalid gtag resource: {$gtagURL}.'
99
+ };
100
+ const ERROR_FACTORY = new util.ErrorFactory('analytics', 'Analytics', ERRORS);
101
+
102
+ /**
103
+ * @license
104
+ * Copyright 2019 Google LLC
105
+ *
106
+ * Licensed under the Apache License, Version 2.0 (the "License");
107
+ * you may not use this file except in compliance with the License.
108
+ * You may obtain a copy of the License at
109
+ *
110
+ * http://www.apache.org/licenses/LICENSE-2.0
111
+ *
112
+ * Unless required by applicable law or agreed to in writing, software
113
+ * distributed under the License is distributed on an "AS IS" BASIS,
114
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
115
+ * See the License for the specific language governing permissions and
116
+ * limitations under the License.
117
+ */
118
+ /**
119
+ * Verifies and creates a TrustedScriptURL.
120
+ */
121
+ function createGtagTrustedTypesScriptURL(url) {
122
+ if (!url.startsWith(GTAG_URL)) {
123
+ const err = ERROR_FACTORY.create("invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */, {
124
+ gtagURL: url
125
+ });
126
+ logger.warn(err.message);
127
+ return '';
128
+ }
129
+ return url;
130
+ }
131
+ /**
132
+ * Makeshift polyfill for Promise.allSettled(). Resolves when all promises
133
+ * have either resolved or rejected.
134
+ *
135
+ * @param promises Array of promises to wait for.
136
+ */
137
+ function promiseAllSettled(promises) {
138
+ return Promise.all(promises.map(promise => promise.catch(e => e)));
139
+ }
140
+ /**
141
+ * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
142
+ *
143
+ * @param policyName A string containing the name of the policy
144
+ * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods
145
+ * | the TrustedTypePolicy reference documentation}.
146
+ */
147
+ function createTrustedTypesPolicy(policyName, policyOptions) {
148
+ // Create a TrustedTypes policy that we can use for updating src
149
+ // properties
150
+ let trustedTypesPolicy;
151
+ if (window.trustedTypes) {
152
+ trustedTypesPolicy = window.trustedTypes.createPolicy(policyName, policyOptions);
153
+ }
154
+ return trustedTypesPolicy;
155
+ }
156
+ /**
157
+ * Inserts gtag script tag into the page to asynchronously download gtag.
158
+ * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
159
+ */
160
+ function insertScriptTag(dataLayerName, measurementId) {
161
+ const trustedTypesPolicy = createTrustedTypesPolicy('firebase-js-sdk-policy', {
162
+ createScriptURL: createGtagTrustedTypesScriptURL
163
+ });
164
+ const script = document.createElement('script');
165
+ // We are not providing an analyticsId in the URL because it would trigger a `page_view`
166
+ // without fid. We will initialize ga-id using gtag (config) command together with fid.
167
+ const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;
168
+ script.src = trustedTypesPolicy
169
+ ? trustedTypesPolicy?.createScriptURL(gtagScriptURL)
170
+ : gtagScriptURL;
171
+ script.async = true;
172
+ document.head.appendChild(script);
173
+ }
174
+ /**
175
+ * Get reference to, or create, global datalayer.
176
+ * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
177
+ */
178
+ function getOrCreateDataLayer(dataLayerName) {
179
+ // Check for existing dataLayer and create if needed.
180
+ let dataLayer = [];
181
+ if (Array.isArray(window[dataLayerName])) {
182
+ dataLayer = window[dataLayerName];
183
+ }
184
+ else {
185
+ window[dataLayerName] = dataLayer;
186
+ }
187
+ return dataLayer;
188
+ }
189
+ /**
190
+ * Wrapped gtag logic when gtag is called with 'config' command.
191
+ *
192
+ * @param gtagCore Basic gtag function that just appends to dataLayer.
193
+ * @param initializationPromisesMap Map of appIds to their initialization promises.
194
+ * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
195
+ * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
196
+ * @param measurementId GA Measurement ID to set config for.
197
+ * @param gtagParams Gtag config params to set.
198
+ */
199
+ async function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {
200
+ // If config is already fetched, we know the appId and can use it to look up what FID promise we
201
+ /// are waiting for, and wait only on that one.
202
+ const correspondingAppId = measurementIdToAppId[measurementId];
203
+ try {
204
+ if (correspondingAppId) {
205
+ await initializationPromisesMap[correspondingAppId];
206
+ }
207
+ else {
208
+ // If config is not fetched yet, wait for all configs (we don't know which one we need) and
209
+ // find the appId (if any) corresponding to this measurementId. If there is one, wait on
210
+ // that appId's initialization promise. If there is none, promise resolves and gtag
211
+ // call goes through.
212
+ const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);
213
+ const foundConfig = dynamicConfigResults.find(config => config.measurementId === measurementId);
214
+ if (foundConfig) {
215
+ await initializationPromisesMap[foundConfig.appId];
216
+ }
217
+ }
218
+ }
219
+ catch (e) {
220
+ logger.error(e);
221
+ }
222
+ gtagCore("config" /* GtagCommand.CONFIG */, measurementId, gtagParams);
223
+ }
224
+ /**
225
+ * Wrapped gtag logic when gtag is called with 'event' command.
226
+ *
227
+ * @param gtagCore Basic gtag function that just appends to dataLayer.
228
+ * @param initializationPromisesMap Map of appIds to their initialization promises.
229
+ * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
230
+ * @param measurementId GA Measurement ID to log event to.
231
+ * @param gtagParams Params to log with this event.
232
+ */
233
+ async function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {
234
+ try {
235
+ let initializationPromisesToWaitFor = [];
236
+ // If there's a 'send_to' param, check if any ID specified matches
237
+ // an initializeIds() promise we are waiting for.
238
+ if (gtagParams && gtagParams['send_to']) {
239
+ let gaSendToList = gtagParams['send_to'];
240
+ // Make it an array if is isn't, so it can be dealt with the same way.
241
+ if (!Array.isArray(gaSendToList)) {
242
+ gaSendToList = [gaSendToList];
243
+ }
244
+ // Checking 'send_to' fields requires having all measurement ID results back from
245
+ // the dynamic config fetch.
246
+ const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);
247
+ for (const sendToId of gaSendToList) {
248
+ // Any fetched dynamic measurement ID that matches this 'send_to' ID
249
+ const foundConfig = dynamicConfigResults.find(config => config.measurementId === sendToId);
250
+ const initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];
251
+ if (initializationPromise) {
252
+ initializationPromisesToWaitFor.push(initializationPromise);
253
+ }
254
+ else {
255
+ // Found an item in 'send_to' that is not associated
256
+ // directly with an FID, possibly a group. Empty this array,
257
+ // exit the loop early, and let it get populated below.
258
+ initializationPromisesToWaitFor = [];
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ // This will be unpopulated if there was no 'send_to' field , or
264
+ // if not all entries in the 'send_to' field could be mapped to
265
+ // a FID. In these cases, wait on all pending initialization promises.
266
+ if (initializationPromisesToWaitFor.length === 0) {
267
+ /* eslint-disable-next-line @typescript-eslint/no-floating-promises */
268
+ initializationPromisesToWaitFor = Object.values(initializationPromisesMap);
269
+ }
270
+ // Run core gtag function with args after all relevant initialization
271
+ // promises have been resolved.
272
+ await Promise.all(initializationPromisesToWaitFor);
273
+ // Workaround for http://b/141370449 - third argument cannot be undefined.
274
+ gtagCore("event" /* GtagCommand.EVENT */, measurementId, gtagParams || {});
275
+ }
276
+ catch (e) {
277
+ logger.error(e);
278
+ }
279
+ }
280
+ /**
281
+ * Wraps a standard gtag function with extra code to wait for completion of
282
+ * relevant initialization promises before sending requests.
283
+ *
284
+ * @param gtagCore Basic gtag function that just appends to dataLayer.
285
+ * @param initializationPromisesMap Map of appIds to their initialization promises.
286
+ * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
287
+ * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
288
+ */
289
+ function wrapGtag(gtagCore,
290
+ /**
291
+ * Allows wrapped gtag calls to wait on whichever initialization promises are required,
292
+ * depending on the contents of the gtag params' `send_to` field, if any.
293
+ */
294
+ initializationPromisesMap,
295
+ /**
296
+ * Wrapped gtag calls sometimes require all dynamic config fetches to have returned
297
+ * before determining what initialization promises (which include FIDs) to wait for.
298
+ */
299
+ dynamicConfigPromisesList,
300
+ /**
301
+ * Wrapped gtag config calls can narrow down which initialization promise (with FID)
302
+ * to wait for if the measurementId is already fetched, by getting the corresponding appId,
303
+ * which is the key for the initialization promises map.
304
+ */
305
+ measurementIdToAppId) {
306
+ /**
307
+ * Wrapper around gtag that ensures FID is sent with gtag calls.
308
+ * @param command Gtag command type.
309
+ * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
310
+ * @param gtagParams Params if event is EVENT/CONFIG.
311
+ */
312
+ async function gtagWrapper(command, ...args) {
313
+ try {
314
+ // If event, check that relevant initialization promises have completed.
315
+ if (command === "event" /* GtagCommand.EVENT */) {
316
+ const [measurementId, gtagParams] = args;
317
+ // If EVENT, second arg must be measurementId.
318
+ await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams);
319
+ }
320
+ else if (command === "config" /* GtagCommand.CONFIG */) {
321
+ const [measurementId, gtagParams] = args;
322
+ // If CONFIG, second arg must be measurementId.
323
+ await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams);
324
+ }
325
+ else if (command === "consent" /* GtagCommand.CONSENT */) {
326
+ const [consentAction, gtagParams] = args;
327
+ // consentAction can be one of 'default' or 'update'.
328
+ gtagCore("consent" /* GtagCommand.CONSENT */, consentAction, gtagParams);
329
+ }
330
+ else if (command === "get" /* GtagCommand.GET */) {
331
+ const [measurementId, fieldName, callback] = args;
332
+ gtagCore("get" /* GtagCommand.GET */, measurementId, fieldName, callback);
333
+ }
334
+ else if (command === "set" /* GtagCommand.SET */) {
335
+ const [customParams] = args;
336
+ // If SET, second arg must be params.
337
+ gtagCore("set" /* GtagCommand.SET */, customParams);
338
+ }
339
+ else {
340
+ gtagCore(command, ...args);
341
+ }
342
+ }
343
+ catch (e) {
344
+ logger.error(e);
345
+ }
346
+ }
347
+ return gtagWrapper;
348
+ }
349
+ /**
350
+ * Creates global gtag function or wraps existing one if found.
351
+ * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and
352
+ * 'event' calls that belong to the GAID associated with this Firebase instance.
353
+ *
354
+ * @param initializationPromisesMap Map of appIds to their initialization promises.
355
+ * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
356
+ * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
357
+ * @param dataLayerName Name of global GA datalayer array.
358
+ * @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified).
359
+ */
360
+ function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {
361
+ // Create a basic core gtag function
362
+ let gtagCore = function (..._args) {
363
+ // Must push IArguments object, not an array.
364
+ window[dataLayerName].push(arguments);
365
+ };
366
+ // Replace it with existing one if found
367
+ if (window[gtagFunctionName] &&
368
+ typeof window[gtagFunctionName] === 'function') {
369
+ // @ts-ignore
370
+ gtagCore = window[gtagFunctionName];
371
+ }
372
+ window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);
373
+ return {
374
+ gtagCore,
375
+ wrappedGtag: window[gtagFunctionName]
376
+ };
377
+ }
378
+ /**
379
+ * Returns the script tag in the DOM matching both the gtag url pattern
380
+ * and the provided data layer name.
381
+ */
382
+ function findGtagScriptOnPage(dataLayerName) {
383
+ const scriptTags = window.document.getElementsByTagName('script');
384
+ for (const tag of Object.values(scriptTags)) {
385
+ if (tag.src &&
386
+ tag.src.includes(GTAG_URL) &&
387
+ tag.src.includes(dataLayerName)) {
388
+ return tag;
389
+ }
390
+ }
391
+ return null;
392
+ }
393
+
394
+ /**
395
+ * @license
396
+ * Copyright 2020 Google LLC
397
+ *
398
+ * Licensed under the Apache License, Version 2.0 (the "License");
399
+ * you may not use this file except in compliance with the License.
400
+ * You may obtain a copy of the License at
401
+ *
402
+ * http://www.apache.org/licenses/LICENSE-2.0
403
+ *
404
+ * Unless required by applicable law or agreed to in writing, software
405
+ * distributed under the License is distributed on an "AS IS" BASIS,
406
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
407
+ * See the License for the specific language governing permissions and
408
+ * limitations under the License.
409
+ */
410
+ /**
411
+ * Backoff factor for 503 errors, which we want to be conservative about
412
+ * to avoid overloading servers. Each retry interval will be
413
+ * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one
414
+ * will be ~30 seconds (with fuzzing).
415
+ */
416
+ const LONG_RETRY_FACTOR = 30;
417
+ /**
418
+ * Base wait interval to multiplied by backoffFactor^backoffCount.
419
+ */
420
+ const BASE_INTERVAL_MILLIS = 1000;
421
+ /**
422
+ * Stubbable retry data storage class.
423
+ */
424
+ class RetryData {
425
+ constructor(throttleMetadata = {}, intervalMillis = BASE_INTERVAL_MILLIS) {
426
+ this.throttleMetadata = throttleMetadata;
427
+ this.intervalMillis = intervalMillis;
428
+ }
429
+ getThrottleMetadata(appId) {
430
+ return this.throttleMetadata[appId];
431
+ }
432
+ setThrottleMetadata(appId, metadata) {
433
+ this.throttleMetadata[appId] = metadata;
434
+ }
435
+ deleteThrottleMetadata(appId) {
436
+ delete this.throttleMetadata[appId];
437
+ }
438
+ }
439
+ const defaultRetryData = new RetryData();
440
+ /**
441
+ * Set GET request headers.
442
+ * @param apiKey App API key.
443
+ */
444
+ function getHeaders(apiKey) {
445
+ return new Headers({
446
+ Accept: 'application/json',
447
+ 'x-goog-api-key': apiKey
448
+ });
449
+ }
450
+ /**
451
+ * Fetches dynamic config from backend.
452
+ * @param app Firebase app to fetch config for.
453
+ */
454
+ async function fetchDynamicConfig(appFields) {
455
+ const { appId, apiKey } = appFields;
456
+ const request = {
457
+ method: 'GET',
458
+ headers: getHeaders(apiKey)
459
+ };
460
+ const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);
461
+ const response = await fetch(appUrl, request);
462
+ if (response.status !== 200 && response.status !== 304) {
463
+ let errorMessage = '';
464
+ try {
465
+ // Try to get any error message text from server response.
466
+ const jsonResponse = (await response.json());
467
+ if (jsonResponse.error?.message) {
468
+ errorMessage = jsonResponse.error.message;
469
+ }
470
+ }
471
+ catch (_ignored) { }
472
+ throw ERROR_FACTORY.create("config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */, {
473
+ httpStatus: response.status,
474
+ responseMessage: errorMessage
475
+ });
476
+ }
477
+ return response.json();
478
+ }
479
+ /**
480
+ * Fetches dynamic config from backend, retrying if failed.
481
+ * @param app Firebase app to fetch config for.
482
+ */
483
+ async function fetchDynamicConfigWithRetry(app,
484
+ // retryData and timeoutMillis are parameterized to allow passing a different value for testing.
485
+ retryData = defaultRetryData, timeoutMillis) {
486
+ const { appId, apiKey, measurementId } = app.options;
487
+ if (!appId) {
488
+ throw ERROR_FACTORY.create("no-app-id" /* AnalyticsError.NO_APP_ID */);
489
+ }
490
+ if (!apiKey) {
491
+ if (measurementId) {
492
+ return {
493
+ measurementId,
494
+ appId
495
+ };
496
+ }
497
+ throw ERROR_FACTORY.create("no-api-key" /* AnalyticsError.NO_API_KEY */);
498
+ }
499
+ const throttleMetadata = retryData.getThrottleMetadata(appId) || {
500
+ backoffCount: 0,
501
+ throttleEndTimeMillis: Date.now()
502
+ };
503
+ const signal = new AnalyticsAbortSignal();
504
+ setTimeout(async () => {
505
+ // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
506
+ signal.abort();
507
+ }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);
508
+ return attemptFetchDynamicConfigWithRetry({ appId, apiKey, measurementId }, throttleMetadata, signal, retryData);
509
+ }
510
+ /**
511
+ * Runs one retry attempt.
512
+ * @param appFields Necessary app config fields.
513
+ * @param throttleMetadata Ongoing metadata to determine throttling times.
514
+ * @param signal Abort signal.
515
+ */
516
+ async function attemptFetchDynamicConfigWithRetry(appFields, { throttleEndTimeMillis, backoffCount }, signal, retryData = defaultRetryData // for testing
517
+ ) {
518
+ const { appId, measurementId } = appFields;
519
+ // Starts with a (potentially zero) timeout to support resumption from stored state.
520
+ // Ensures the throttle end time is honored if the last attempt timed out.
521
+ // Note the SDK will never make a request if the fetch timeout expires at this point.
522
+ try {
523
+ await setAbortableTimeout(signal, throttleEndTimeMillis);
524
+ }
525
+ catch (e) {
526
+ if (measurementId) {
527
+ logger.warn(`Timed out fetching this Firebase app's measurement ID from the server.` +
528
+ ` Falling back to the measurement ID ${measurementId}` +
529
+ ` provided in the "measurementId" field in the local Firebase config. [${e?.message}]`);
530
+ return { appId, measurementId };
531
+ }
532
+ throw e;
533
+ }
534
+ try {
535
+ const response = await fetchDynamicConfig(appFields);
536
+ // Note the SDK only clears throttle state if response is success or non-retriable.
537
+ retryData.deleteThrottleMetadata(appId);
538
+ return response;
539
+ }
540
+ catch (e) {
541
+ const error = e;
542
+ if (!isRetriableError(error)) {
543
+ retryData.deleteThrottleMetadata(appId);
544
+ if (measurementId) {
545
+ logger.warn(`Failed to fetch this Firebase app's measurement ID from the server.` +
546
+ ` Falling back to the measurement ID ${measurementId}` +
547
+ ` provided in the "measurementId" field in the local Firebase config. [${error?.message}]`);
548
+ return { appId, measurementId };
549
+ }
550
+ else {
551
+ throw e;
552
+ }
553
+ }
554
+ const backoffMillis = Number(error?.customData?.httpStatus) === 503
555
+ ? util.calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)
556
+ : util.calculateBackoffMillis(backoffCount, retryData.intervalMillis);
557
+ // Increments backoff state.
558
+ const throttleMetadata = {
559
+ throttleEndTimeMillis: Date.now() + backoffMillis,
560
+ backoffCount: backoffCount + 1
561
+ };
562
+ // Persists state.
563
+ retryData.setThrottleMetadata(appId, throttleMetadata);
564
+ logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);
565
+ return attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData);
566
+ }
567
+ }
568
+ /**
569
+ * Supports waiting on a backoff by:
570
+ *
571
+ * <ul>
572
+ * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
573
+ * <li>Listening on a signal bus for abort events, just like the Fetch API</li>
574
+ * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
575
+ * request appear the same.</li>
576
+ * </ul>
577
+ *
578
+ * <p>Visible for testing.
579
+ */
580
+ function setAbortableTimeout(signal, throttleEndTimeMillis) {
581
+ return new Promise((resolve, reject) => {
582
+ // Derives backoff from given end time, normalizing negative numbers to zero.
583
+ const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
584
+ const timeout = setTimeout(resolve, backoffMillis);
585
+ // Adds listener, rather than sets onabort, because signal is a shared object.
586
+ signal.addEventListener(() => {
587
+ clearTimeout(timeout);
588
+ // If the request completes before this timeout, the rejection has no effect.
589
+ reject(ERROR_FACTORY.create("fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */, {
590
+ throttleEndTimeMillis
591
+ }));
592
+ });
593
+ });
594
+ }
595
+ /**
596
+ * Returns true if the {@link Error} indicates a fetch request may succeed later.
597
+ */
598
+ function isRetriableError(e) {
599
+ if (!(e instanceof util.FirebaseError) || !e.customData) {
600
+ return false;
601
+ }
602
+ // Uses string index defined by ErrorData, which FirebaseError implements.
603
+ const httpStatus = Number(e.customData['httpStatus']);
604
+ return (httpStatus === 429 ||
605
+ httpStatus === 500 ||
606
+ httpStatus === 503 ||
607
+ httpStatus === 504);
608
+ }
609
+ /**
610
+ * Shims a minimal AbortSignal (copied from Remote Config).
611
+ *
612
+ * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
613
+ * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
614
+ * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
615
+ * swapped out if/when we do.
616
+ */
617
+ class AnalyticsAbortSignal {
618
+ constructor() {
619
+ this.listeners = [];
620
+ }
621
+ addEventListener(listener) {
622
+ this.listeners.push(listener);
623
+ }
624
+ abort() {
625
+ this.listeners.forEach(listener => listener());
626
+ }
627
+ }
628
+
629
+ /**
630
+ * @license
631
+ * Copyright 2019 Google LLC
632
+ *
633
+ * Licensed under the Apache License, Version 2.0 (the "License");
634
+ * you may not use this file except in compliance with the License.
635
+ * You may obtain a copy of the License at
636
+ *
637
+ * http://www.apache.org/licenses/LICENSE-2.0
638
+ *
639
+ * Unless required by applicable law or agreed to in writing, software
640
+ * distributed under the License is distributed on an "AS IS" BASIS,
641
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
642
+ * See the License for the specific language governing permissions and
643
+ * limitations under the License.
644
+ */
645
+ /**
646
+ * Event parameters to set on 'gtag' during initialization.
647
+ */
648
+ let defaultEventParametersForInit;
649
+ /**
650
+ * Logs an analytics event through the Firebase SDK.
651
+ *
652
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
653
+ * @param eventName Google Analytics event name, choose from standard list or use a custom string.
654
+ * @param eventParams Analytics event parameters.
655
+ */
656
+ async function logEvent$1(gtagFunction, initializationPromise, eventName, eventParams, options) {
657
+ if (options && options.global) {
658
+ gtagFunction("event" /* GtagCommand.EVENT */, eventName, eventParams);
659
+ return;
660
+ }
661
+ else {
662
+ const measurementId = await initializationPromise;
663
+ const params = {
664
+ ...eventParams,
665
+ 'send_to': measurementId
666
+ };
667
+ gtagFunction("event" /* GtagCommand.EVENT */, eventName, params);
668
+ }
669
+ }
670
+ /**
671
+ * Set screen_name parameter for this Google Analytics ID.
672
+ *
673
+ * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.
674
+ * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.
675
+ *
676
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
677
+ * @param screenName Screen name string to set.
678
+ */
679
+ async function setCurrentScreen$1(gtagFunction, initializationPromise, screenName, options) {
680
+ if (options && options.global) {
681
+ gtagFunction("set" /* GtagCommand.SET */, { 'screen_name': screenName });
682
+ return Promise.resolve();
683
+ }
684
+ else {
685
+ const measurementId = await initializationPromise;
686
+ gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
687
+ update: true,
688
+ 'screen_name': screenName
689
+ });
690
+ }
691
+ }
692
+ /**
693
+ * Set user_id parameter for this Google Analytics ID.
694
+ *
695
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
696
+ * @param id User ID string to set
697
+ */
698
+ async function setUserId$1(gtagFunction, initializationPromise, id, options) {
699
+ if (options && options.global) {
700
+ gtagFunction("set" /* GtagCommand.SET */, { 'user_id': id });
701
+ return Promise.resolve();
702
+ }
703
+ else {
704
+ const measurementId = await initializationPromise;
705
+ gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
706
+ update: true,
707
+ 'user_id': id
708
+ });
709
+ }
710
+ }
711
+ /**
712
+ * Set all other user properties other than user_id and screen_name.
713
+ *
714
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
715
+ * @param properties Map of user properties to set
716
+ */
717
+ async function setUserProperties$1(gtagFunction, initializationPromise, properties, options) {
718
+ if (options && options.global) {
719
+ const flatProperties = {};
720
+ for (const key of Object.keys(properties)) {
721
+ // use dot notation for merge behavior in gtag.js
722
+ flatProperties[`user_properties.${key}`] = properties[key];
723
+ }
724
+ gtagFunction("set" /* GtagCommand.SET */, flatProperties);
725
+ return Promise.resolve();
726
+ }
727
+ else {
728
+ const measurementId = await initializationPromise;
729
+ gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
730
+ update: true,
731
+ 'user_properties': properties
732
+ });
733
+ }
734
+ }
735
+ /**
736
+ * Retrieves a unique Google Analytics identifier for the web client.
737
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
738
+ *
739
+ * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
740
+ */
741
+ async function internalGetGoogleAnalyticsClientId(gtagFunction, initializationPromise) {
742
+ const measurementId = await initializationPromise;
743
+ return new Promise((resolve, reject) => {
744
+ gtagFunction("get" /* GtagCommand.GET */, measurementId, 'client_id', (clientId) => {
745
+ if (!clientId) {
746
+ reject(ERROR_FACTORY.create("no-client-id" /* AnalyticsError.NO_CLIENT_ID */));
747
+ }
748
+ resolve(clientId);
749
+ });
750
+ });
751
+ }
752
+ /**
753
+ * Set whether collection is enabled for this ID.
754
+ *
755
+ * @param enabled If true, collection is enabled for this ID.
756
+ */
757
+ async function setAnalyticsCollectionEnabled$1(initializationPromise, enabled) {
758
+ const measurementId = await initializationPromise;
759
+ window[`ga-disable-${measurementId}`] = !enabled;
760
+ }
761
+ /**
762
+ * Consent parameters to default to during 'gtag' initialization.
763
+ */
764
+ let defaultConsentSettingsForInit;
765
+ /**
766
+ * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of
767
+ * analytics.
768
+ *
769
+ * @param consentSettings Maps the applicable end user consent state for gtag.js.
770
+ */
771
+ function _setConsentDefaultForInit(consentSettings) {
772
+ defaultConsentSettingsForInit = consentSettings;
773
+ }
774
+ /**
775
+ * Sets the variable `defaultEventParametersForInit` for use in the initialization of
776
+ * analytics.
777
+ *
778
+ * @param customParams Any custom params the user may pass to gtag.js.
779
+ */
780
+ function _setDefaultEventParametersForInit(customParams) {
781
+ defaultEventParametersForInit = customParams;
782
+ }
783
+
784
+ /**
785
+ * @license
786
+ * Copyright 2020 Google LLC
787
+ *
788
+ * Licensed under the Apache License, Version 2.0 (the "License");
789
+ * you may not use this file except in compliance with the License.
790
+ * You may obtain a copy of the License at
791
+ *
792
+ * http://www.apache.org/licenses/LICENSE-2.0
793
+ *
794
+ * Unless required by applicable law or agreed to in writing, software
795
+ * distributed under the License is distributed on an "AS IS" BASIS,
796
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
797
+ * See the License for the specific language governing permissions and
798
+ * limitations under the License.
799
+ */
800
+ async function validateIndexedDB() {
801
+ if (!util.isIndexedDBAvailable()) {
802
+ logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */, {
803
+ errorInfo: 'IndexedDB is not available in this environment.'
804
+ }).message);
805
+ return false;
806
+ }
807
+ else {
808
+ try {
809
+ await util.validateIndexedDBOpenable();
810
+ }
811
+ catch (e) {
812
+ logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */, {
813
+ errorInfo: e?.toString()
814
+ }).message);
815
+ return false;
816
+ }
817
+ }
818
+ return true;
819
+ }
820
+ /**
821
+ * Initialize the analytics instance in gtag.js by calling config command with fid.
822
+ *
823
+ * NOTE: We combine analytics initialization and setting fid together because we want fid to be
824
+ * part of the `page_view` event that's sent during the initialization
825
+ * @param app Firebase app
826
+ * @param gtagCore The gtag function that's not wrapped.
827
+ * @param dynamicConfigPromisesList Array of all dynamic config promises.
828
+ * @param measurementIdToAppId Maps measurementID to appID.
829
+ * @param installations _FirebaseInstallationsInternal instance.
830
+ *
831
+ * @returns Measurement ID.
832
+ */
833
+ async function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) {
834
+ const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);
835
+ // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.
836
+ dynamicConfigPromise
837
+ .then(config => {
838
+ measurementIdToAppId[config.measurementId] = config.appId;
839
+ if (app.options.measurementId &&
840
+ config.measurementId !== app.options.measurementId) {
841
+ logger.warn(`The measurement ID in the local Firebase config (${app.options.measurementId})` +
842
+ ` does not match the measurement ID fetched from the server (${config.measurementId}).` +
843
+ ` To ensure analytics events are always sent to the correct Analytics property,` +
844
+ ` update the` +
845
+ ` measurement ID field in the local config or remove it from the local config.`);
846
+ }
847
+ })
848
+ .catch(e => logger.error(e));
849
+ // Add to list to track state of all dynamic config promises.
850
+ dynamicConfigPromisesList.push(dynamicConfigPromise);
851
+ const fidPromise = validateIndexedDB().then(envIsValid => {
852
+ if (envIsValid) {
853
+ return installations.getId();
854
+ }
855
+ else {
856
+ return undefined;
857
+ }
858
+ });
859
+ const [dynamicConfig, fid] = await Promise.all([
860
+ dynamicConfigPromise,
861
+ fidPromise
862
+ ]);
863
+ // Detect if user has already put the gtag <script> tag on this page with the passed in
864
+ // data layer name.
865
+ if (!findGtagScriptOnPage(dataLayerName)) {
866
+ insertScriptTag(dataLayerName, dynamicConfig.measurementId);
867
+ }
868
+ // Detects if there are consent settings that need to be configured.
869
+ if (defaultConsentSettingsForInit) {
870
+ gtagCore("consent" /* GtagCommand.CONSENT */, 'default', defaultConsentSettingsForInit);
871
+ _setConsentDefaultForInit(undefined);
872
+ }
873
+ // This command initializes gtag.js and only needs to be called once for the entire web app,
874
+ // but since it is idempotent, we can call it multiple times.
875
+ // We keep it together with other initialization logic for better code structure.
876
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
877
+ gtagCore('js', new Date());
878
+ // User config added first. We don't want users to accidentally overwrite
879
+ // base Firebase config properties.
880
+ const configProperties = options?.config ?? {};
881
+ // guard against developers accidentally setting properties with prefix `firebase_`
882
+ configProperties[ORIGIN_KEY] = 'firebase';
883
+ configProperties.update = true;
884
+ if (fid != null) {
885
+ configProperties[GA_FID_KEY] = fid;
886
+ }
887
+ // It should be the first config command called on this GA-ID
888
+ // Initialize this GA-ID and set FID on it using the gtag config API.
889
+ // Note: This will trigger a page_view event unless 'send_page_view' is set to false in
890
+ // `configProperties`.
891
+ gtagCore("config" /* GtagCommand.CONFIG */, dynamicConfig.measurementId, configProperties);
892
+ // Detects if there is data that will be set on every event logged from the SDK.
893
+ if (defaultEventParametersForInit) {
894
+ gtagCore("set" /* GtagCommand.SET */, defaultEventParametersForInit);
895
+ _setDefaultEventParametersForInit(undefined);
896
+ }
897
+ return dynamicConfig.measurementId;
898
+ }
899
+
900
+ /**
901
+ * @license
902
+ * Copyright 2019 Google LLC
903
+ *
904
+ * Licensed under the Apache License, Version 2.0 (the "License");
905
+ * you may not use this file except in compliance with the License.
906
+ * You may obtain a copy of the License at
907
+ *
908
+ * http://www.apache.org/licenses/LICENSE-2.0
909
+ *
910
+ * Unless required by applicable law or agreed to in writing, software
911
+ * distributed under the License is distributed on an "AS IS" BASIS,
912
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
913
+ * See the License for the specific language governing permissions and
914
+ * limitations under the License.
915
+ */
916
+ /**
917
+ * Analytics Service class.
918
+ */
919
+ class AnalyticsService {
920
+ constructor(app) {
921
+ this.app = app;
922
+ }
923
+ _delete() {
924
+ delete initializationPromisesMap[this.app.options.appId];
925
+ return Promise.resolve();
926
+ }
927
+ }
928
+ /**
929
+ * Maps appId to full initialization promise. Wrapped gtag calls must wait on
930
+ * all or some of these, depending on the call's `send_to` param and the status
931
+ * of the dynamic config fetches (see below).
932
+ */
933
+ let initializationPromisesMap = {};
934
+ /**
935
+ * List of dynamic config fetch promises. In certain cases, wrapped gtag calls
936
+ * wait on all these to be complete in order to determine if it can selectively
937
+ * wait for only certain initialization (FID) promises or if it must wait for all.
938
+ */
939
+ let dynamicConfigPromisesList = [];
940
+ /**
941
+ * Maps fetched measurementIds to appId. Populated when the app's dynamic config
942
+ * fetch completes. If already populated, gtag config calls can use this to
943
+ * selectively wait for only this app's initialization promise (FID) instead of all
944
+ * initialization promises.
945
+ */
946
+ const measurementIdToAppId = {};
947
+ /**
948
+ * Name for window global data layer array used by GA: defaults to 'dataLayer'.
949
+ */
950
+ let dataLayerName = 'dataLayer';
951
+ /**
952
+ * Name for window global gtag function used by GA: defaults to 'gtag'.
953
+ */
954
+ let gtagName = 'gtag';
955
+ /**
956
+ * Reproduction of standard gtag function or reference to existing
957
+ * gtag function on window object.
958
+ */
959
+ let gtagCoreFunction;
960
+ /**
961
+ * Wrapper around gtag function that ensures FID is sent with all
962
+ * relevant event and config calls.
963
+ */
964
+ let wrappedGtagFunction;
965
+ /**
966
+ * Flag to ensure page initialization steps (creation or wrapping of
967
+ * dataLayer and gtag script) are only run once per page load.
968
+ */
969
+ let globalInitDone = false;
970
+ /**
971
+ * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.
972
+ * Intended to be used if `gtag.js` script has been installed on
973
+ * this page independently of Firebase Analytics, and is using non-default
974
+ * names for either the `gtag` function or for `dataLayer`.
975
+ * Must be called before calling `getAnalytics()` or it won't
976
+ * have any effect.
977
+ *
978
+ * @public
979
+ *
980
+ * @param options - Custom gtag and dataLayer names.
981
+ */
982
+ function settings(options) {
983
+ if (globalInitDone) {
984
+ throw ERROR_FACTORY.create("already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */);
985
+ }
986
+ if (options.dataLayerName) {
987
+ dataLayerName = options.dataLayerName;
988
+ }
989
+ if (options.gtagName) {
990
+ gtagName = options.gtagName;
991
+ }
992
+ }
993
+ /**
994
+ * Returns true if no environment mismatch is found.
995
+ * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT
996
+ * error that also lists details for each mismatch found.
997
+ */
998
+ function warnOnBrowserContextMismatch() {
999
+ const mismatchedEnvMessages = [];
1000
+ if (util.isBrowserExtension()) {
1001
+ mismatchedEnvMessages.push('This is a browser extension environment.');
1002
+ }
1003
+ if (!util.areCookiesEnabled()) {
1004
+ mismatchedEnvMessages.push('Cookies are not available.');
1005
+ }
1006
+ if (mismatchedEnvMessages.length > 0) {
1007
+ const details = mismatchedEnvMessages
1008
+ .map((message, index) => `(${index + 1}) ${message}`)
1009
+ .join(' ');
1010
+ const err = ERROR_FACTORY.create("invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */, {
1011
+ errorInfo: details
1012
+ });
1013
+ logger.warn(err.message);
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Analytics instance factory.
1018
+ * @internal
1019
+ */
1020
+ function factory(app, installations, options) {
1021
+ warnOnBrowserContextMismatch();
1022
+ const appId = app.options.appId;
1023
+ if (!appId) {
1024
+ throw ERROR_FACTORY.create("no-app-id" /* AnalyticsError.NO_APP_ID */);
1025
+ }
1026
+ if (!app.options.apiKey) {
1027
+ if (app.options.measurementId) {
1028
+ logger.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest` +
1029
+ ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +
1030
+ ` provided in the "measurementId" field in the local Firebase config.`);
1031
+ }
1032
+ else {
1033
+ throw ERROR_FACTORY.create("no-api-key" /* AnalyticsError.NO_API_KEY */);
1034
+ }
1035
+ }
1036
+ if (initializationPromisesMap[appId] != null) {
1037
+ throw ERROR_FACTORY.create("already-exists" /* AnalyticsError.ALREADY_EXISTS */, {
1038
+ id: appId
1039
+ });
1040
+ }
1041
+ if (!globalInitDone) {
1042
+ // Steps here should only be done once per page: creation or wrapping
1043
+ // of dataLayer and global gtag function.
1044
+ getOrCreateDataLayer(dataLayerName);
1045
+ const { wrappedGtag, gtagCore } = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName);
1046
+ wrappedGtagFunction = wrappedGtag;
1047
+ gtagCoreFunction = gtagCore;
1048
+ globalInitDone = true;
1049
+ }
1050
+ // Async but non-blocking.
1051
+ // This map reflects the completion state of all promises for each appId.
1052
+ initializationPromisesMap[appId] = _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName, options);
1053
+ const analyticsInstance = new AnalyticsService(app);
1054
+ return analyticsInstance;
1055
+ }
1056
+
1057
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1058
+ /**
1059
+ * Returns an {@link Analytics} instance for the given app.
1060
+ *
1061
+ * @public
1062
+ *
1063
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1064
+ */
1065
+ function getAnalytics(app$1 = app.getApp()) {
1066
+ app$1 = util.getModularInstance(app$1);
1067
+ // Dependencies
1068
+ const analyticsProvider = app._getProvider(app$1, ANALYTICS_TYPE);
1069
+ if (analyticsProvider.isInitialized()) {
1070
+ return analyticsProvider.getImmediate();
1071
+ }
1072
+ return initializeAnalytics(app$1);
1073
+ }
1074
+ /**
1075
+ * Returns an {@link Analytics} instance for the given app.
1076
+ *
1077
+ * @public
1078
+ *
1079
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1080
+ */
1081
+ function initializeAnalytics(app$1, options = {}) {
1082
+ // Dependencies
1083
+ const analyticsProvider = app._getProvider(app$1, ANALYTICS_TYPE);
1084
+ if (analyticsProvider.isInitialized()) {
1085
+ const existingInstance = analyticsProvider.getImmediate();
1086
+ if (util.deepEqual(options, analyticsProvider.getOptions())) {
1087
+ return existingInstance;
1088
+ }
1089
+ else {
1090
+ throw ERROR_FACTORY.create("already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */);
1091
+ }
1092
+ }
1093
+ const analyticsInstance = analyticsProvider.initialize({ options });
1094
+ return analyticsInstance;
1095
+ }
1096
+ /**
1097
+ * This is a public static method provided to users that wraps four different checks:
1098
+ *
1099
+ * 1. Check if it's not a browser extension environment.
1100
+ * 2. Check if cookies are enabled in current browser.
1101
+ * 3. Check if IndexedDB is supported by the browser environment.
1102
+ * 4. Check if the current browser context is valid for using `IndexedDB.open()`.
1103
+ *
1104
+ * @public
1105
+ *
1106
+ */
1107
+ async function isSupported() {
1108
+ if (util.isBrowserExtension()) {
1109
+ return false;
1110
+ }
1111
+ if (!util.areCookiesEnabled()) {
1112
+ return false;
1113
+ }
1114
+ if (!util.isIndexedDBAvailable()) {
1115
+ return false;
1116
+ }
1117
+ try {
1118
+ const isDBOpenable = await util.validateIndexedDBOpenable();
1119
+ return isDBOpenable;
1120
+ }
1121
+ catch (error) {
1122
+ return false;
1123
+ }
1124
+ }
1125
+ /**
1126
+ * Use gtag `config` command to set `screen_name`.
1127
+ *
1128
+ * @public
1129
+ *
1130
+ * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.
1131
+ * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.
1132
+ *
1133
+ * @param analyticsInstance - The {@link Analytics} instance.
1134
+ * @param screenName - Screen name to set.
1135
+ */
1136
+ function setCurrentScreen(analyticsInstance, screenName, options) {
1137
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1138
+ setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(e => logger.error(e));
1139
+ }
1140
+ /**
1141
+ * Retrieves a unique Google Analytics identifier for the web client.
1142
+ * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
1143
+ *
1144
+ * @public
1145
+ *
1146
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
1147
+ */
1148
+ async function getGoogleAnalyticsClientId(analyticsInstance) {
1149
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1150
+ return internalGetGoogleAnalyticsClientId(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId]);
1151
+ }
1152
+ /**
1153
+ * Use gtag `config` command to set `user_id`.
1154
+ *
1155
+ * @public
1156
+ *
1157
+ * @param analyticsInstance - The {@link Analytics} instance.
1158
+ * @param id - User ID to set.
1159
+ */
1160
+ function setUserId(analyticsInstance, id, options) {
1161
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1162
+ setUserId$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], id, options).catch(e => logger.error(e));
1163
+ }
1164
+ /**
1165
+ * Use gtag `config` command to set all params specified.
1166
+ *
1167
+ * @public
1168
+ */
1169
+ function setUserProperties(analyticsInstance, properties, options) {
1170
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1171
+ setUserProperties$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], properties, options).catch(e => logger.error(e));
1172
+ }
1173
+ /**
1174
+ * Sets whether Google Analytics collection is enabled for this app on this device.
1175
+ * Sets global `window['ga-disable-analyticsId'] = true;`
1176
+ *
1177
+ * @public
1178
+ *
1179
+ * @param analyticsInstance - The {@link Analytics} instance.
1180
+ * @param enabled - If true, enables collection, if false, disables it.
1181
+ */
1182
+ function setAnalyticsCollectionEnabled(analyticsInstance, enabled) {
1183
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1184
+ setAnalyticsCollectionEnabled$1(initializationPromisesMap[analyticsInstance.app.options.appId], enabled).catch(e => logger.error(e));
1185
+ }
1186
+ /**
1187
+ * Adds data that will be set on every event logged from the SDK, including automatic ones.
1188
+ * With gtag's "set" command, the values passed persist on the current page and are passed with
1189
+ * all subsequent events.
1190
+ * @public
1191
+ * @param customParams - Any custom params the user may pass to gtag.js.
1192
+ */
1193
+ function setDefaultEventParameters(customParams) {
1194
+ // Check if reference to existing gtag function on window object exists
1195
+ if (wrappedGtagFunction) {
1196
+ wrappedGtagFunction("set" /* GtagCommand.SET */, customParams);
1197
+ }
1198
+ else {
1199
+ _setDefaultEventParametersForInit(customParams);
1200
+ }
1201
+ }
1202
+ /**
1203
+ * Sends a Google Analytics event with given `eventParams`. This method
1204
+ * automatically associates this logged event with this Firebase web
1205
+ * app instance on this device.
1206
+ * List of official event parameters can be found in the gtag.js
1207
+ * reference documentation:
1208
+ * {@link https://developers.google.com/gtagjs/reference/ga4-events
1209
+ * | the GA4 reference documentation}.
1210
+ *
1211
+ * @public
1212
+ */
1213
+ function logEvent(analyticsInstance, eventName, eventParams, options) {
1214
+ analyticsInstance = util.getModularInstance(analyticsInstance);
1215
+ logEvent$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], eventName, eventParams, options).catch(e => logger.error(e));
1216
+ }
1217
+ /**
1218
+ * Sets the applicable end user consent state for this web app across all gtag references once
1219
+ * Firebase Analytics is initialized.
1220
+ *
1221
+ * Use the {@link ConsentSettings} to specify individual consent type values. By default consent
1222
+ * types are set to "granted".
1223
+ * @public
1224
+ * @param consentSettings - Maps the applicable end user consent state for gtag.js.
1225
+ */
1226
+ function setConsent(consentSettings) {
1227
+ // Check if reference to existing gtag function on window object exists
1228
+ if (wrappedGtagFunction) {
1229
+ wrappedGtagFunction("consent" /* GtagCommand.CONSENT */, 'update', consentSettings);
1230
+ }
1231
+ else {
1232
+ _setConsentDefaultForInit(consentSettings);
1233
+ }
1234
+ }
1235
+
1236
+ const name = "@firebase/analytics";
1237
+ const version = "0.10.20";
1238
+
1239
+ /**
1240
+ * The Firebase Analytics Web SDK.
1241
+ * This SDK does not work in a Node.js environment.
1242
+ *
1243
+ * @packageDocumentation
1244
+ */
1245
+ function registerAnalytics() {
1246
+ app._registerComponent(new component.Component(ANALYTICS_TYPE, (container, { options: analyticsOptions }) => {
1247
+ // getImmediate for FirebaseApp will always succeed
1248
+ const app = container.getProvider('app').getImmediate();
1249
+ const installations = container
1250
+ .getProvider('installations-internal')
1251
+ .getImmediate();
1252
+ return factory(app, installations, analyticsOptions);
1253
+ }, "PUBLIC" /* ComponentType.PUBLIC */));
1254
+ app._registerComponent(new component.Component('analytics-internal', internalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
1255
+ app.registerVersion(name, version);
1256
+ // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
1257
+ app.registerVersion(name, version, 'cjs2020');
1258
+ function internalFactory(container) {
1259
+ try {
1260
+ const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();
1261
+ return {
1262
+ logEvent: (eventName, eventParams, options) => logEvent(analytics, eventName, eventParams, options),
1263
+ setUserProperties: (properties, options) => setUserProperties(analytics, properties, options)
1264
+ };
1265
+ }
1266
+ catch (e) {
1267
+ throw ERROR_FACTORY.create("interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */, {
1268
+ reason: e
1269
+ });
1270
+ }
1271
+ }
1272
+ }
1273
+ registerAnalytics();
1274
+
1275
+ exports.getAnalytics = getAnalytics;
1276
+ exports.getGoogleAnalyticsClientId = getGoogleAnalyticsClientId;
1277
+ exports.initializeAnalytics = initializeAnalytics;
1278
+ exports.isSupported = isSupported;
1279
+ exports.logEvent = logEvent;
1280
+ exports.setAnalyticsCollectionEnabled = setAnalyticsCollectionEnabled;
1281
+ exports.setConsent = setConsent;
1282
+ exports.setCurrentScreen = setCurrentScreen;
1283
+ exports.setDefaultEventParameters = setDefaultEventParameters;
1284
+ exports.setUserId = setUserId;
1285
+ exports.setUserProperties = setUserProperties;
1286
+ exports.settings = settings;
1287
+ //# sourceMappingURL=index.cjs.js.map