firebase
Version:
Firebase JavaScript library for web and Node.js
3 lines (2 loc) • 32 kB
JavaScript
import{registerVersion as t,_registerComponent as e,_getProvider as n,getApp as r}from"https://www.gstatic.com/firebasejs/9.0.0-beta.7/firebase-app.js";var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function o(t,e){for(var n=0,r=e.length,i=t.length;n<r;n++,i++)t[i]=e[n];return t}var a=function(t){function e(n,r,i){var o=t.call(this,r)||this;return o.code=n,o.customData=i,o.name="FirebaseError",Object.setPrototypeOf(o,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(o,s.prototype.create),o}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e}(Error),s=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n}return t.prototype.create=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var r=e[0]||{},i=this.service+"/"+t,o=this.errors[t],s=o?c(o,r):"Error",u=this.serviceName+": "+s+" ("+i+").",l=new a(i,u,r);return l},t}();function c(t,e){return t.replace(p,(function(t,n){var r=e[n];return null!=r?String(r):"<"+n+"?>"}))}var u,l,p=/\{\$([^}]+)}/g;function f(t){return t&&t._delegate?t._delegate:t}!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(l||(l={}));var d={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},h=l.INFO,g=((u={})[l.DEBUG]="log",u[l.VERBOSE]="log",u[l.INFO]="info",u[l.WARN]="warn",u[l.ERROR]="error",u),m=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var i=(new Date).toISOString(),a=g[e];if(!a)throw new Error("Attempted to log a message with an invalid logType (value: "+e+")");console[a].apply(console,o(["["+i+"] "+t.name+":"],n))}},y=function(){function t(t){this.name=t,this._logLevel=h,this._logHandler=m,this._userLogHandler=null}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in l))throw new TypeError('Invalid value "'+t+'" assigned to `logLevel`');this._logLevel=t},enumerable:!1,configurable:!0}),t.prototype.setLogLevel=function(t){this._logLevel="string"==typeof t?d[t]:t},Object.defineProperty(t.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(t){this._userLogHandler=t},enumerable:!1,configurable:!0}),t.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,o([this,l.DEBUG],t)),this._logHandler.apply(this,o([this,l.DEBUG],t))},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,o([this,l.VERBOSE],t)),this._logHandler.apply(this,o([this,l.VERBOSE],t))},t.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,o([this,l.INFO],t)),this._logHandler.apply(this,o([this,l.INFO],t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,o([this,l.WARN],t)),this._logHandler.apply(this,o([this,l.WARN],t))},t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,o([this,l.ERROR],t)),this._logHandler.apply(this,o([this,l.ERROR],t))},t}(),v=function(){function t(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}return t.prototype.setInstantiationMode=function(t){return this.instantiationMode=t,this},t.prototype.setMultipleInstances=function(t){return this.multipleInstances=t,this},t.prototype.setServiceProps=function(t){return this.serviceProps=t,this},t.prototype.setInstanceCreatedCallback=function(t){return this.onInstanceCreated=t,this},t}();function _(t){return Array.prototype.slice.call(t)}function b(t){return new Promise((function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function w(t,e,n){var r,i=new Promise((function(i,o){b(r=t[e].apply(t,n)).then(i,o)}));return i.request=r,i}function E(t,e,n){var r=w(t,e,n);return r.then((function(t){if(t)return new N(t,r.request)}))}function I(t,e,n){n.forEach((function(n){Object.defineProperty(t.prototype,n,{get:function(){return this[e][n]},set:function(t){this[e][n]=t}})}))}function T(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return w(this[e],r,arguments)})}))}function S(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return this[e][r].apply(this[e],arguments)})}))}function O(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return E(this[e],r,arguments)})}))}function A(t){this._index=t}function N(t,e){this._cursor=t,this._request=e}function k(t){this._store=t}function R(t){this._tx=t,this.complete=new Promise((function(e,n){t.oncomplete=function(){e()},t.onerror=function(){n(t.error)},t.onabort=function(){n(t.error)}}))}function C(t,e,n){this._db=t,this.oldVersion=e,this.transaction=new R(n)}function P(t){this._db=t}I(A,"_index",["name","keyPath","multiEntry","unique"]),T(A,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),O(A,"_index",IDBIndex,["openCursor","openKeyCursor"]),I(N,"_cursor",["direction","key","primaryKey","value"]),T(N,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(t){t in IDBCursor.prototype&&(N.prototype[t]=function(){var e=this,n=arguments;return Promise.resolve().then((function(){return e._cursor[t].apply(e._cursor,n),b(e._request).then((function(t){if(t)return new N(t,e._request)}))}))})})),k.prototype.createIndex=function(){return new A(this._store.createIndex.apply(this._store,arguments))},k.prototype.index=function(){return new A(this._store.index.apply(this._store,arguments))},I(k,"_store",["name","keyPath","indexNames","autoIncrement"]),T(k,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),O(k,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),S(k,"_store",IDBObjectStore,["deleteIndex"]),R.prototype.objectStore=function(){return new k(this._tx.objectStore.apply(this._tx,arguments))},I(R,"_tx",["objectStoreNames","mode"]),S(R,"_tx",IDBTransaction,["abort"]),C.prototype.createObjectStore=function(){return new k(this._db.createObjectStore.apply(this._db,arguments))},I(C,"_db",["name","version","objectStoreNames"]),S(C,"_db",IDBDatabase,["deleteObjectStore","close"]),P.prototype.transaction=function(){return new R(this._db.transaction.apply(this._db,arguments))},I(P,"_db",["name","version","objectStoreNames"]),S(P,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(t){[k,A].forEach((function(e){t in e.prototype&&(e.prototype[t.replace("open","iterate")]=function(){var e=_(arguments),n=e[e.length-1],r=this._store||this._index,i=r[t].apply(r,e.slice(0,-1));i.onsuccess=function(){n(i.result)}})}))})),[A,k].forEach((function(t){t.prototype.getAll||(t.prototype.getAll=function(t,e){var n=this,r=[];return new Promise((function(i){n.iterateCursor(t,(function(t){t?(r.push(t.value),void 0===e||r.length!=e?t.continue():i(r)):i(r)}))}))})}));const M=new s("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function j(t){return t instanceof a&&t.code.includes("request-failed")}function x({projectId:t}){return`https://firebaseinstallations.googleapis.com/v1/projects/${t}/installations`}function B(t){return{token:t.token,requestStatus:2,expiresIn:(e=t.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()};var e}async function D(t,e){const n=(await e.json()).error;return M.create("request-failed",{requestName:t,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function L({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function F(t,{refreshToken:e}){const n=L(t);return n.append("Authorization",function(t){return`FIS_v2 ${t}`}(e)),n}async function U(t){const e=await t();return e.status>=500&&e.status<600?t():e}function q(t){return new Promise((e=>{setTimeout(e,t)}))}const $=/^[cdef][\w-]{21}$/;function H(){try{const t=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(t),t[0]=112+t[0]%16;const e=function(t){return(e=t,btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var e}(t);return $.test(e)?e:""}catch(t){return""}}function V(t){return`${t.appName}!${t.appId}`}const K=new Map;function W(t,e){const n=V(t);z(n,e),function(t,e){const n=function(){!G&&"BroadcastChannel"in self&&(G=new BroadcastChannel("[Firebase] FID Change"),G.onmessage=t=>{z(t.data.key,t.data.fid)});return G}();n&&n.postMessage({key:t,fid:e});0===K.size&&G&&(G.close(),G=null)}(n,e)}function z(t,e){const n=K.get(t);if(n)for(const t of n)t(e)}let G=null;const J="firebase-installations-store";let Y=null;function Z(){return Y||(Y=function(t,e,n){var r=w(indexedDB,"open",[t,e]),i=r.request;return i&&(i.onupgradeneeded=function(t){n&&n(new C(i.result,t.oldVersion,i.transaction))}),r.then((function(t){return new P(t)}))}("firebase-installations-database",1,(t=>{switch(t.oldVersion){case 0:t.createObjectStore(J)}}))),Y}async function Q(t,e){const n=V(t),r=(await Z()).transaction(J,"readwrite"),i=r.objectStore(J),o=await i.get(n);return await i.put(e,n),await r.complete,o&&o.fid===e.fid||W(t,e.fid),e}async function X(t){const e=V(t),n=(await Z()).transaction(J,"readwrite");await n.objectStore(J).delete(e),await n.complete}async function tt(t,e){const n=V(t),r=(await Z()).transaction(J,"readwrite"),i=r.objectStore(J),o=await i.get(n),a=e(o);return void 0===a?await i.delete(n):await i.put(a,n),await r.complete,!a||o&&o.fid===a.fid||W(t,a.fid),a}async function et(t){let e;const n=await tt(t,(n=>{const r=function(t){return it(t||{fid:H(),registrationStatus:0})}(n),i=function(t,e){if(0===e.registrationStatus){if(!navigator.onLine){return{installationEntry:e,registrationPromise:Promise.reject(M.create("app-offline"))}}const n={fid:e.fid,registrationStatus:1,registrationTime:Date.now()};return{installationEntry:n,registrationPromise:async function(t,e){try{return Q(t,await async function(t,{fid:e}){const n=x(t),r=L(t),i={fid:e,authVersion:"FIS_v2",appId:t.appId,sdkVersion:"w:0.0.900-exp.6ef484a04"},o={method:"POST",headers:r,body:JSON.stringify(i)},a=await U((()=>fetch(n,o)));if(a.ok){const t=await a.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:B(t.authToken)}}throw await D("Create Installation",a)}(t,e))}catch(n){throw j(n)&&409===n.customData.serverCode?await X(t):await Q(t,{fid:e.fid,registrationStatus:0}),n}}(t,n)}}return 1===e.registrationStatus?{installationEntry:e,registrationPromise:nt(t)}:{installationEntry:e}}(t,r);return e=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await e}:{installationEntry:n,registrationPromise:e}}async function nt(t){let e=await rt(t);for(;1===e.registrationStatus;)await q(100),e=await rt(t);if(0===e.registrationStatus){const{installationEntry:e,registrationPromise:n}=await et(t);return n||e}return e}function rt(t){return tt(t,(t=>{if(!t)throw M.create("installation-not-found");return it(t)}))}function it(t){return 1===(e=t).registrationStatus&&e.registrationTime+1e4<Date.now()?{fid:t.fid,registrationStatus:0}:t;var e}async function ot({appConfig:t,platformLoggerProvider:e},n){const r=function(t,{fid:e}){return`${x(t)}/${e}/authTokens:generate`}(t,n),i=F(t,n),o=e.getImmediate({optional:!0});o&&i.append("x-firebase-client",o.getPlatformInfoString());const a={installation:{sdkVersion:"w:0.0.900-exp.6ef484a04"}},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await U((()=>fetch(r,s)));if(c.ok){return B(await c.json())}throw await D("Generate Auth Token",c)}async function at(t,e=!1){let n;const r=await tt(t.appConfig,(r=>{if(!ct(r))throw M.create("not-registered");const i=r.authToken;if(!e&&function(t){return 2===t.requestStatus&&!function(t){const e=Date.now();return e<t.creationTime||t.creationTime+t.expiresIn<e+36e5}(t)}(i))return r;if(1===i.requestStatus)return n=async function(t,e){let n=await st(t.appConfig);for(;1===n.authToken.requestStatus;)await q(100),n=await st(t.appConfig);const r=n.authToken;return 0===r.requestStatus?at(t,e):r}(t,e),r;{if(!navigator.onLine)throw M.create("app-offline");const e=function(t){const e={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},t),{authToken:e})}(r);return n=async function(t,e){try{const n=await ot(t,e),r=Object.assign(Object.assign({},e),{authToken:n});return await Q(t.appConfig,r),n}catch(n){if(!j(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},e),{authToken:{requestStatus:0}});await Q(t.appConfig,n)}else await X(t.appConfig);throw n}}(t,e),e}}));return n?await n:r.authToken}function st(t){return tt(t,(t=>{if(!ct(t))throw M.create("not-registered");const e=t.authToken;return 1===(n=e).requestStatus&&n.requestTime+1e4<Date.now()?Object.assign(Object.assign({},t),{authToken:{requestStatus:0}}):t;var n}))}function ct(t){return void 0!==t&&2===t.registrationStatus}async function ut(t,e=!1){const n=t;await async function(t){const{registrationPromise:e}=await et(t);e&&await e}(n.appConfig);return(await at(n,e)).token}function lt(t){return M.create("missing-app-config-values",{valueName:t})}const pt=t=>{const e=t.getProvider("app-exp").getImmediate(),r=n(e,"installations-exp").getImmediate();return{getId:()=>async function(t){const e=t,{installationEntry:n,registrationPromise:r}=await et(e.appConfig);return r?r.catch(console.error):at(e).catch(console.error),n.fid}(r),getToken:t=>ut(r,t)}};e(new v("installations-exp",(t=>{const e=t.getProvider("app-exp").getImmediate();return{app:e,appConfig:function(t){if(!t||!t.options)throw lt("App Configuration");if(!t.name)throw lt("App Name");const e=["projectId","apiKey","appId"];for(const n of e)if(!t.options[n])throw lt(n);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(e),platformLoggerProvider:n(e,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),e(new v("installations-exp-internal",pt,"PRIVATE")),t("@firebase/installations-exp","0.0.900-exp.6ef484a04");const ft=new s("performance","Performance",{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"Performance can only be initialized once."}),dt=new y("Performance");let ht,gt,mt,yt;dt.logLevel=l.INFO;class vt{constructor(t){if(this.window=t,!t)throw ft.create("no window");this.performance=t.performance,this.PerformanceObserver=t.PerformanceObserver,this.windowLocation=t.location,this.navigator=t.navigator,this.document=t.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=t.localStorage),t.perfMetrics&&t.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=t.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(t){this.performance&&this.performance.mark&&this.performance.mark(t)}measure(t,e,n){this.performance&&this.performance.measure&&this.performance.measure(t,e,n)}getEntriesByType(t){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(t):[]}getEntriesByName(t){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(t):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&this.navigator&&this.navigator.cookieEnabled?"indexedDB"in self&&null!=indexedDB||(dt.info("IndexedDB is not supported by current browswer"),!1):(dt.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(t,e){if(!this.PerformanceObserver)return;new this.PerformanceObserver((t=>{for(const n of t.getEntries())e(n)})).observe({entryTypes:[t]})}static getInstance(){return void 0===ht&&(ht=new vt(gt)),ht}}function _t(){return mt}function bt(t,e){const n=t.length-e.length;if(n<0||n>1)throw ft.create("invalid String merger input");const r=[];for(let n=0;n<t.length;n++)r.push(t.charAt(n)),e.length>n&&r.push(e.charAt(n));return r.join("")}class wt{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=bt("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=bt("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===yt&&(yt=new wt),yt}}var Et;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VISIBLE=1]="VISIBLE",t[t.HIDDEN=2]="HIDDEN"}(Et||(Et={}));const It=["firebase_","google_","ga_"],Tt=new RegExp("^[a-zA-Z]\\w*$");function St(){const t=vt.getInstance().navigator;return"serviceWorker"in t?t.serviceWorker.controller?2:3:1}function Ot(){switch(vt.getInstance().document.visibilityState){case"visible":return Et.VISIBLE;case"hidden":return Et.HIDDEN;default:return Et.UNKNOWN}}function At(){const t=vt.getInstance().navigator.connection;switch(t&&t.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}function Nt(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.appId;if(!n)throw ft.create("no app id");return n}const kt=!0;function Rt(t,e){const n=function(){const t=vt.getInstance().localStorage;if(!t)return;const e=t.getItem("@firebase/performance/configexpire");if(!(e&&(n=e,Number(n)>Date.now())))return;var n;const r=t.getItem("@firebase/performance/config");if(!r)return;try{return JSON.parse(r)}catch(t){return}}();return n?(Ct(n),Promise.resolve()):function(t,e){return function(t){const e=t.getToken();return e.then((t=>{})),e}(t.installations).then((n=>{const r=function(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.projectId;if(!n)throw ft.create("no project id");return n}(t.app),i=function(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.apiKey;if(!n)throw ft.create("no api key");return n}(t.app),o=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${r}/namespaces/fireperf:fetch?key=${i}`,{method:"POST",headers:{Authorization:`FIREBASE_INSTALLATIONS_AUTH ${n}`},body:JSON.stringify({app_instance_id:e,app_instance_id_token:n,app_id:Nt(t.app),app_version:"0.0.900-exp.6ef484a04",sdk_version:"0.0.1"})});return fetch(o).then((t=>{if(t.ok)return t.json();throw ft.create("RC response not ok")}))})).catch((()=>{dt.info("Could not fetch config, will use default configs")}))}(t,e).then(Ct).then((t=>function(t){const e=vt.getInstance().localStorage;if(!t||!e)return;e.setItem("@firebase/performance/config",JSON.stringify(t)),e.setItem("@firebase/performance/configexpire",String(Date.now()+60*wt.getInstance().configTimeToLive*60*1e3))}(t)),(()=>{}))}function Ct(t){if(!t)return t;const e=wt.getInstance(),n=t.entries||{};return void 0!==n.fpr_enabled?e.loggingEnabled="true"===String(n.fpr_enabled):e.loggingEnabled=kt,n.fpr_log_source&&(e.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(e.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(e.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(e.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(e.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),e.logTraceAfterSampling=Pt(e.tracesSamplingRate),e.logNetworkAfterSampling=Pt(e.networkRequestsSamplingRate),t}function Pt(t){return Math.random()<=t}let Mt,jt=1;function xt(t){return jt=2,Mt=Mt||function(t){return function(){const t=vt.getInstance().document;return new Promise((e=>{if(t&&"complete"!==t.readyState){const n=()=>{"complete"===t.readyState&&(t.removeEventListener("readystatechange",n),e())};t.addEventListener("readystatechange",n)}else e()}))}().then((()=>function(t){const e=t.getId();return e.then((t=>{mt=t})),e}(t.installations))).then((e=>Rt(t,e))).then((()=>Bt()),(()=>Bt()))}(t),Mt}function Bt(){jt=3}let Dt,Lt=3,Ft=[],Ut=!1;function qt(t){setTimeout((()=>{if(0!==Lt)return Ft.length?void function(){const t=Ft.splice(0,1e3),e=t.map((t=>({source_extension_json_proto3:t.message,event_time_ms:String(t.eventTime)})));(function(t,e){return function(t){const e=wt.getInstance().getFlTransportFullUrl();return fetch(e,{method:"POST",body:JSON.stringify(t)})}(t).then((t=>(t.ok||dt.info("Call to Firebase backend failed."),t.json()))).then((t=>{const n=Number(t.nextRequestWaitMillis);let r=1e4;isNaN(n)||(r=Math.max(n,r));const i=t.logResponseDetails;Array.isArray(i)&&i.length>0&&"RETRY_REQUEST_LATER"===i[0].responseAction&&(Ft=[...e,...Ft],dt.info("Retry transport request later.")),Lt=3,qt(r)}))})({request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:wt.getInstance().logSource,log_event:e},t).catch((()=>{Ft=[...t,...Ft],Lt--,dt.info(`Tries left: ${Lt}.`),qt(1e4)}))}():qt(1e4)}),t)}function $t(t){return(...e)=>{!function(t){if(!t.eventTime||!t.message)throw ft.create("invalid cc log");Ft=[...Ft,t]}({message:t(...e),eventTime:Date.now()})}}function Ht(t,e){Dt||(Dt=$t(Wt)),Dt(t,e)}function Vt(t){const e=wt.getInstance();!e.instrumentationEnabled&&t.isAuto||(e.dataCollectionEnabled||t.isAuto)&&vt.getInstance().requiredApisAvailable()&&(t.isAuto&&Ot()!==Et.VISIBLE||(3===jt?Kt(t):xt(t.performanceController).then((()=>Kt(t)),(()=>Kt(t)))))}function Kt(t){if(!_t())return;const e=wt.getInstance();e.loggingEnabled&&e.logTraceAfterSampling&&setTimeout((()=>Ht(t,1)),0)}function Wt(t,e){return 0===e?function(t){const e={url:t.url,http_method:t.httpMethod||0,http_response_code:200,response_payload_bytes:t.responsePayloadBytes,client_start_time_us:t.startTimeUs,time_to_response_initiated_us:t.timeToResponseInitiatedUs,time_to_response_completed_us:t.timeToResponseCompletedUs},n={application_info:zt(t.performanceController.app),network_request_metric:e};return JSON.stringify(n)}(t):function(t){const e={name:t.name,is_auto:t.isAuto,client_start_time_us:t.startTimeUs,duration_us:t.durationUs};0!==Object.keys(t.counters).length&&(e.counters=t.counters);const n=t.getAttributes();0!==Object.keys(n).length&&(e.custom_attributes=n);const r={application_info:zt(t.performanceController.app),trace_metric:e};return JSON.stringify(r)}(t)}function zt(t){return{google_app_id:Nt(t),app_instance_id:_t(),web_app_info:{sdk_version:"0.0.900-exp.6ef484a04",page_url:vt.getInstance().getUrl(),service_worker_status:St(),visibility_state:Ot(),effective_connection_type:At()},application_process_state:0}}const Gt=["_fp","_fcp","_fid"];class Jt{constructor(t,e,n=!1,r){this.performanceController=t,this.name=e,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=vt.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`FB-PERF-TRACE-MEASURE-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw ft.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw ft.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),Vt(this)}record(t,e,n){if(t<=0)throw ft.create("nonpositive trace startTime",{traceName:this.name});if(e<=0)throw ft.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*e),this.startTimeUs=Math.floor(1e3*t),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const t of Object.keys(n.metrics))isNaN(Number(n.metrics[t]))||(this.counters[t]=Number(Math.floor(n.metrics[t])));Vt(this)}incrementMetric(t,e=1){void 0===this.counters[t]?this.putMetric(t,e):this.putMetric(t,this.counters[t]+e)}putMetric(t,e){if(!function(t,e){return!(0===t.length||t.length>100)&&(e&&e.startsWith("_wt_")&&Gt.indexOf(t)>-1||!t.startsWith("_"))}(t,this.name))throw ft.create("invalid custom metric name",{customMetricName:t});this.counters[t]=function(t){const e=Math.floor(t);return e<t&&dt.info(`Metric value should be an Integer, setting the value as : ${e}.`),e}(e)}getMetric(t){return this.counters[t]||0}putAttribute(t,e){const n=function(t){return!(0===t.length||t.length>40)&&(!It.some((e=>t.startsWith(e)))&&!!t.match(Tt))}(t),r=function(t){return 0!==t.length&&t.length<=100}(e);if(n&&r)this.customAttributes[t]=e;else{if(!n)throw ft.create("invalid attribute name",{attributeName:t});if(!r)throw ft.create("invalid attribute value",{attributeValue:e})}}getAttribute(t){return this.customAttributes[t]}removeAttribute(t){void 0!==this.customAttributes[t]&&delete this.customAttributes[t]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(t){this.startTimeUs=t}setDuration(t){this.durationUs=t}calculateTraceMetrics(){const t=this.api.getEntriesByName(this.traceMeasure),e=t&&t[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(t,e,n,r){const i=vt.getInstance().getUrl();if(!i)return;const o=new Jt(t,"_wt_"+i,!0),a=Math.floor(1e3*vt.getInstance().getTimeOrigin());o.setStartTime(a),e&&e[0]&&(o.setDuration(Math.floor(1e3*e[0].duration)),o.putMetric("domInteractive",Math.floor(1e3*e[0].domInteractive)),o.putMetric("domContentLoadedEventEnd",Math.floor(1e3*e[0].domContentLoadedEventEnd)),o.putMetric("loadEventEnd",Math.floor(1e3*e[0].loadEventEnd)));if(n){const t=n.find((t=>"first-paint"===t.name));t&&t.startTime&&o.putMetric("_fp",Math.floor(1e3*t.startTime));const e=n.find((t=>"first-contentful-paint"===t.name));e&&e.startTime&&o.putMetric("_fcp",Math.floor(1e3*e.startTime)),r&&o.putMetric("_fid",Math.floor(1e3*r))}Vt(o)}static createUserTimingTrace(t,e){Vt(new Jt(t,e,!1,e))}}function Yt(t,e){const n=e;if(!n||void 0===n.responseStart)return;const r=vt.getInstance().getTimeOrigin(),i=Math.floor(1e3*(n.startTime+r)),o=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,a=Math.floor(1e3*(n.responseEnd-n.startTime));!function(t){const e=wt.getInstance();if(!e.instrumentationEnabled)return;const n=t.url,r=e.logEndPointUrl.split("?")[0],i=e.flTransportEndpointUrl.split("?")[0];n!==r&&n!==i&&e.loggingEnabled&&e.logNetworkAfterSampling&&setTimeout((()=>Ht(t,0)),0)}({performanceController:t,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:i,timeToResponseInitiatedUs:o,timeToResponseCompletedUs:a})}function Zt(t){_t()&&(setTimeout((()=>function(t){const e=vt.getInstance(),n=e.getEntriesByType("navigation"),r=e.getEntriesByType("paint");if(e.onFirstInputDelay){let i=setTimeout((()=>{Jt.createOobTrace(t,n,r),i=void 0}),5e3);e.onFirstInputDelay((e=>{i&&(clearTimeout(i),Jt.createOobTrace(t,n,r,e))}))}else Jt.createOobTrace(t,n,r)}(t)),0),setTimeout((()=>function(t){const e=vt.getInstance(),n=e.getEntriesByType("resource");for(const e of n)Yt(t,e);e.setupObserver("resource",(e=>Yt(t,e)))}(t)),0),setTimeout((()=>function(t){const e=vt.getInstance(),n=e.getEntriesByType("measure");for(const e of n)Qt(t,e);e.setupObserver("measure",(e=>Qt(t,e)))}(t)),0))}function Qt(t,e){const n=e.name;"FB-PERF-TRACE-MEASURE"!==n.substring(0,"FB-PERF-TRACE-MEASURE".length)&&Jt.createUserTimingTrace(t,n)}class Xt{constructor(t,e){this.app=t,this.installations=e,this.initialized=!1}_init(t){this.initialized||(void 0!==(null==t?void 0:t.dataCollectionEnabled)&&(this.dataCollectionEnabled=t.dataCollectionEnabled),void 0!==(null==t?void 0:t.instrumentationEnabled)&&(this.instrumentationEnabled=t.instrumentationEnabled),vt.getInstance().requiredApisAvailable()?new Promise((function(t,e){try{var n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=function(){i.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=function(){n=!1},i.onerror=function(){var t;e((null===(t=i.error)||void 0===t?void 0:t.message)||"")}}catch(t){e(t)}})).then((t=>{t&&(Ut||(qt(5500),Ut=!0),xt(this).then((()=>Zt(this)),(()=>Zt(this))),this.initialized=!0)})).catch((t=>{dt.info(`Environment doesn't support IndexedDB: ${t}`)})):dt.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(t){wt.getInstance().instrumentationEnabled=t}get instrumentationEnabled(){return wt.getInstance().instrumentationEnabled}set dataCollectionEnabled(t){wt.getInstance().dataCollectionEnabled=t}get dataCollectionEnabled(){return wt.getInstance().dataCollectionEnabled}}function te(t=r()){t=f(t);return n(t,"performance-exp").getImmediate()}function ee(t,e){t=f(t);const r=n(t,"performance-exp");if(r.isInitialized())throw ft.create("already initialized");return r.initialize({options:e})}function ne(t,e){return t=f(t),new Jt(t,e)}e(new v("performance-exp",((t,{options:e})=>{const n=t.getProvider("app-exp").getImmediate(),r=t.getProvider("installations-exp-internal").getImmediate();if("[DEFAULT]"!==n.name)throw ft.create("FB not default");if("undefined"==typeof window)throw ft.create("no window");!function(t){gt=t}(window);const i=new Xt(n,r);return i._init(e),i}),"PUBLIC")),t("@firebase/performance-exp","0.0.900-exp.6ef484a04");export{te as getPerformance,ee as initializePerformance,ne as trace};
//# sourceMappingURL=firebase-performance.js.map