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