GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1363 lines
60 KiB

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