UNPKG

firebase

Version:

Firebase JavaScript library for web and Node.js

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