index.esm2017.js 53 KB

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