No Description
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.

index.esm.js 62KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. import { ErrorFactory, areCookiesEnabled, isIndexedDBAvailable, validateIndexedDBOpenable, getModularInstance, deepEqual } from '@firebase/util';
  2. import { Logger, LogLevel } from '@firebase/logger';
  3. import { __spreadArray, __assign } from 'tslib';
  4. import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';
  5. import { Component } from '@firebase/component';
  6. import '@firebase/installations';
  7. var name = "@firebase/performance";
  8. var version = "0.6.1";
  9. /**
  10. * @license
  11. * Copyright 2020 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. var SDK_VERSION = version;
  26. /** The prefix for start User Timing marks used for creating Traces. */
  27. var TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';
  28. /** The prefix for stop User Timing marks used for creating Traces. */
  29. var TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';
  30. /** The prefix for User Timing measure used for creating Traces. */
  31. var TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';
  32. /** The prefix for out of the box page load Trace name. */
  33. var OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';
  34. var FIRST_PAINT_COUNTER_NAME = '_fp';
  35. var FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';
  36. var FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';
  37. var CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';
  38. var CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire';
  39. var SERVICE = 'performance';
  40. var SERVICE_NAME = 'Performance';
  41. /**
  42. * @license
  43. * Copyright 2020 Google LLC
  44. *
  45. * Licensed under the Apache License, Version 2.0 (the "License");
  46. * you may not use this file except in compliance with the License.
  47. * You may obtain a copy of the License at
  48. *
  49. * http://www.apache.org/licenses/LICENSE-2.0
  50. *
  51. * Unless required by applicable law or agreed to in writing, software
  52. * distributed under the License is distributed on an "AS IS" BASIS,
  53. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  54. * See the License for the specific language governing permissions and
  55. * limitations under the License.
  56. */
  57. var _a;
  58. var ERROR_DESCRIPTION_MAP = (_a = {},
  59. _a["trace started" /* ErrorCode.TRACE_STARTED_BEFORE */] = 'Trace {$traceName} was started before.',
  60. _a["trace stopped" /* ErrorCode.TRACE_STOPPED_BEFORE */] = 'Trace {$traceName} is not running.',
  61. _a["nonpositive trace startTime" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */] = 'Trace {$traceName} startTime should be positive.',
  62. _a["nonpositive trace duration" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */] = 'Trace {$traceName} duration should be positive.',
  63. _a["no window" /* ErrorCode.NO_WINDOW */] = 'Window is not available.',
  64. _a["no app id" /* ErrorCode.NO_APP_ID */] = 'App id is not available.',
  65. _a["no project id" /* ErrorCode.NO_PROJECT_ID */] = 'Project id is not available.',
  66. _a["no api key" /* ErrorCode.NO_API_KEY */] = 'Api key is not available.',
  67. _a["invalid cc log" /* ErrorCode.INVALID_CC_LOG */] = 'Attempted to queue invalid cc event',
  68. _a["FB not default" /* ErrorCode.FB_NOT_DEFAULT */] = 'Performance can only start when Firebase app instance is the default one.',
  69. _a["RC response not ok" /* ErrorCode.RC_NOT_OK */] = 'RC response is not ok',
  70. _a["invalid attribute name" /* ErrorCode.INVALID_ATTRIBUTE_NAME */] = 'Attribute name {$attributeName} is invalid.',
  71. _a["invalid attribute value" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */] = 'Attribute value {$attributeValue} is invalid.',
  72. _a["invalid custom metric name" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */] = 'Custom metric name {$customMetricName} is invalid',
  73. _a["invalid String merger input" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */] = 'Input for String merger is invalid, contact support team to resolve.',
  74. _a["already initialized" /* ErrorCode.ALREADY_INITIALIZED */] = 'initializePerformance() has already been called with ' +
  75. 'different options. To avoid this error, call initializePerformance() with the ' +
  76. 'same options as when it was originally called, or call getPerformance() to return the' +
  77. ' already initialized instance.',
  78. _a);
  79. var ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
  80. /**
  81. * @license
  82. * Copyright 2020 Google LLC
  83. *
  84. * Licensed under the Apache License, Version 2.0 (the "License");
  85. * you may not use this file except in compliance with the License.
  86. * You may obtain a copy of the License at
  87. *
  88. * http://www.apache.org/licenses/LICENSE-2.0
  89. *
  90. * Unless required by applicable law or agreed to in writing, software
  91. * distributed under the License is distributed on an "AS IS" BASIS,
  92. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  93. * See the License for the specific language governing permissions and
  94. * limitations under the License.
  95. */
  96. var consoleLogger = new Logger(SERVICE_NAME);
  97. consoleLogger.logLevel = LogLevel.INFO;
  98. /**
  99. * @license
  100. * Copyright 2020 Google LLC
  101. *
  102. * Licensed under the Apache License, Version 2.0 (the "License");
  103. * you may not use this file except in compliance with the License.
  104. * You may obtain a copy of the License at
  105. *
  106. * http://www.apache.org/licenses/LICENSE-2.0
  107. *
  108. * Unless required by applicable law or agreed to in writing, software
  109. * distributed under the License is distributed on an "AS IS" BASIS,
  110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  111. * See the License for the specific language governing permissions and
  112. * limitations under the License.
  113. */
  114. var apiInstance;
  115. var windowInstance;
  116. /**
  117. * This class holds a reference to various browser related objects injected by
  118. * set methods.
  119. */
  120. var Api = /** @class */ (function () {
  121. function Api(window) {
  122. this.window = window;
  123. if (!window) {
  124. throw ERROR_FACTORY.create("no window" /* ErrorCode.NO_WINDOW */);
  125. }
  126. this.performance = window.performance;
  127. this.PerformanceObserver = window.PerformanceObserver;
  128. this.windowLocation = window.location;
  129. this.navigator = window.navigator;
  130. this.document = window.document;
  131. if (this.navigator && this.navigator.cookieEnabled) {
  132. // If user blocks cookies on the browser, accessing localStorage will
  133. // throw an exception.
  134. this.localStorage = window.localStorage;
  135. }
  136. if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) {
  137. this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;
  138. }
  139. }
  140. Api.prototype.getUrl = function () {
  141. // Do not capture the string query part of url.
  142. return this.windowLocation.href.split('?')[0];
  143. };
  144. Api.prototype.mark = function (name) {
  145. if (!this.performance || !this.performance.mark) {
  146. return;
  147. }
  148. this.performance.mark(name);
  149. };
  150. Api.prototype.measure = function (measureName, mark1, mark2) {
  151. if (!this.performance || !this.performance.measure) {
  152. return;
  153. }
  154. this.performance.measure(measureName, mark1, mark2);
  155. };
  156. Api.prototype.getEntriesByType = function (type) {
  157. if (!this.performance || !this.performance.getEntriesByType) {
  158. return [];
  159. }
  160. return this.performance.getEntriesByType(type);
  161. };
  162. Api.prototype.getEntriesByName = function (name) {
  163. if (!this.performance || !this.performance.getEntriesByName) {
  164. return [];
  165. }
  166. return this.performance.getEntriesByName(name);
  167. };
  168. Api.prototype.getTimeOrigin = function () {
  169. // Polyfill the time origin with performance.timing.navigationStart.
  170. return (this.performance &&
  171. (this.performance.timeOrigin || this.performance.timing.navigationStart));
  172. };
  173. Api.prototype.requiredApisAvailable = function () {
  174. if (!fetch || !Promise || !areCookiesEnabled()) {
  175. consoleLogger.info('Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.');
  176. return false;
  177. }
  178. if (!isIndexedDBAvailable()) {
  179. consoleLogger.info('IndexedDB is not supported by current browswer');
  180. return false;
  181. }
  182. return true;
  183. };
  184. Api.prototype.setupObserver = function (entryType, callback) {
  185. if (!this.PerformanceObserver) {
  186. return;
  187. }
  188. var observer = new this.PerformanceObserver(function (list) {
  189. for (var _i = 0, _a = list.getEntries(); _i < _a.length; _i++) {
  190. var entry = _a[_i];
  191. // `entry` is a PerformanceEntry instance.
  192. callback(entry);
  193. }
  194. });
  195. // Start observing the entry types you care about.
  196. observer.observe({ entryTypes: [entryType] });
  197. };
  198. Api.getInstance = function () {
  199. if (apiInstance === undefined) {
  200. apiInstance = new Api(windowInstance);
  201. }
  202. return apiInstance;
  203. };
  204. return Api;
  205. }());
  206. function setupApi(window) {
  207. windowInstance = window;
  208. }
  209. /**
  210. * @license
  211. * Copyright 2020 Google LLC
  212. *
  213. * Licensed under the Apache License, Version 2.0 (the "License");
  214. * you may not use this file except in compliance with the License.
  215. * You may obtain a copy of the License at
  216. *
  217. * http://www.apache.org/licenses/LICENSE-2.0
  218. *
  219. * Unless required by applicable law or agreed to in writing, software
  220. * distributed under the License is distributed on an "AS IS" BASIS,
  221. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  222. * See the License for the specific language governing permissions and
  223. * limitations under the License.
  224. */
  225. var iid;
  226. function getIidPromise(installationsService) {
  227. var iidPromise = installationsService.getId();
  228. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  229. iidPromise.then(function (iidVal) {
  230. iid = iidVal;
  231. });
  232. return iidPromise;
  233. }
  234. // This method should be used after the iid is retrieved by getIidPromise method.
  235. function getIid() {
  236. return iid;
  237. }
  238. function getAuthTokenPromise(installationsService) {
  239. var authTokenPromise = installationsService.getToken();
  240. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  241. authTokenPromise.then(function (authTokenVal) {
  242. });
  243. return authTokenPromise;
  244. }
  245. /**
  246. * @license
  247. * Copyright 2020 Google LLC
  248. *
  249. * Licensed under the Apache License, Version 2.0 (the "License");
  250. * you may not use this file except in compliance with the License.
  251. * You may obtain a copy of the License at
  252. *
  253. * http://www.apache.org/licenses/LICENSE-2.0
  254. *
  255. * Unless required by applicable law or agreed to in writing, software
  256. * distributed under the License is distributed on an "AS IS" BASIS,
  257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  258. * See the License for the specific language governing permissions and
  259. * limitations under the License.
  260. */
  261. function mergeStrings(part1, part2) {
  262. var sizeDiff = part1.length - part2.length;
  263. if (sizeDiff < 0 || sizeDiff > 1) {
  264. throw ERROR_FACTORY.create("invalid String merger input" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */);
  265. }
  266. var resultArray = [];
  267. for (var i = 0; i < part1.length; i++) {
  268. resultArray.push(part1.charAt(i));
  269. if (part2.length > i) {
  270. resultArray.push(part2.charAt(i));
  271. }
  272. }
  273. return resultArray.join('');
  274. }
  275. /**
  276. * @license
  277. * Copyright 2019 Google LLC
  278. *
  279. * Licensed under the Apache License, Version 2.0 (the "License");
  280. * you may not use this file except in compliance with the License.
  281. * You may obtain a copy of the License at
  282. *
  283. * http://www.apache.org/licenses/LICENSE-2.0
  284. *
  285. * Unless required by applicable law or agreed to in writing, software
  286. * distributed under the License is distributed on an "AS IS" BASIS,
  287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  288. * See the License for the specific language governing permissions and
  289. * limitations under the License.
  290. */
  291. var settingsServiceInstance;
  292. var SettingsService = /** @class */ (function () {
  293. function SettingsService() {
  294. // The variable which controls logging of automatic traces and HTTP/S network monitoring.
  295. this.instrumentationEnabled = true;
  296. // The variable which controls logging of custom traces.
  297. this.dataCollectionEnabled = true;
  298. // Configuration flags set through remote config.
  299. this.loggingEnabled = false;
  300. // Sampling rate between 0 and 1.
  301. this.tracesSamplingRate = 1;
  302. this.networkRequestsSamplingRate = 1;
  303. // Address of logging service.
  304. this.logEndPointUrl = 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';
  305. // Performance event transport endpoint URL which should be compatible with proto3.
  306. // New Address for transport service, not configurable via Remote Config.
  307. this.flTransportEndpointUrl = mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');
  308. this.transportKey = mergeStrings('AzSC8r6ReiGqFMyfvgow', 'Iayx0u-XT3vksVM-pIV');
  309. // Source type for performance event logs.
  310. this.logSource = 462;
  311. // Flags which control per session logging of traces and network requests.
  312. this.logTraceAfterSampling = false;
  313. this.logNetworkAfterSampling = false;
  314. // TTL of config retrieved from remote config in hours.
  315. this.configTimeToLive = 12;
  316. }
  317. SettingsService.prototype.getFlTransportFullUrl = function () {
  318. return this.flTransportEndpointUrl.concat('?key=', this.transportKey);
  319. };
  320. SettingsService.getInstance = function () {
  321. if (settingsServiceInstance === undefined) {
  322. settingsServiceInstance = new SettingsService();
  323. }
  324. return settingsServiceInstance;
  325. };
  326. return SettingsService;
  327. }());
  328. /**
  329. * @license
  330. * Copyright 2020 Google LLC
  331. *
  332. * Licensed under the Apache License, Version 2.0 (the "License");
  333. * you may not use this file except in compliance with the License.
  334. * You may obtain a copy of the License at
  335. *
  336. * http://www.apache.org/licenses/LICENSE-2.0
  337. *
  338. * Unless required by applicable law or agreed to in writing, software
  339. * distributed under the License is distributed on an "AS IS" BASIS,
  340. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  341. * See the License for the specific language governing permissions and
  342. * limitations under the License.
  343. */
  344. var VisibilityState;
  345. (function (VisibilityState) {
  346. VisibilityState[VisibilityState["UNKNOWN"] = 0] = "UNKNOWN";
  347. VisibilityState[VisibilityState["VISIBLE"] = 1] = "VISIBLE";
  348. VisibilityState[VisibilityState["HIDDEN"] = 2] = "HIDDEN";
  349. })(VisibilityState || (VisibilityState = {}));
  350. var RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];
  351. var ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\w*$');
  352. var MAX_ATTRIBUTE_NAME_LENGTH = 40;
  353. var MAX_ATTRIBUTE_VALUE_LENGTH = 100;
  354. function getServiceWorkerStatus() {
  355. var navigator = Api.getInstance().navigator;
  356. if (navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) {
  357. if (navigator.serviceWorker.controller) {
  358. return 2 /* ServiceWorkerStatus.CONTROLLED */;
  359. }
  360. else {
  361. return 3 /* ServiceWorkerStatus.UNCONTROLLED */;
  362. }
  363. }
  364. else {
  365. return 1 /* ServiceWorkerStatus.UNSUPPORTED */;
  366. }
  367. }
  368. function getVisibilityState() {
  369. var document = Api.getInstance().document;
  370. var visibilityState = document.visibilityState;
  371. switch (visibilityState) {
  372. case 'visible':
  373. return VisibilityState.VISIBLE;
  374. case 'hidden':
  375. return VisibilityState.HIDDEN;
  376. default:
  377. return VisibilityState.UNKNOWN;
  378. }
  379. }
  380. function getEffectiveConnectionType() {
  381. var navigator = Api.getInstance().navigator;
  382. var navigatorConnection = navigator.connection;
  383. var effectiveType = navigatorConnection && navigatorConnection.effectiveType;
  384. switch (effectiveType) {
  385. case 'slow-2g':
  386. return 1 /* EffectiveConnectionType.CONNECTION_SLOW_2G */;
  387. case '2g':
  388. return 2 /* EffectiveConnectionType.CONNECTION_2G */;
  389. case '3g':
  390. return 3 /* EffectiveConnectionType.CONNECTION_3G */;
  391. case '4g':
  392. return 4 /* EffectiveConnectionType.CONNECTION_4G */;
  393. default:
  394. return 0 /* EffectiveConnectionType.UNKNOWN */;
  395. }
  396. }
  397. function isValidCustomAttributeName(name) {
  398. if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) {
  399. return false;
  400. }
  401. var matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(function (prefix) {
  402. return name.startsWith(prefix);
  403. });
  404. return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX);
  405. }
  406. function isValidCustomAttributeValue(value) {
  407. return value.length !== 0 && value.length <= MAX_ATTRIBUTE_VALUE_LENGTH;
  408. }
  409. /**
  410. * @license
  411. * Copyright 2020 Google LLC
  412. *
  413. * Licensed under the Apache License, Version 2.0 (the "License");
  414. * you may not use this file except in compliance with the License.
  415. * You may obtain a copy of the License at
  416. *
  417. * http://www.apache.org/licenses/LICENSE-2.0
  418. *
  419. * Unless required by applicable law or agreed to in writing, software
  420. * distributed under the License is distributed on an "AS IS" BASIS,
  421. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  422. * See the License for the specific language governing permissions and
  423. * limitations under the License.
  424. */
  425. function getAppId(firebaseApp) {
  426. var _a;
  427. var appId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.appId;
  428. if (!appId) {
  429. throw ERROR_FACTORY.create("no app id" /* ErrorCode.NO_APP_ID */);
  430. }
  431. return appId;
  432. }
  433. function getProjectId(firebaseApp) {
  434. var _a;
  435. var projectId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.projectId;
  436. if (!projectId) {
  437. throw ERROR_FACTORY.create("no project id" /* ErrorCode.NO_PROJECT_ID */);
  438. }
  439. return projectId;
  440. }
  441. function getApiKey(firebaseApp) {
  442. var _a;
  443. var apiKey = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.apiKey;
  444. if (!apiKey) {
  445. throw ERROR_FACTORY.create("no api key" /* ErrorCode.NO_API_KEY */);
  446. }
  447. return apiKey;
  448. }
  449. /**
  450. * @license
  451. * Copyright 2020 Google LLC
  452. *
  453. * Licensed under the Apache License, Version 2.0 (the "License");
  454. * you may not use this file except in compliance with the License.
  455. * You may obtain a copy of the License at
  456. *
  457. * http://www.apache.org/licenses/LICENSE-2.0
  458. *
  459. * Unless required by applicable law or agreed to in writing, software
  460. * distributed under the License is distributed on an "AS IS" BASIS,
  461. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  462. * See the License for the specific language governing permissions and
  463. * limitations under the License.
  464. */
  465. var REMOTE_CONFIG_SDK_VERSION = '0.0.1';
  466. // These values will be used if the remote config object is successfully
  467. // retrieved, but the template does not have these fields.
  468. var DEFAULT_CONFIGS = {
  469. loggingEnabled: true
  470. };
  471. var FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';
  472. function getConfig(performanceController, iid) {
  473. var config = getStoredConfig();
  474. if (config) {
  475. processConfig(config);
  476. return Promise.resolve();
  477. }
  478. return getRemoteConfig(performanceController, iid)
  479. .then(processConfig)
  480. .then(function (config) { return storeConfig(config); },
  481. /** Do nothing for error, use defaults set in settings service. */
  482. function () { });
  483. }
  484. function getStoredConfig() {
  485. var localStorage = Api.getInstance().localStorage;
  486. if (!localStorage) {
  487. return;
  488. }
  489. var expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);
  490. if (!expiryString || !configValid(expiryString)) {
  491. return;
  492. }
  493. var configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);
  494. if (!configStringified) {
  495. return;
  496. }
  497. try {
  498. var configResponse = JSON.parse(configStringified);
  499. return configResponse;
  500. }
  501. catch (_a) {
  502. return;
  503. }
  504. }
  505. function storeConfig(config) {
  506. var localStorage = Api.getInstance().localStorage;
  507. if (!config || !localStorage) {
  508. return;
  509. }
  510. localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));
  511. localStorage.setItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY, String(Date.now() +
  512. SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000));
  513. }
  514. var COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs';
  515. function getRemoteConfig(performanceController, iid) {
  516. // Perf needs auth token only to retrieve remote config.
  517. return getAuthTokenPromise(performanceController.installations)
  518. .then(function (authToken) {
  519. var projectId = getProjectId(performanceController.app);
  520. var apiKey = getApiKey(performanceController.app);
  521. var configEndPoint = "https://firebaseremoteconfig.googleapis.com/v1/projects/".concat(projectId, "/namespaces/fireperf:fetch?key=").concat(apiKey);
  522. var request = new Request(configEndPoint, {
  523. method: 'POST',
  524. headers: { Authorization: "".concat(FIS_AUTH_PREFIX, " ").concat(authToken) },
  525. /* eslint-disable camelcase */
  526. body: JSON.stringify({
  527. app_instance_id: iid,
  528. app_instance_id_token: authToken,
  529. app_id: getAppId(performanceController.app),
  530. app_version: SDK_VERSION,
  531. sdk_version: REMOTE_CONFIG_SDK_VERSION
  532. })
  533. /* eslint-enable camelcase */
  534. });
  535. return fetch(request).then(function (response) {
  536. if (response.ok) {
  537. return response.json();
  538. }
  539. // In case response is not ok. This will be caught by catch.
  540. throw ERROR_FACTORY.create("RC response not ok" /* ErrorCode.RC_NOT_OK */);
  541. });
  542. })
  543. .catch(function () {
  544. consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);
  545. return undefined;
  546. });
  547. }
  548. /**
  549. * Processes config coming either from calling RC or from local storage.
  550. * This method only runs if call is successful or config in storage
  551. * is valid.
  552. */
  553. function processConfig(config) {
  554. if (!config) {
  555. return config;
  556. }
  557. var settingsServiceInstance = SettingsService.getInstance();
  558. var entries = config.entries || {};
  559. if (entries.fpr_enabled !== undefined) {
  560. // TODO: Change the assignment of loggingEnabled once the received type is
  561. // known.
  562. settingsServiceInstance.loggingEnabled =
  563. String(entries.fpr_enabled) === 'true';
  564. }
  565. else {
  566. // Config retrieved successfully, but there is no fpr_enabled in template.
  567. // Use secondary configs value.
  568. settingsServiceInstance.loggingEnabled = DEFAULT_CONFIGS.loggingEnabled;
  569. }
  570. if (entries.fpr_log_source) {
  571. settingsServiceInstance.logSource = Number(entries.fpr_log_source);
  572. }
  573. else if (DEFAULT_CONFIGS.logSource) {
  574. settingsServiceInstance.logSource = DEFAULT_CONFIGS.logSource;
  575. }
  576. if (entries.fpr_log_endpoint_url) {
  577. settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;
  578. }
  579. else if (DEFAULT_CONFIGS.logEndPointUrl) {
  580. settingsServiceInstance.logEndPointUrl = DEFAULT_CONFIGS.logEndPointUrl;
  581. }
  582. // Key from Remote Config has to be non-empty string, otherwsie use local value.
  583. if (entries.fpr_log_transport_key) {
  584. settingsServiceInstance.transportKey = entries.fpr_log_transport_key;
  585. }
  586. else if (DEFAULT_CONFIGS.transportKey) {
  587. settingsServiceInstance.transportKey = DEFAULT_CONFIGS.transportKey;
  588. }
  589. if (entries.fpr_vc_network_request_sampling_rate !== undefined) {
  590. settingsServiceInstance.networkRequestsSamplingRate = Number(entries.fpr_vc_network_request_sampling_rate);
  591. }
  592. else if (DEFAULT_CONFIGS.networkRequestsSamplingRate !== undefined) {
  593. settingsServiceInstance.networkRequestsSamplingRate =
  594. DEFAULT_CONFIGS.networkRequestsSamplingRate;
  595. }
  596. if (entries.fpr_vc_trace_sampling_rate !== undefined) {
  597. settingsServiceInstance.tracesSamplingRate = Number(entries.fpr_vc_trace_sampling_rate);
  598. }
  599. else if (DEFAULT_CONFIGS.tracesSamplingRate !== undefined) {
  600. settingsServiceInstance.tracesSamplingRate =
  601. DEFAULT_CONFIGS.tracesSamplingRate;
  602. }
  603. // Set the per session trace and network logging flags.
  604. settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(settingsServiceInstance.tracesSamplingRate);
  605. settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(settingsServiceInstance.networkRequestsSamplingRate);
  606. return config;
  607. }
  608. function configValid(expiry) {
  609. return Number(expiry) > Date.now();
  610. }
  611. function shouldLogAfterSampling(samplingRate) {
  612. return Math.random() <= samplingRate;
  613. }
  614. /**
  615. * @license
  616. * Copyright 2020 Google LLC
  617. *
  618. * Licensed under the Apache License, Version 2.0 (the "License");
  619. * you may not use this file except in compliance with the License.
  620. * You may obtain a copy of the License at
  621. *
  622. * http://www.apache.org/licenses/LICENSE-2.0
  623. *
  624. * Unless required by applicable law or agreed to in writing, software
  625. * distributed under the License is distributed on an "AS IS" BASIS,
  626. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  627. * See the License for the specific language governing permissions and
  628. * limitations under the License.
  629. */
  630. var initializationStatus = 1 /* InitializationStatus.notInitialized */;
  631. var initializationPromise;
  632. function getInitializationPromise(performanceController) {
  633. initializationStatus = 2 /* InitializationStatus.initializationPending */;
  634. initializationPromise =
  635. initializationPromise || initializePerf(performanceController);
  636. return initializationPromise;
  637. }
  638. function isPerfInitialized() {
  639. return initializationStatus === 3 /* InitializationStatus.initialized */;
  640. }
  641. function initializePerf(performanceController) {
  642. return getDocumentReadyComplete()
  643. .then(function () { return getIidPromise(performanceController.installations); })
  644. .then(function (iid) { return getConfig(performanceController, iid); })
  645. .then(function () { return changeInitializationStatus(); }, function () { return changeInitializationStatus(); });
  646. }
  647. /**
  648. * Returns a promise which resolves whenever the document readystate is complete or
  649. * immediately if it is called after page load complete.
  650. */
  651. function getDocumentReadyComplete() {
  652. var document = Api.getInstance().document;
  653. return new Promise(function (resolve) {
  654. if (document && document.readyState !== 'complete') {
  655. var handler_1 = function () {
  656. if (document.readyState === 'complete') {
  657. document.removeEventListener('readystatechange', handler_1);
  658. resolve();
  659. }
  660. };
  661. document.addEventListener('readystatechange', handler_1);
  662. }
  663. else {
  664. resolve();
  665. }
  666. });
  667. }
  668. function changeInitializationStatus() {
  669. initializationStatus = 3 /* InitializationStatus.initialized */;
  670. }
  671. /**
  672. * @license
  673. * Copyright 2020 Google LLC
  674. *
  675. * Licensed under the Apache License, Version 2.0 (the "License");
  676. * you may not use this file except in compliance with the License.
  677. * You may obtain a copy of the License at
  678. *
  679. * http://www.apache.org/licenses/LICENSE-2.0
  680. *
  681. * Unless required by applicable law or agreed to in writing, software
  682. * distributed under the License is distributed on an "AS IS" BASIS,
  683. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  684. * See the License for the specific language governing permissions and
  685. * limitations under the License.
  686. */
  687. var DEFAULT_SEND_INTERVAL_MS = 10 * 1000;
  688. var INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;
  689. // If end point does not work, the call will be tried for these many times.
  690. var DEFAULT_REMAINING_TRIES = 3;
  691. var MAX_EVENT_COUNT_PER_REQUEST = 1000;
  692. var remainingTries = DEFAULT_REMAINING_TRIES;
  693. /* eslint-enable camelcase */
  694. var queue = [];
  695. var isTransportSetup = false;
  696. function setupTransportService() {
  697. if (!isTransportSetup) {
  698. processQueue(INITIAL_SEND_TIME_DELAY_MS);
  699. isTransportSetup = true;
  700. }
  701. }
  702. function processQueue(timeOffset) {
  703. setTimeout(function () {
  704. // If there is no remainingTries left, stop retrying.
  705. if (remainingTries === 0) {
  706. return;
  707. }
  708. // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again.
  709. if (!queue.length) {
  710. return processQueue(DEFAULT_SEND_INTERVAL_MS);
  711. }
  712. dispatchQueueEvents();
  713. }, timeOffset);
  714. }
  715. function dispatchQueueEvents() {
  716. // Extract events up to the maximum cap of single logRequest from top of "official queue".
  717. // The staged events will be used for current logRequest attempt, remaining events will be kept
  718. // for next attempt.
  719. var staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);
  720. /* eslint-disable camelcase */
  721. // We will pass the JSON serialized event to the backend.
  722. var log_event = staged.map(function (evt) { return ({
  723. source_extension_json_proto3: evt.message,
  724. event_time_ms: String(evt.eventTime)
  725. }); });
  726. var data = {
  727. request_time_ms: String(Date.now()),
  728. client_info: {
  729. client_type: 1,
  730. js_client_info: {}
  731. },
  732. log_source: SettingsService.getInstance().logSource,
  733. log_event: log_event
  734. };
  735. /* eslint-enable camelcase */
  736. sendEventsToFl(data, staged).catch(function () {
  737. // If the request fails for some reason, add the events that were attempted
  738. // back to the primary queue to retry later.
  739. queue = __spreadArray(__spreadArray([], staged, true), queue, true);
  740. remainingTries--;
  741. consoleLogger.info("Tries left: ".concat(remainingTries, "."));
  742. processQueue(DEFAULT_SEND_INTERVAL_MS);
  743. });
  744. }
  745. function sendEventsToFl(data, staged) {
  746. return postToFlEndpoint(data)
  747. .then(function (res) {
  748. if (!res.ok) {
  749. consoleLogger.info('Call to Firebase backend failed.');
  750. }
  751. return res.json();
  752. })
  753. .then(function (res) {
  754. // Find the next call wait time from the response.
  755. var transportWait = Number(res.nextRequestWaitMillis);
  756. var requestOffset = DEFAULT_SEND_INTERVAL_MS;
  757. if (!isNaN(transportWait)) {
  758. requestOffset = Math.max(transportWait, requestOffset);
  759. }
  760. // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action.
  761. // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER.
  762. var logResponseDetails = res.logResponseDetails;
  763. if (Array.isArray(logResponseDetails) &&
  764. logResponseDetails.length > 0 &&
  765. logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER') {
  766. queue = __spreadArray(__spreadArray([], staged, true), queue, true);
  767. consoleLogger.info("Retry transport request later.");
  768. }
  769. remainingTries = DEFAULT_REMAINING_TRIES;
  770. // Schedule the next process.
  771. processQueue(requestOffset);
  772. });
  773. }
  774. function postToFlEndpoint(data) {
  775. var flTransportFullUrl = SettingsService.getInstance().getFlTransportFullUrl();
  776. return fetch(flTransportFullUrl, {
  777. method: 'POST',
  778. body: JSON.stringify(data)
  779. });
  780. }
  781. function addToQueue(evt) {
  782. if (!evt.eventTime || !evt.message) {
  783. throw ERROR_FACTORY.create("invalid cc log" /* ErrorCode.INVALID_CC_LOG */);
  784. }
  785. // Add the new event to the queue.
  786. queue = __spreadArray(__spreadArray([], queue, true), [evt], false);
  787. }
  788. /** Log handler for cc service to send the performance logs to the server. */
  789. function transportHandler(
  790. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  791. serializer) {
  792. return function () {
  793. var args = [];
  794. for (var _i = 0; _i < arguments.length; _i++) {
  795. args[_i] = arguments[_i];
  796. }
  797. var message = serializer.apply(void 0, args);
  798. addToQueue({
  799. message: message,
  800. eventTime: Date.now()
  801. });
  802. };
  803. }
  804. /**
  805. * @license
  806. * Copyright 2020 Google LLC
  807. *
  808. * Licensed under the Apache License, Version 2.0 (the "License");
  809. * you may not use this file except in compliance with the License.
  810. * You may obtain a copy of the License at
  811. *
  812. * http://www.apache.org/licenses/LICENSE-2.0
  813. *
  814. * Unless required by applicable law or agreed to in writing, software
  815. * distributed under the License is distributed on an "AS IS" BASIS,
  816. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  817. * See the License for the specific language governing permissions and
  818. * limitations under the License.
  819. */
  820. /* eslint-enble camelcase */
  821. var logger;
  822. // This method is not called before initialization.
  823. function sendLog(resource, resourceType) {
  824. if (!logger) {
  825. logger = transportHandler(serializer);
  826. }
  827. logger(resource, resourceType);
  828. }
  829. function logTrace(trace) {
  830. var settingsService = SettingsService.getInstance();
  831. // Do not log if trace is auto generated and instrumentation is disabled.
  832. if (!settingsService.instrumentationEnabled && trace.isAuto) {
  833. return;
  834. }
  835. // Do not log if trace is custom and data collection is disabled.
  836. if (!settingsService.dataCollectionEnabled && !trace.isAuto) {
  837. return;
  838. }
  839. // Do not log if required apis are not available.
  840. if (!Api.getInstance().requiredApisAvailable()) {
  841. return;
  842. }
  843. // Only log the page load auto traces if page is visible.
  844. if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE) {
  845. return;
  846. }
  847. if (isPerfInitialized()) {
  848. sendTraceLog(trace);
  849. }
  850. else {
  851. // Custom traces can be used before the initialization but logging
  852. // should wait until after.
  853. getInitializationPromise(trace.performanceController).then(function () { return sendTraceLog(trace); }, function () { return sendTraceLog(trace); });
  854. }
  855. }
  856. function sendTraceLog(trace) {
  857. if (!getIid()) {
  858. return;
  859. }
  860. var settingsService = SettingsService.getInstance();
  861. if (!settingsService.loggingEnabled ||
  862. !settingsService.logTraceAfterSampling) {
  863. return;
  864. }
  865. setTimeout(function () { return sendLog(trace, 1 /* ResourceType.Trace */); }, 0);
  866. }
  867. function logNetworkRequest(networkRequest) {
  868. var settingsService = SettingsService.getInstance();
  869. // Do not log network requests if instrumentation is disabled.
  870. if (!settingsService.instrumentationEnabled) {
  871. return;
  872. }
  873. // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle.
  874. // Need to blacklist both old and new endpoints to avoid migration gap.
  875. var networkRequestUrl = networkRequest.url;
  876. // Blacklist old log endpoint and new transport endpoint.
  877. // Because Performance SDK doesn't instrument requests sent from SDK itself.
  878. var logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];
  879. var flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];
  880. if (networkRequestUrl === logEndpointUrl ||
  881. networkRequestUrl === flEndpointUrl) {
  882. return;
  883. }
  884. if (!settingsService.loggingEnabled ||
  885. !settingsService.logNetworkAfterSampling) {
  886. return;
  887. }
  888. setTimeout(function () { return sendLog(networkRequest, 0 /* ResourceType.NetworkRequest */); }, 0);
  889. }
  890. function serializer(resource, resourceType) {
  891. if (resourceType === 0 /* ResourceType.NetworkRequest */) {
  892. return serializeNetworkRequest(resource);
  893. }
  894. return serializeTrace(resource);
  895. }
  896. function serializeNetworkRequest(networkRequest) {
  897. var networkRequestMetric = {
  898. url: networkRequest.url,
  899. http_method: networkRequest.httpMethod || 0,
  900. http_response_code: 200,
  901. response_payload_bytes: networkRequest.responsePayloadBytes,
  902. client_start_time_us: networkRequest.startTimeUs,
  903. time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,
  904. time_to_response_completed_us: networkRequest.timeToResponseCompletedUs
  905. };
  906. var perfMetric = {
  907. application_info: getApplicationInfo(networkRequest.performanceController.app),
  908. network_request_metric: networkRequestMetric
  909. };
  910. return JSON.stringify(perfMetric);
  911. }
  912. function serializeTrace(trace) {
  913. var traceMetric = {
  914. name: trace.name,
  915. is_auto: trace.isAuto,
  916. client_start_time_us: trace.startTimeUs,
  917. duration_us: trace.durationUs
  918. };
  919. if (Object.keys(trace.counters).length !== 0) {
  920. traceMetric.counters = trace.counters;
  921. }
  922. var customAttributes = trace.getAttributes();
  923. if (Object.keys(customAttributes).length !== 0) {
  924. traceMetric.custom_attributes = customAttributes;
  925. }
  926. var perfMetric = {
  927. application_info: getApplicationInfo(trace.performanceController.app),
  928. trace_metric: traceMetric
  929. };
  930. return JSON.stringify(perfMetric);
  931. }
  932. function getApplicationInfo(firebaseApp) {
  933. return {
  934. google_app_id: getAppId(firebaseApp),
  935. app_instance_id: getIid(),
  936. web_app_info: {
  937. sdk_version: SDK_VERSION,
  938. page_url: Api.getInstance().getUrl(),
  939. service_worker_status: getServiceWorkerStatus(),
  940. visibility_state: getVisibilityState(),
  941. effective_connection_type: getEffectiveConnectionType()
  942. },
  943. application_process_state: 0
  944. };
  945. }
  946. /**
  947. * @license
  948. * Copyright 2020 Google LLC
  949. *
  950. * Licensed under the Apache License, Version 2.0 (the "License");
  951. * you may not use this file except in compliance with the License.
  952. * You may obtain a copy of the License at
  953. *
  954. * http://www.apache.org/licenses/LICENSE-2.0
  955. *
  956. * Unless required by applicable law or agreed to in writing, software
  957. * distributed under the License is distributed on an "AS IS" BASIS,
  958. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  959. * See the License for the specific language governing permissions and
  960. * limitations under the License.
  961. */
  962. var MAX_METRIC_NAME_LENGTH = 100;
  963. var RESERVED_AUTO_PREFIX = '_';
  964. var oobMetrics = [
  965. FIRST_PAINT_COUNTER_NAME,
  966. FIRST_CONTENTFUL_PAINT_COUNTER_NAME,
  967. FIRST_INPUT_DELAY_COUNTER_NAME
  968. ];
  969. /**
  970. * Returns true if the metric is custom and does not start with reserved prefix, or if
  971. * the metric is one of out of the box page load trace metrics.
  972. */
  973. function isValidMetricName(name, traceName) {
  974. if (name.length === 0 || name.length > MAX_METRIC_NAME_LENGTH) {
  975. return false;
  976. }
  977. return ((traceName &&
  978. traceName.startsWith(OOB_TRACE_PAGE_LOAD_PREFIX) &&
  979. oobMetrics.indexOf(name) > -1) ||
  980. !name.startsWith(RESERVED_AUTO_PREFIX));
  981. }
  982. /**
  983. * Converts the provided value to an integer value to be used in case of a metric.
  984. * @param providedValue Provided number value of the metric that needs to be converted to an integer.
  985. *
  986. * @returns Converted integer number to be set for the metric.
  987. */
  988. function convertMetricValueToInteger(providedValue) {
  989. var valueAsInteger = Math.floor(providedValue);
  990. if (valueAsInteger < providedValue) {
  991. consoleLogger.info("Metric value should be an Integer, setting the value as : ".concat(valueAsInteger, "."));
  992. }
  993. return valueAsInteger;
  994. }
  995. /**
  996. * @license
  997. * Copyright 2020 Google LLC
  998. *
  999. * Licensed under the Apache License, Version 2.0 (the "License");
  1000. * you may not use this file except in compliance with the License.
  1001. * You may obtain a copy of the License at
  1002. *
  1003. * http://www.apache.org/licenses/LICENSE-2.0
  1004. *
  1005. * Unless required by applicable law or agreed to in writing, software
  1006. * distributed under the License is distributed on an "AS IS" BASIS,
  1007. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1008. * See the License for the specific language governing permissions and
  1009. * limitations under the License.
  1010. */
  1011. var Trace = /** @class */ (function () {
  1012. /**
  1013. * @param performanceController The performance controller running.
  1014. * @param name The name of the trace.
  1015. * @param isAuto If the trace is auto-instrumented.
  1016. * @param traceMeasureName The name of the measure marker in user timing specification. This field
  1017. * is only set when the trace is built for logging when the user directly uses the user timing
  1018. * api (performance.mark and performance.measure).
  1019. */
  1020. function Trace(performanceController, name, isAuto, traceMeasureName) {
  1021. if (isAuto === void 0) { isAuto = false; }
  1022. this.performanceController = performanceController;
  1023. this.name = name;
  1024. this.isAuto = isAuto;
  1025. this.state = 1 /* TraceState.UNINITIALIZED */;
  1026. this.customAttributes = {};
  1027. this.counters = {};
  1028. this.api = Api.getInstance();
  1029. this.randomId = Math.floor(Math.random() * 1000000);
  1030. if (!this.isAuto) {
  1031. this.traceStartMark = "".concat(TRACE_START_MARK_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
  1032. this.traceStopMark = "".concat(TRACE_STOP_MARK_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
  1033. this.traceMeasure =
  1034. traceMeasureName ||
  1035. "".concat(TRACE_MEASURE_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
  1036. if (traceMeasureName) {
  1037. // For the case of direct user timing traces, no start stop will happen. The measure object
  1038. // is already available.
  1039. this.calculateTraceMetrics();
  1040. }
  1041. }
  1042. }
  1043. /**
  1044. * Starts a trace. The measurement of the duration starts at this point.
  1045. */
  1046. Trace.prototype.start = function () {
  1047. if (this.state !== 1 /* TraceState.UNINITIALIZED */) {
  1048. throw ERROR_FACTORY.create("trace started" /* ErrorCode.TRACE_STARTED_BEFORE */, {
  1049. traceName: this.name
  1050. });
  1051. }
  1052. this.api.mark(this.traceStartMark);
  1053. this.state = 2 /* TraceState.RUNNING */;
  1054. };
  1055. /**
  1056. * Stops the trace. The measurement of the duration of the trace stops at this point and trace
  1057. * is logged.
  1058. */
  1059. Trace.prototype.stop = function () {
  1060. if (this.state !== 2 /* TraceState.RUNNING */) {
  1061. throw ERROR_FACTORY.create("trace stopped" /* ErrorCode.TRACE_STOPPED_BEFORE */, {
  1062. traceName: this.name
  1063. });
  1064. }
  1065. this.state = 3 /* TraceState.TERMINATED */;
  1066. this.api.mark(this.traceStopMark);
  1067. this.api.measure(this.traceMeasure, this.traceStartMark, this.traceStopMark);
  1068. this.calculateTraceMetrics();
  1069. logTrace(this);
  1070. };
  1071. /**
  1072. * Records a trace with predetermined values. If this method is used a trace is created and logged
  1073. * directly. No need to use start and stop methods.
  1074. * @param startTime Trace start time since epoch in millisec
  1075. * @param duration The duraction of the trace in millisec
  1076. * @param options An object which can optionally hold maps of custom metrics and custom attributes
  1077. */
  1078. Trace.prototype.record = function (startTime, duration, options) {
  1079. if (startTime <= 0) {
  1080. throw ERROR_FACTORY.create("nonpositive trace startTime" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */, {
  1081. traceName: this.name
  1082. });
  1083. }
  1084. if (duration <= 0) {
  1085. throw ERROR_FACTORY.create("nonpositive trace duration" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */, {
  1086. traceName: this.name
  1087. });
  1088. }
  1089. this.durationUs = Math.floor(duration * 1000);
  1090. this.startTimeUs = Math.floor(startTime * 1000);
  1091. if (options && options.attributes) {
  1092. this.customAttributes = __assign({}, options.attributes);
  1093. }
  1094. if (options && options.metrics) {
  1095. for (var _i = 0, _a = Object.keys(options.metrics); _i < _a.length; _i++) {
  1096. var metricName = _a[_i];
  1097. if (!isNaN(Number(options.metrics[metricName]))) {
  1098. this.counters[metricName] = Math.floor(Number(options.metrics[metricName]));
  1099. }
  1100. }
  1101. }
  1102. logTrace(this);
  1103. };
  1104. /**
  1105. * Increments a custom metric by a certain number or 1 if number not specified. Will create a new
  1106. * custom metric if one with the given name does not exist. The value will be floored down to an
  1107. * integer.
  1108. * @param counter Name of the custom metric
  1109. * @param numAsInteger Increment by value
  1110. */
  1111. Trace.prototype.incrementMetric = function (counter, numAsInteger) {
  1112. if (numAsInteger === void 0) { numAsInteger = 1; }
  1113. if (this.counters[counter] === undefined) {
  1114. this.putMetric(counter, numAsInteger);
  1115. }
  1116. else {
  1117. this.putMetric(counter, this.counters[counter] + numAsInteger);
  1118. }
  1119. };
  1120. /**
  1121. * Sets a custom metric to a specified value. Will create a new custom metric if one with the
  1122. * given name does not exist. The value will be floored down to an integer.
  1123. * @param counter Name of the custom metric
  1124. * @param numAsInteger Set custom metric to this value
  1125. */
  1126. Trace.prototype.putMetric = function (counter, numAsInteger) {
  1127. if (isValidMetricName(counter, this.name)) {
  1128. this.counters[counter] = convertMetricValueToInteger(numAsInteger !== null && numAsInteger !== void 0 ? numAsInteger : 0);
  1129. }
  1130. else {
  1131. throw ERROR_FACTORY.create("invalid custom metric name" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */, {
  1132. customMetricName: counter
  1133. });
  1134. }
  1135. };
  1136. /**
  1137. * Returns the value of the custom metric by that name. If a custom metric with that name does
  1138. * not exist will return zero.
  1139. * @param counter
  1140. */
  1141. Trace.prototype.getMetric = function (counter) {
  1142. return this.counters[counter] || 0;
  1143. };
  1144. /**
  1145. * Sets a custom attribute of a trace to a certain value.
  1146. * @param attr
  1147. * @param value
  1148. */
  1149. Trace.prototype.putAttribute = function (attr, value) {
  1150. var isValidName = isValidCustomAttributeName(attr);
  1151. var isValidValue = isValidCustomAttributeValue(value);
  1152. if (isValidName && isValidValue) {
  1153. this.customAttributes[attr] = value;
  1154. return;
  1155. }
  1156. // Throw appropriate error when the attribute name or value is invalid.
  1157. if (!isValidName) {
  1158. throw ERROR_FACTORY.create("invalid attribute name" /* ErrorCode.INVALID_ATTRIBUTE_NAME */, {
  1159. attributeName: attr
  1160. });
  1161. }
  1162. if (!isValidValue) {
  1163. throw ERROR_FACTORY.create("invalid attribute value" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */, {
  1164. attributeValue: value
  1165. });
  1166. }
  1167. };
  1168. /**
  1169. * Retrieves the value a custom attribute of a trace is set to.
  1170. * @param attr
  1171. */
  1172. Trace.prototype.getAttribute = function (attr) {
  1173. return this.customAttributes[attr];
  1174. };
  1175. Trace.prototype.removeAttribute = function (attr) {
  1176. if (this.customAttributes[attr] === undefined) {
  1177. return;
  1178. }
  1179. delete this.customAttributes[attr];
  1180. };
  1181. Trace.prototype.getAttributes = function () {
  1182. return __assign({}, this.customAttributes);
  1183. };
  1184. Trace.prototype.setStartTime = function (startTime) {
  1185. this.startTimeUs = startTime;
  1186. };
  1187. Trace.prototype.setDuration = function (duration) {
  1188. this.durationUs = duration;
  1189. };
  1190. /**
  1191. * Calculates and assigns the duration and start time of the trace using the measure performance
  1192. * entry.
  1193. */
  1194. Trace.prototype.calculateTraceMetrics = function () {
  1195. var perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);
  1196. var perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];
  1197. if (perfMeasureEntry) {
  1198. this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);
  1199. this.startTimeUs = Math.floor((perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000);
  1200. }
  1201. };
  1202. /**
  1203. * @param navigationTimings A single element array which contains the navigationTIming object of
  1204. * the page load
  1205. * @param paintTimings A array which contains paintTiming object of the page load
  1206. * @param firstInputDelay First input delay in millisec
  1207. */
  1208. Trace.createOobTrace = function (performanceController, navigationTimings, paintTimings, firstInputDelay) {
  1209. var route = Api.getInstance().getUrl();
  1210. if (!route) {
  1211. return;
  1212. }
  1213. var trace = new Trace(performanceController, OOB_TRACE_PAGE_LOAD_PREFIX + route, true);
  1214. var timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);
  1215. trace.setStartTime(timeOriginUs);
  1216. // navigationTimings includes only one element.
  1217. if (navigationTimings && navigationTimings[0]) {
  1218. trace.setDuration(Math.floor(navigationTimings[0].duration * 1000));
  1219. trace.putMetric('domInteractive', Math.floor(navigationTimings[0].domInteractive * 1000));
  1220. trace.putMetric('domContentLoadedEventEnd', Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000));
  1221. trace.putMetric('loadEventEnd', Math.floor(navigationTimings[0].loadEventEnd * 1000));
  1222. }
  1223. var FIRST_PAINT = 'first-paint';
  1224. var FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';
  1225. if (paintTimings) {
  1226. var firstPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_PAINT; });
  1227. if (firstPaint && firstPaint.startTime) {
  1228. trace.putMetric(FIRST_PAINT_COUNTER_NAME, Math.floor(firstPaint.startTime * 1000));
  1229. }
  1230. var firstContentfulPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_CONTENTFUL_PAINT; });
  1231. if (firstContentfulPaint && firstContentfulPaint.startTime) {
  1232. trace.putMetric(FIRST_CONTENTFUL_PAINT_COUNTER_NAME, Math.floor(firstContentfulPaint.startTime * 1000));
  1233. }
  1234. if (firstInputDelay) {
  1235. trace.putMetric(FIRST_INPUT_DELAY_COUNTER_NAME, Math.floor(firstInputDelay * 1000));
  1236. }
  1237. }
  1238. logTrace(trace);
  1239. };
  1240. Trace.createUserTimingTrace = function (performanceController, measureName) {
  1241. var trace = new Trace(performanceController, measureName, false, measureName);
  1242. logTrace(trace);
  1243. };
  1244. return Trace;
  1245. }());
  1246. /**
  1247. * @license
  1248. * Copyright 2020 Google LLC
  1249. *
  1250. * Licensed under the Apache License, Version 2.0 (the "License");
  1251. * you may not use this file except in compliance with the License.
  1252. * You may obtain a copy of the License at
  1253. *
  1254. * http://www.apache.org/licenses/LICENSE-2.0
  1255. *
  1256. * Unless required by applicable law or agreed to in writing, software
  1257. * distributed under the License is distributed on an "AS IS" BASIS,
  1258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1259. * See the License for the specific language governing permissions and
  1260. * limitations under the License.
  1261. */
  1262. function createNetworkRequestEntry(performanceController, entry) {
  1263. var performanceEntry = entry;
  1264. if (!performanceEntry || performanceEntry.responseStart === undefined) {
  1265. return;
  1266. }
  1267. var timeOrigin = Api.getInstance().getTimeOrigin();
  1268. var startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000);
  1269. var timeToResponseInitiatedUs = performanceEntry.responseStart
  1270. ? Math.floor((performanceEntry.responseStart - performanceEntry.startTime) * 1000)
  1271. : undefined;
  1272. var timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000);
  1273. // Remove the query params from logged network request url.
  1274. var url = performanceEntry.name && performanceEntry.name.split('?')[0];
  1275. var networkRequest = {
  1276. performanceController: performanceController,
  1277. url: url,
  1278. responsePayloadBytes: performanceEntry.transferSize,
  1279. startTimeUs: startTimeUs,
  1280. timeToResponseInitiatedUs: timeToResponseInitiatedUs,
  1281. timeToResponseCompletedUs: timeToResponseCompletedUs
  1282. };
  1283. logNetworkRequest(networkRequest);
  1284. }
  1285. /**
  1286. * @license
  1287. * Copyright 2020 Google LLC
  1288. *
  1289. * Licensed under the Apache License, Version 2.0 (the "License");
  1290. * you may not use this file except in compliance with the License.
  1291. * You may obtain a copy of the License at
  1292. *
  1293. * http://www.apache.org/licenses/LICENSE-2.0
  1294. *
  1295. * Unless required by applicable law or agreed to in writing, software
  1296. * distributed under the License is distributed on an "AS IS" BASIS,
  1297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1298. * See the License for the specific language governing permissions and
  1299. * limitations under the License.
  1300. */
  1301. var FID_WAIT_TIME_MS = 5000;
  1302. function setupOobResources(performanceController) {
  1303. // Do not initialize unless iid is available.
  1304. if (!getIid()) {
  1305. return;
  1306. }
  1307. // The load event might not have fired yet, and that means performance navigation timing
  1308. // object has a duration of 0. The setup should run after all current tasks in js queue.
  1309. setTimeout(function () { return setupOobTraces(performanceController); }, 0);
  1310. setTimeout(function () { return setupNetworkRequests(performanceController); }, 0);
  1311. setTimeout(function () { return setupUserTimingTraces(performanceController); }, 0);
  1312. }
  1313. function setupNetworkRequests(performanceController) {
  1314. var api = Api.getInstance();
  1315. var resources = api.getEntriesByType('resource');
  1316. for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
  1317. var resource = resources_1[_i];
  1318. createNetworkRequestEntry(performanceController, resource);
  1319. }
  1320. api.setupObserver('resource', function (entry) {
  1321. return createNetworkRequestEntry(performanceController, entry);
  1322. });
  1323. }
  1324. function setupOobTraces(performanceController) {
  1325. var api = Api.getInstance();
  1326. var navigationTimings = api.getEntriesByType('navigation');
  1327. var paintTimings = api.getEntriesByType('paint');
  1328. // If First Input Desly polyfill is added to the page, report the fid value.
  1329. // https://github.com/GoogleChromeLabs/first-input-delay
  1330. if (api.onFirstInputDelay) {
  1331. // If the fid call back is not called for certain time, continue without it.
  1332. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1333. var timeoutId_1 = setTimeout(function () {
  1334. Trace.createOobTrace(performanceController, navigationTimings, paintTimings);
  1335. timeoutId_1 = undefined;
  1336. }, FID_WAIT_TIME_MS);
  1337. api.onFirstInputDelay(function (fid) {
  1338. if (timeoutId_1) {
  1339. clearTimeout(timeoutId_1);
  1340. Trace.createOobTrace(performanceController, navigationTimings, paintTimings, fid);
  1341. }
  1342. });
  1343. }
  1344. else {
  1345. Trace.createOobTrace(performanceController, navigationTimings, paintTimings);
  1346. }
  1347. }
  1348. function setupUserTimingTraces(performanceController) {
  1349. var api = Api.getInstance();
  1350. // Run through the measure performance entries collected up to this point.
  1351. var measures = api.getEntriesByType('measure');
  1352. for (var _i = 0, measures_1 = measures; _i < measures_1.length; _i++) {
  1353. var measure = measures_1[_i];
  1354. createUserTimingTrace(performanceController, measure);
  1355. }
  1356. // Setup an observer to capture the measures from this point on.
  1357. api.setupObserver('measure', function (entry) {
  1358. return createUserTimingTrace(performanceController, entry);
  1359. });
  1360. }
  1361. function createUserTimingTrace(performanceController, measure) {
  1362. var measureName = measure.name;
  1363. // Do not create a trace, if the user timing marks and measures are created by the sdk itself.
  1364. if (measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===
  1365. TRACE_MEASURE_PREFIX) {
  1366. return;
  1367. }
  1368. Trace.createUserTimingTrace(performanceController, measureName);
  1369. }
  1370. /**
  1371. * @license
  1372. * Copyright 2020 Google LLC
  1373. *
  1374. * Licensed under the Apache License, Version 2.0 (the "License");
  1375. * you may not use this file except in compliance with the License.
  1376. * You may obtain a copy of the License at
  1377. *
  1378. * http://www.apache.org/licenses/LICENSE-2.0
  1379. *
  1380. * Unless required by applicable law or agreed to in writing, software
  1381. * distributed under the License is distributed on an "AS IS" BASIS,
  1382. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1383. * See the License for the specific language governing permissions and
  1384. * limitations under the License.
  1385. */
  1386. var PerformanceController = /** @class */ (function () {
  1387. function PerformanceController(app, installations) {
  1388. this.app = app;
  1389. this.installations = installations;
  1390. this.initialized = false;
  1391. }
  1392. /**
  1393. * This method *must* be called internally as part of creating a
  1394. * PerformanceController instance.
  1395. *
  1396. * Currently it's not possible to pass the settings object through the
  1397. * constructor using Components, so this method exists to be called with the
  1398. * desired settings, to ensure nothing is collected without the user's
  1399. * consent.
  1400. */
  1401. PerformanceController.prototype._init = function (settings) {
  1402. var _this = this;
  1403. if (this.initialized) {
  1404. return;
  1405. }
  1406. if ((settings === null || settings === void 0 ? void 0 : settings.dataCollectionEnabled) !== undefined) {
  1407. this.dataCollectionEnabled = settings.dataCollectionEnabled;
  1408. }
  1409. if ((settings === null || settings === void 0 ? void 0 : settings.instrumentationEnabled) !== undefined) {
  1410. this.instrumentationEnabled = settings.instrumentationEnabled;
  1411. }
  1412. if (Api.getInstance().requiredApisAvailable()) {
  1413. validateIndexedDBOpenable()
  1414. .then(function (isAvailable) {
  1415. if (isAvailable) {
  1416. setupTransportService();
  1417. getInitializationPromise(_this).then(function () { return setupOobResources(_this); }, function () { return setupOobResources(_this); });
  1418. _this.initialized = true;
  1419. }
  1420. })
  1421. .catch(function (error) {
  1422. consoleLogger.info("Environment doesn't support IndexedDB: ".concat(error));
  1423. });
  1424. }
  1425. else {
  1426. consoleLogger.info('Firebase Performance cannot start if the browser does not support ' +
  1427. '"Fetch" and "Promise", or cookies are disabled.');
  1428. }
  1429. };
  1430. Object.defineProperty(PerformanceController.prototype, "instrumentationEnabled", {
  1431. get: function () {
  1432. return SettingsService.getInstance().instrumentationEnabled;
  1433. },
  1434. set: function (val) {
  1435. SettingsService.getInstance().instrumentationEnabled = val;
  1436. },
  1437. enumerable: false,
  1438. configurable: true
  1439. });
  1440. Object.defineProperty(PerformanceController.prototype, "dataCollectionEnabled", {
  1441. get: function () {
  1442. return SettingsService.getInstance().dataCollectionEnabled;
  1443. },
  1444. set: function (val) {
  1445. SettingsService.getInstance().dataCollectionEnabled = val;
  1446. },
  1447. enumerable: false,
  1448. configurable: true
  1449. });
  1450. return PerformanceController;
  1451. }());
  1452. /**
  1453. * Firebase Performance Monitoring
  1454. *
  1455. * @packageDocumentation
  1456. */
  1457. var DEFAULT_ENTRY_NAME = '[DEFAULT]';
  1458. /**
  1459. * Returns a {@link FirebasePerformance} instance for the given app.
  1460. * @param app - The {@link @firebase/app#FirebaseApp} to use.
  1461. * @public
  1462. */
  1463. function getPerformance(app) {
  1464. if (app === void 0) { app = getApp(); }
  1465. app = getModularInstance(app);
  1466. var provider = _getProvider(app, 'performance');
  1467. var perfInstance = provider.getImmediate();
  1468. return perfInstance;
  1469. }
  1470. /**
  1471. * Returns a {@link FirebasePerformance} instance for the given app. Can only be called once.
  1472. * @param app - The {@link @firebase/app#FirebaseApp} to use.
  1473. * @param settings - Optional settings for the {@link FirebasePerformance} instance.
  1474. * @public
  1475. */
  1476. function initializePerformance(app, settings) {
  1477. app = getModularInstance(app);
  1478. var provider = _getProvider(app, 'performance');
  1479. // throw if an instance was already created.
  1480. // It could happen if initializePerformance() is called more than once, or getPerformance() is called first.
  1481. if (provider.isInitialized()) {
  1482. var existingInstance = provider.getImmediate();
  1483. var initialSettings = provider.getOptions();
  1484. if (deepEqual(initialSettings, settings !== null && settings !== void 0 ? settings : {})) {
  1485. return existingInstance;
  1486. }
  1487. else {
  1488. throw ERROR_FACTORY.create("already initialized" /* ErrorCode.ALREADY_INITIALIZED */);
  1489. }
  1490. }
  1491. var perfInstance = provider.initialize({
  1492. options: settings
  1493. });
  1494. return perfInstance;
  1495. }
  1496. /**
  1497. * Returns a new `PerformanceTrace` instance.
  1498. * @param performance - The {@link FirebasePerformance} instance to use.
  1499. * @param name - The name of the trace.
  1500. * @public
  1501. */
  1502. function trace(performance, name) {
  1503. performance = getModularInstance(performance);
  1504. return new Trace(performance, name);
  1505. }
  1506. var factory = function (container, _a) {
  1507. var settings = _a.options;
  1508. // Dependencies
  1509. var app = container.getProvider('app').getImmediate();
  1510. var installations = container
  1511. .getProvider('installations-internal')
  1512. .getImmediate();
  1513. if (app.name !== DEFAULT_ENTRY_NAME) {
  1514. throw ERROR_FACTORY.create("FB not default" /* ErrorCode.FB_NOT_DEFAULT */);
  1515. }
  1516. if (typeof window === 'undefined') {
  1517. throw ERROR_FACTORY.create("no window" /* ErrorCode.NO_WINDOW */);
  1518. }
  1519. setupApi(window);
  1520. var perfInstance = new PerformanceController(app, installations);
  1521. perfInstance._init(settings);
  1522. return perfInstance;
  1523. };
  1524. function registerPerformance() {
  1525. _registerComponent(new Component('performance', factory, "PUBLIC" /* ComponentType.PUBLIC */));
  1526. registerVersion(name, version);
  1527. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  1528. registerVersion(name, version, 'esm5');
  1529. }
  1530. registerPerformance();
  1531. export { getPerformance, initializePerformance, trace };
  1532. //# sourceMappingURL=index.esm.js.map