firebase 12.17.0 → 12.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-ai.js +1 -1
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +4 -4
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +4 -4
- package/firebase-data-connect.js +1 -1
- package/firebase-data-connect.js.map +1 -1
- package/firebase-database-compat.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-lite-pipelines.js +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-pipelines.js +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-standalone-compat.js +3 -3
- package/firebase-performance.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +3 -3
|
@@ -259,7 +259,7 @@ class Le{constructor(e,t,n){this._isDeleted=!1,this._options={...e},this._config
|
|
|
259
259
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
260
260
|
* See the License for the specific language governing permissions and
|
|
261
261
|
* limitations under the License.
|
|
262
|
-
*/const Re="12.17.
|
|
262
|
+
*/const Re="12.17.1";function Fe(e,t={}){let n=e;if("object"!=typeof t){t={name:t}}const r={name:Ee,automaticDataCollectionEnabled:!0,...t},i=r.name;if("string"!=typeof i||!i)throw Me.create("bad-app-name",{appName:String(i)});if(n||(n=c()),!n)throw Me.create("no-options");const a=Ie.get(i);if(a){if(m(n,a.options)){if(m(r,a.config))return a;throw Me.create("duplicate-app",{appName:i,mismatchedParam:"config",oldValue:JSON.stringify(a.config),newValue:JSON.stringify(r)})}throw Me.create("duplicate-app",{appName:i,mismatchedParam:"options",oldValue:JSON.stringify(a.options),newValue:JSON.stringify(n)})}const o=new w(i);for(const e of Ce.values())o.addComponent(e);const s=new Le(n,r,o);return Ie.set(i,s),s}async function $e(e){let t=!1;const n=e.name;if(Ie.has(n))t=!0,Ie.delete(n);else if(Te.has(n)){e.decRefCount()<=0&&(Te.delete(n),t=!0)}t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function xe(e,t,n){let r=Se[e]??e;n&&(r+=`-${n}`);const i=r.match(/\s|\//),a=t.match(/\s|\//);if(i||a){const e=[`Unable to register library "${r}" with version "${t}":`];return i&&e.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&a&&e.push("and"),a&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void G.warn(e.join(" "))}De(new v(`${r}-version`,(()=>({library:r,version:t})),"VERSION"))}function Ue(e,t){if(null!==e&&"function"!=typeof e)throw Me.create("invalid-log-argument");!function(e,t){for(const n of E){let r=null;t&&t.level&&(r=I[t.level]),n.userLogHandler=null===e?null:(t,n,...i)=>{const a=i.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");n>=(r??t.logLevel)&&e({level:S[n].toLowerCase(),message:a,args:i,type:t.name})}}}(e,t)}function je(e){var t;t=e,E.forEach((e=>{e.setLogLevel(t)}))}
|
|
263
263
|
/**
|
|
264
264
|
* @license
|
|
265
265
|
* Copyright 2021 Google LLC
|
|
@@ -439,7 +439,7 @@ function(e){xe("@firebase/app-compat","0.5.16",e)}("lite");
|
|
|
439
439
|
* See the License for the specific language governing permissions and
|
|
440
440
|
* limitations under the License.
|
|
441
441
|
*/
|
|
442
|
-
nt.registerVersion("firebase","12.17.0","app-compat");var rt,it,at=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},ot=function(e){if("loading"===document.readyState)return"loading";var t=at();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},st=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},ct=function(e,t){var n="";try{for(;e&&9!==e.nodeType;){var r=e,i=r.id?"#"+r.id:st(r)+(r.classList&&r.classList.value&&r.classList.value.trim()&&r.classList.value.trim().length?"."+r.classList.value.trim().replace(/\s+/g,"."):"");if(n.length+i.length>(t||100)-1)return n||i;if(n=n?i+">"+n:i,r.id)break;e=r.parentNode}}catch(e){}return n},lt=-1,ut=function(e){addEventListener("pageshow",(function(t){t.persisted&&(lt=t.timeStamp,e(t))}),!0)},ft=function(){var e=at();return e&&e.activationStart||0},dt=function(e,t){var n=at(),r="navigate";return lt>=0?r="back-forward-cache":n&&(document.prerendering||ft()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},pt=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(e){}},ht=function(e,t,n,r){var i,a;return function(o){t.value>=0&&(o||r)&&((a=t.value-(i||0))||void 0===i)&&(i=t.value,t.delta=a,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},gt=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},mt=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},bt=function(e){var t=!1;return function(){t||(e(),t=!0)}},vt=-1,yt=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},_t=function(e){"hidden"===document.visibilityState&&vt>-1&&(vt="visibilitychange"===e.type?e.timeStamp:0,Et())},wt=function(){addEventListener("visibilitychange",_t,!0),addEventListener("prerenderingchange",_t,!0)},Et=function(){removeEventListener("visibilitychange",_t,!0),removeEventListener("prerenderingchange",_t,!0)},St=function(){return vt<0&&(vt=yt(),wt(),ut((function(){setTimeout((function(){vt=yt(),wt()}),0)}))),{get firstHiddenTime(){return vt}}},It=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},Tt=[1800,3e3],Ct=[.1,.25],At=function(e,t){!function(e,t){t=t||{},function(e,t){t=t||{},It((function(){var n,r=St(),i=dt("FCP"),a=pt("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(a.disconnect(),e.startTime<r.firstHiddenTime&&(i.value=Math.max(e.startTime-ft(),0),i.entries.push(e),n(!0)))}))}));a&&(n=ht(e,i,Tt,t.reportAllChanges),ut((function(r){i=dt("FCP"),n=ht(e,i,Tt,t.reportAllChanges),gt((function(){i.value=performance.now()-r.timeStamp,n(!0)}))})))}))}(bt((function(){var n,r=dt("CLS",0),i=0,a=[],o=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=a[0],n=a[a.length-1];i&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(i+=e.value,a.push(e)):(i=e.value,a=[e])}})),i>r.value&&(r.value=i,r.entries=a,n())},s=pt("layout-shift",o);s&&(n=ht(e,r,Ct,t.reportAllChanges),mt((function(){o(s.takeRecords()),n(!0)})),ut((function(){i=0,r=dt("CLS",0),n=ht(e,r,Ct,t.reportAllChanges),gt((function(){return n()}))})),setTimeout(n,0))})))}((function(t){var n=function(e){var t,n={};if(e.entries.length){var r=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(r&&r.sources&&r.sources.length){var i=(t=r.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];i&&(n={largestShiftTarget:ct(i.node),largestShiftTime:r.startTime,largestShiftValue:r.value,largestShiftSource:i,largestShiftEntry:r,loadState:ot(r.startTime)})}}return Object.assign(e,{attribution:n})}(t);e(n)}),t)},Dt=0,Nt=1/0,kt=0,Ot=function(e){e.forEach((function(e){e.interactionId&&(Nt=Math.min(Nt,e.interactionId),kt=Math.max(kt,e.interactionId),Dt=kt?(kt-Nt)/7+1:0)}))},Mt=function(){return rt?Dt:performance.interactionCount||0},Lt=function(){"interactionCount"in performance||rt||(rt=pt("event",Ot,{type:"event",buffered:!0,durationThreshold:0}))},Pt=[],Bt=new Map,Rt=0,Ft=[],$t=function(e){if(Ft.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Pt[Pt.length-1],n=Bt.get(e.interactionId);if(n||Pt.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};Bt.set(r.id,r),Pt.push(r)}Pt.sort((function(e,t){return t.latency-e.latency})),Pt.length>10&&Pt.splice(10).forEach((function(e){return Bt.delete(e.id)}))}}},xt=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=bt(e),"hidden"===document.visibilityState?e():(n=t(e),mt(e)),n},Ut=[200,500],jt=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},It((function(){var n;Lt();var r,i=dt("INP"),a=function(e){xt((function(){e.forEach($t);var t=function(){var e=Math.min(Pt.length-1,Math.floor((Mt()-Rt)/50));return Pt[e]}();t&&t.latency!==i.value&&(i.value=t.latency,i.entries=t.entries,r())}))},o=pt("event",a,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});r=ht(e,i,Ut,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),mt((function(){a(o.takeRecords()),r(!0)})),ut((function(){Rt=Mt(),Pt.length=0,Bt.clear(),i=dt("INP"),r=ht(e,i,Ut,t.reportAllChanges)})))})))},Vt=[],zt=[],Ht=0,qt=new WeakMap,Wt=new Map,Jt=-1,Kt=function(e){Vt=Vt.concat(e),Gt()},Gt=function(){Jt<0&&(Jt=xt(Xt))},Xt=function(){Wt.size>10&&Wt.forEach((function(e,t){Bt.has(t)||Wt.delete(t)}));var e=Pt.map((function(e){return qt.get(e.entries[0])})),t=zt.length-50;zt=zt.filter((function(n,r){return r>=t||e.includes(n)}));for(var n=new Set,r=0;r<zt.length;r++){var i=zt[r];Yt(i.startTime,i.processingEnd).forEach((function(e){n.add(e)}))}var a=Vt.length-1-50;Vt=Vt.filter((function(e,t){return e.startTime>Ht&&t>a||n.has(e)})),Jt=-1};Ft.push((function(e){e.interactionId&&e.target&&!Wt.has(e.interactionId)&&Wt.set(e.interactionId,e.target)}),(function(e){var t,n=e.startTime+e.duration;Ht=Math.max(Ht,e.processingEnd);for(var r=zt.length-1;r>=0;r--){var i=zt[r];if(Math.abs(n-i.renderTime)<=8){(t=i).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:n,entries:[e]},zt.push(t)),(e.interactionId||"first-input"===e.entryType)&&qt.set(e,t),Gt()}));var Yt=function(e,t){for(var n,r=[],i=0;n=Vt[i];i++)if(!(n.startTime+n.duration<e)){if(n.startTime>t)break;r.push(n)}return r},Zt=function(e,t){it||(it=pt("long-animation-frame",Kt)),jt((function(t){var n=function(e){var t=e.entries[0],n=qt.get(t),r=t.processingStart,i=n.processingEnd,a=n.entries.sort((function(e,t){return e.processingStart-t.processingStart})),o=Yt(t.startTime,i),s=e.entries.find((function(e){return e.target})),c=s&&s.target||Wt.get(t.interactionId),l=[t.startTime+t.duration,i].concat(o.map((function(e){return e.startTime+e.duration}))),u=Math.max.apply(Math,l),f={interactionTarget:ct(c),interactionTargetElement:c,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:u,processedEventEntries:a,longAnimationFrameEntries:o,inputDelay:r-t.startTime,processingDuration:i-r,presentationDelay:Math.max(u-i,0),loadState:ot(t.startTime)};return Object.assign(e,{attribution:f})}(t);e(n)}),t)},Qt=[2500,4e3],en={},tn=function(e,t){!function(e,t){t=t||{},It((function(){var n,r=St(),i=dt("LCP"),a=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<r.firstHiddenTime&&(i.value=Math.max(e.startTime-ft(),0),i.entries=[e],n())}))},o=pt("largest-contentful-paint",a);if(o){n=ht(e,i,Qt,t.reportAllChanges);var s=bt((function(){en[i.id]||(a(o.takeRecords()),o.disconnect(),en[i.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return xt(s)}),{once:!0,capture:!0})})),mt(s),ut((function(r){i=dt("LCP"),n=ht(e,i,Qt,t.reportAllChanges),gt((function(){i.value=performance.now()-r.timeStamp,en[i.id]=!0,n(!0)}))}))}}))}((function(t){var n=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var n=at();if(n){var r=n.activationStart||0,i=e.entries[e.entries.length-1],a=i.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===i.url}))[0],o=Math.max(0,n.responseStart-r),s=Math.max(o,a?(a.requestStart||a.startTime)-r:0),c=Math.max(s,a?a.responseEnd-r:0),l=Math.max(c,i.startTime-r);t={element:ct(i.element),timeToFirstByte:o,resourceLoadDelay:s-o,resourceLoadDuration:c-s,elementRenderDelay:l-c,navigationEntry:n,lcpEntry:i},i.url&&(t.url=i.url),a&&(t.lcpResourceEntry=a)}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)};const nn="@firebase/installations",rn="0.6.23",an=1e4,on=`w:${rn}`,sn="FIS_v2",cn=36e5,ln=new h("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 un(e){return e instanceof p&&e.code.includes("request-failed")}
|
|
442
|
+
nt.registerVersion("firebase","12.17.1","app-compat");var rt,it,at=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},ot=function(e){if("loading"===document.readyState)return"loading";var t=at();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},st=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},ct=function(e,t){var n="";try{for(;e&&9!==e.nodeType;){var r=e,i=r.id?"#"+r.id:st(r)+(r.classList&&r.classList.value&&r.classList.value.trim()&&r.classList.value.trim().length?"."+r.classList.value.trim().replace(/\s+/g,"."):"");if(n.length+i.length>(t||100)-1)return n||i;if(n=n?i+">"+n:i,r.id)break;e=r.parentNode}}catch(e){}return n},lt=-1,ut=function(e){addEventListener("pageshow",(function(t){t.persisted&&(lt=t.timeStamp,e(t))}),!0)},ft=function(){var e=at();return e&&e.activationStart||0},dt=function(e,t){var n=at(),r="navigate";return lt>=0?r="back-forward-cache":n&&(document.prerendering||ft()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},pt=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(e){}},ht=function(e,t,n,r){var i,a;return function(o){t.value>=0&&(o||r)&&((a=t.value-(i||0))||void 0===i)&&(i=t.value,t.delta=a,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},gt=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},mt=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},bt=function(e){var t=!1;return function(){t||(e(),t=!0)}},vt=-1,yt=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},_t=function(e){"hidden"===document.visibilityState&&vt>-1&&(vt="visibilitychange"===e.type?e.timeStamp:0,Et())},wt=function(){addEventListener("visibilitychange",_t,!0),addEventListener("prerenderingchange",_t,!0)},Et=function(){removeEventListener("visibilitychange",_t,!0),removeEventListener("prerenderingchange",_t,!0)},St=function(){return vt<0&&(vt=yt(),wt(),ut((function(){setTimeout((function(){vt=yt(),wt()}),0)}))),{get firstHiddenTime(){return vt}}},It=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},Tt=[1800,3e3],Ct=[.1,.25],At=function(e,t){!function(e,t){t=t||{},function(e,t){t=t||{},It((function(){var n,r=St(),i=dt("FCP"),a=pt("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(a.disconnect(),e.startTime<r.firstHiddenTime&&(i.value=Math.max(e.startTime-ft(),0),i.entries.push(e),n(!0)))}))}));a&&(n=ht(e,i,Tt,t.reportAllChanges),ut((function(r){i=dt("FCP"),n=ht(e,i,Tt,t.reportAllChanges),gt((function(){i.value=performance.now()-r.timeStamp,n(!0)}))})))}))}(bt((function(){var n,r=dt("CLS",0),i=0,a=[],o=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=a[0],n=a[a.length-1];i&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(i+=e.value,a.push(e)):(i=e.value,a=[e])}})),i>r.value&&(r.value=i,r.entries=a,n())},s=pt("layout-shift",o);s&&(n=ht(e,r,Ct,t.reportAllChanges),mt((function(){o(s.takeRecords()),n(!0)})),ut((function(){i=0,r=dt("CLS",0),n=ht(e,r,Ct,t.reportAllChanges),gt((function(){return n()}))})),setTimeout(n,0))})))}((function(t){var n=function(e){var t,n={};if(e.entries.length){var r=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(r&&r.sources&&r.sources.length){var i=(t=r.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];i&&(n={largestShiftTarget:ct(i.node),largestShiftTime:r.startTime,largestShiftValue:r.value,largestShiftSource:i,largestShiftEntry:r,loadState:ot(r.startTime)})}}return Object.assign(e,{attribution:n})}(t);e(n)}),t)},Dt=0,Nt=1/0,kt=0,Ot=function(e){e.forEach((function(e){e.interactionId&&(Nt=Math.min(Nt,e.interactionId),kt=Math.max(kt,e.interactionId),Dt=kt?(kt-Nt)/7+1:0)}))},Mt=function(){return rt?Dt:performance.interactionCount||0},Lt=function(){"interactionCount"in performance||rt||(rt=pt("event",Ot,{type:"event",buffered:!0,durationThreshold:0}))},Pt=[],Bt=new Map,Rt=0,Ft=[],$t=function(e){if(Ft.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Pt[Pt.length-1],n=Bt.get(e.interactionId);if(n||Pt.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};Bt.set(r.id,r),Pt.push(r)}Pt.sort((function(e,t){return t.latency-e.latency})),Pt.length>10&&Pt.splice(10).forEach((function(e){return Bt.delete(e.id)}))}}},xt=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=bt(e),"hidden"===document.visibilityState?e():(n=t(e),mt(e)),n},Ut=[200,500],jt=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},It((function(){var n;Lt();var r,i=dt("INP"),a=function(e){xt((function(){e.forEach($t);var t=function(){var e=Math.min(Pt.length-1,Math.floor((Mt()-Rt)/50));return Pt[e]}();t&&t.latency!==i.value&&(i.value=t.latency,i.entries=t.entries,r())}))},o=pt("event",a,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});r=ht(e,i,Ut,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),mt((function(){a(o.takeRecords()),r(!0)})),ut((function(){Rt=Mt(),Pt.length=0,Bt.clear(),i=dt("INP"),r=ht(e,i,Ut,t.reportAllChanges)})))})))},Vt=[],zt=[],Ht=0,qt=new WeakMap,Wt=new Map,Jt=-1,Kt=function(e){Vt=Vt.concat(e),Gt()},Gt=function(){Jt<0&&(Jt=xt(Xt))},Xt=function(){Wt.size>10&&Wt.forEach((function(e,t){Bt.has(t)||Wt.delete(t)}));var e=Pt.map((function(e){return qt.get(e.entries[0])})),t=zt.length-50;zt=zt.filter((function(n,r){return r>=t||e.includes(n)}));for(var n=new Set,r=0;r<zt.length;r++){var i=zt[r];Yt(i.startTime,i.processingEnd).forEach((function(e){n.add(e)}))}var a=Vt.length-1-50;Vt=Vt.filter((function(e,t){return e.startTime>Ht&&t>a||n.has(e)})),Jt=-1};Ft.push((function(e){e.interactionId&&e.target&&!Wt.has(e.interactionId)&&Wt.set(e.interactionId,e.target)}),(function(e){var t,n=e.startTime+e.duration;Ht=Math.max(Ht,e.processingEnd);for(var r=zt.length-1;r>=0;r--){var i=zt[r];if(Math.abs(n-i.renderTime)<=8){(t=i).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:n,entries:[e]},zt.push(t)),(e.interactionId||"first-input"===e.entryType)&&qt.set(e,t),Gt()}));var Yt=function(e,t){for(var n,r=[],i=0;n=Vt[i];i++)if(!(n.startTime+n.duration<e)){if(n.startTime>t)break;r.push(n)}return r},Zt=function(e,t){it||(it=pt("long-animation-frame",Kt)),jt((function(t){var n=function(e){var t=e.entries[0],n=qt.get(t),r=t.processingStart,i=n.processingEnd,a=n.entries.sort((function(e,t){return e.processingStart-t.processingStart})),o=Yt(t.startTime,i),s=e.entries.find((function(e){return e.target})),c=s&&s.target||Wt.get(t.interactionId),l=[t.startTime+t.duration,i].concat(o.map((function(e){return e.startTime+e.duration}))),u=Math.max.apply(Math,l),f={interactionTarget:ct(c),interactionTargetElement:c,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:u,processedEventEntries:a,longAnimationFrameEntries:o,inputDelay:r-t.startTime,processingDuration:i-r,presentationDelay:Math.max(u-i,0),loadState:ot(t.startTime)};return Object.assign(e,{attribution:f})}(t);e(n)}),t)},Qt=[2500,4e3],en={},tn=function(e,t){!function(e,t){t=t||{},It((function(){var n,r=St(),i=dt("LCP"),a=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<r.firstHiddenTime&&(i.value=Math.max(e.startTime-ft(),0),i.entries=[e],n())}))},o=pt("largest-contentful-paint",a);if(o){n=ht(e,i,Qt,t.reportAllChanges);var s=bt((function(){en[i.id]||(a(o.takeRecords()),o.disconnect(),en[i.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return xt(s)}),{once:!0,capture:!0})})),mt(s),ut((function(r){i=dt("LCP"),n=ht(e,i,Qt,t.reportAllChanges),gt((function(){i.value=performance.now()-r.timeStamp,en[i.id]=!0,n(!0)}))}))}}))}((function(t){var n=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var n=at();if(n){var r=n.activationStart||0,i=e.entries[e.entries.length-1],a=i.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===i.url}))[0],o=Math.max(0,n.responseStart-r),s=Math.max(o,a?(a.requestStart||a.startTime)-r:0),c=Math.max(s,a?a.responseEnd-r:0),l=Math.max(c,i.startTime-r);t={element:ct(i.element),timeToFirstByte:o,resourceLoadDelay:s-o,resourceLoadDuration:c-s,elementRenderDelay:l-c,navigationEntry:n,lcpEntry:i},i.url&&(t.url=i.url),a&&(t.lcpResourceEntry=a)}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)};const nn="@firebase/installations",rn="0.6.23",an=1e4,on=`w:${rn}`,sn="FIS_v2",cn=36e5,ln=new h("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 un(e){return e instanceof p&&e.code.includes("request-failed")}
|
|
443
443
|
/**
|
|
444
444
|
* @license
|
|
445
445
|
* Copyright 2019 Google LLC
|
|
@@ -979,5 +979,5 @@ var ri;(ri=nt).INTERNAL.registerComponent(new v("performance-compat",ni,"PUBLIC"
|
|
|
979
979
|
* See the License for the specific language governing permissions and
|
|
980
980
|
* limitations under the License.
|
|
981
981
|
*/
|
|
982
|
-
return nt.registerVersion("firebase","12.17.
|
|
982
|
+
return nt.registerVersion("firebase","12.17.1","compat-lite"),nt}));
|
|
983
983
|
//# sourceMappingURL=firebase-performance-standalone-compat.js.map
|
package/firebase-performance.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as c}from"https://www.gstatic.com/firebasejs/12.17.0/firebase-app.js";class FirebaseError extends Error{constructor(e,t,c){super(t),this.code=e,this.customData=c,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,c){this.service=e,this.serviceName=t,this.errors=c}create(e,...t){const c=t[0]||{},g=`${this.service}/${e}`,w=this.errors[e],I=w?function replaceTemplate(e,t){try{let c=0,g="";for(;c<e.length;){const w=e.indexOf("{$",c);if(-1===w){g+=e.substring(c);break}const I=e.indexOf("}",w+2);if(-1===I){g+=e.substring(c);break}const _=e.substring(w+2,I),k=t[_];g+=e.substring(c,w)+(null!=k?String(k):`<${_}?>`),c=I+1}return g}catch(t){return e}}(w,c):"Error",_=`${this.serviceName}: ${I} (${g}).`;return new FirebaseError(g,_,c)}}function deepEqual(e,t){if(e===t)return!0;const c=Object.keys(e),g=Object.keys(t);for(const w of c){if(!g.includes(w))return!1;const c=e[w],I=t[w];if(isObject(c)&&isObject(I)){if(!deepEqual(c,I))return!1}else if(c!==I)return!1}for(const e of g)if(!c.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}var g;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(g||(g={}));const w={debug:g.DEBUG,verbose:g.VERBOSE,info:g.INFO,warn:g.WARN,error:g.ERROR,silent:g.SILENT},I=g.INFO,_={[g.DEBUG]:"log",[g.VERBOSE]:"log",[g.INFO]:"info",[g.WARN]:"warn",[g.ERROR]:"error"},defaultLogHandler=(e,t,...c)=>{if(t<e.logLevel)return;const g=(new Date).toISOString(),w=_[t];if(!w)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[w](`[${g}] ${e.name}:`,...c)};var k,C,n=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},r=function(e){if("loading"===document.readyState)return"loading";var t=n();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},i=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},a=function(e,t){var c="";try{for(;e&&9!==e.nodeType;){var g=e,w=g.id?"#"+g.id:i(g)+(g.classList&&g.classList.value&&g.classList.value.trim()&&g.classList.value.trim().length?"."+g.classList.value.trim().replace(/\s+/g,"."):"");if(c.length+w.length>(t||100)-1)return c||w;if(c=c?w+">"+c:w,g.id)break;e=g.parentNode}}catch(e){}return c},M=-1,u=function(e){addEventListener("pageshow",(function(t){t.persisted&&(M=t.timeStamp,e(t))}),!0)},s=function(){var e=n();return e&&e.activationStart||0},f=function(e,t){var c=n(),g="navigate";return M>=0?g="back-forward-cache":c&&(document.prerendering||s()>0?g="prerender":document.wasDiscarded?g="restore":c.type&&(g=c.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:g}},d=function(e,t,c){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var g=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return g.observe(Object.assign({type:e,buffered:!0},c||{})),g}}catch(e){}},l=function(e,t,c,g){var w,I;return function(_){t.value>=0&&(_||g)&&((I=t.value-(w||0))||void 0===w)&&(w=t.value,t.delta=I,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,c),e(t))}},m=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},p=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},v=function(e){var t=!1;return function(){t||(e(),t=!0)}},R=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},T=function(e){"hidden"===document.visibilityState&&R>-1&&(R="visibilitychange"===e.type?e.timeStamp:0,E())},y=function(){addEventListener("visibilitychange",T,!0),addEventListener("prerenderingchange",T,!0)},E=function(){removeEventListener("visibilitychange",T,!0),removeEventListener("prerenderingchange",T,!0)},S=function(){return R<0&&(R=h(),y(),u((function(){setTimeout((function(){R=h(),y()}),0)}))),{get firstHiddenTime(){return R}}},b=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},L=[1800,3e3],O=[.1,.25],D=function(e,t){!function(e,t){t=t||{},function(e,t){t=t||{},b((function(){var c,g=S(),w=f("FCP"),I=d("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(I.disconnect(),e.startTime<g.firstHiddenTime&&(w.value=Math.max(e.startTime-s(),0),w.entries.push(e),c(!0)))}))}));I&&(c=l(e,w,L,t.reportAllChanges),u((function(g){w=f("FCP"),c=l(e,w,L,t.reportAllChanges),m((function(){w.value=performance.now()-g.timeStamp,c(!0)}))})))}))}(v((function(){var c,g=f("CLS",0),w=0,I=[],o=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=I[0],c=I[I.length-1];w&&e.startTime-c.startTime<1e3&&e.startTime-t.startTime<5e3?(w+=e.value,I.push(e)):(w=e.value,I=[e])}})),w>g.value&&(g.value=w,g.entries=I,c())},_=d("layout-shift",o);_&&(c=l(e,g,O,t.reportAllChanges),p((function(){o(_.takeRecords()),c(!0)})),u((function(){w=0,g=f("CLS",0),c=l(e,g,O,t.reportAllChanges),m((function(){return c()}))})),setTimeout(c,0))})))}((function(t){var c=function(e){var t,c={};if(e.entries.length){var g=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(g&&g.sources&&g.sources.length){var w=(t=g.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];w&&(c={largestShiftTarget:a(w.node),largestShiftTime:g.startTime,largestShiftValue:g.value,largestShiftSource:w,largestShiftEntry:g,loadState:r(g.startTime)})}}return Object.assign(e,{attribution:c})}(t);e(c)}),t)},B=0,q=1/0,x=0,A=function(e){e.forEach((function(e){e.interactionId&&(q=Math.min(q,e.interactionId),x=Math.max(x,e.interactionId),B=x?(x-q)/7+1:0)}))},F=function(){return k?B:performance.interactionCount||0},P=function(){"interactionCount"in performance||k||(k=d("event",A,{type:"event",buffered:!0,durationThreshold:0}))},U=[],j=new Map,$=0,V=[],H=function(e){if(V.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=U[U.length-1],c=j.get(e.interactionId);if(c||U.length<10||e.duration>t.latency){if(c)e.duration>c.latency?(c.entries=[e],c.latency=e.duration):e.duration===c.latency&&e.startTime===c.entries[0].startTime&&c.entries.push(e);else{var g={id:e.interactionId,latency:e.duration,entries:[e]};j.set(g.id,g),U.push(g)}U.sort((function(e,t){return t.latency-e.latency})),U.length>10&&U.splice(10).forEach((function(e){return j.delete(e.id)}))}}},N=function(e){var t=self.requestIdleCallback||self.setTimeout,c=-1;return e=v(e),"hidden"===document.visibilityState?e():(c=t(e),p(e)),c},W=[200,500],z=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},b((function(){var c;P();var g,w=f("INP"),a=function(e){N((function(){e.forEach(H);var t=function(){var e=Math.min(U.length-1,Math.floor((F()-$)/50));return U[e]}();t&&t.latency!==w.value&&(w.value=t.latency,w.entries=t.entries,g())}))},I=d("event",a,{durationThreshold:null!==(c=t.durationThreshold)&&void 0!==c?c:40});g=l(e,w,W,t.reportAllChanges),I&&(I.observe({type:"first-input",buffered:!0}),p((function(){a(I.takeRecords()),g(!0)})),u((function(){$=F(),U.length=0,j.clear(),w=f("INP"),g=l(e,w,W,t.reportAllChanges)})))})))},K=[],G=[],J=0,Z=new WeakMap,ee=new Map,te=-1,Q=function(e){K=K.concat(e),X()},X=function(){te<0&&(te=N(Y))},Y=function(){ee.size>10&&ee.forEach((function(e,t){j.has(t)||ee.delete(t)}));var e=U.map((function(e){return Z.get(e.entries[0])})),t=G.length-50;G=G.filter((function(c,g){return g>=t||e.includes(c)}));for(var c=new Set,g=0;g<G.length;g++){var w=G[g];nt(w.startTime,w.processingEnd).forEach((function(e){c.add(e)}))}var I=K.length-1-50;K=K.filter((function(e,t){return e.startTime>J&&t>I||c.has(e)})),te=-1};V.push((function(e){e.interactionId&&e.target&&!ee.has(e.interactionId)&&ee.set(e.interactionId,e.target)}),(function(e){var t,c=e.startTime+e.duration;J=Math.max(J,e.processingEnd);for(var g=G.length-1;g>=0;g--){var w=G[g];if(Math.abs(c-w.renderTime)<=8){(t=w).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:c,entries:[e]},G.push(t)),(e.interactionId||"first-input"===e.entryType)&&Z.set(e,t),X()}));var nt=function(e,t){for(var c,g=[],w=0;c=K[w];w++)if(!(c.startTime+c.duration<e)){if(c.startTime>t)break;g.push(c)}return g},rt=function(e,t){C||(C=d("long-animation-frame",Q)),z((function(t){var c=function(e){var t=e.entries[0],c=Z.get(t),g=t.processingStart,w=c.processingEnd,I=c.entries.sort((function(e,t){return e.processingStart-t.processingStart})),_=nt(t.startTime,w),k=e.entries.find((function(e){return e.target})),C=k&&k.target||ee.get(t.interactionId),M=[t.startTime+t.duration,w].concat(_.map((function(e){return e.startTime+e.duration}))),R=Math.max.apply(Math,M),L={interactionTarget:a(C),interactionTargetElement:C,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:R,processedEventEntries:I,longAnimationFrameEntries:_,inputDelay:g-t.startTime,processingDuration:w-g,presentationDelay:Math.max(R-w,0),loadState:r(t.startTime)};return Object.assign(e,{attribution:L})}(t);e(c)}),t)},ne=[2500,4e3],re={},ot=function(e,t){!function(e,t){t=t||{},b((function(){var c,g=S(),w=f("LCP"),a=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<g.firstHiddenTime&&(w.value=Math.max(e.startTime-s(),0),w.entries=[e],c())}))},I=d("largest-contentful-paint",a);if(I){c=l(e,w,ne,t.reportAllChanges);var _=v((function(){re[w.id]||(a(I.takeRecords()),I.disconnect(),re[w.id]=!0,c(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return N(_)}),{once:!0,capture:!0})})),p(_),u((function(g){w=f("LCP"),c=l(e,w,ne,t.reportAllChanges),m((function(){w.value=performance.now()-g.timeStamp,re[w.id]=!0,c(!0)}))}))}}))}((function(t){var c=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var c=n();if(c){var g=c.activationStart||0,w=e.entries[e.entries.length-1],I=w.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===w.url}))[0],_=Math.max(0,c.responseStart-g),k=Math.max(_,I?(I.requestStart||I.startTime)-g:0),C=Math.max(k,I?I.responseEnd-g:0),M=Math.max(C,w.startTime-g);t={element:a(w.element),timeToFirstByte:_,resourceLoadDelay:k-_,resourceLoadDuration:C-k,elementRenderDelay:M-C,navigationEntry:c,lcpEntry:w},w.url&&(t.url=w.url),I&&(t.lcpResourceEntry=I)}}return Object.assign(e,{attribution:t})}(t);e(c)}),t)};class Component{constructor(e,t,c){this.name=e,this.instanceFactory=t,this.type=c,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let ie,ae;const oe=new WeakMap,se=new WeakMap,ce=new WeakMap,ue=new WeakMap,le=new WeakMap;let de={get(e,t,c){if(e instanceof IDBTransaction){if("done"===t)return se.get(e);if("objectStoreNames"===t)return e.objectStoreNames||ce.get(e);if("store"===t)return c.objectStoreNames[1]?void 0:c.objectStore(c.objectStoreNames[0])}return wrap(e[t])},set:(e,t,c)=>(e[t]=c,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return ae||(ae=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(oe.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...c){const g=e.call(unwrap(this),t,...c);return ce.set(g,t.sort?t.sort():[t]),wrap(g)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(se.has(e))return;const t=new Promise(((t,c)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{c(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));se.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return ie||(ie=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,de):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,c)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{c(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&oe.set(t,e)})).catch((()=>{})),le.set(t,e),t}(e);if(ue.has(e))return ue.get(e);const t=transformCachableValue(e);return t!==e&&(ue.set(e,t),le.set(t,e)),t}const unwrap=e=>le.get(e);const fe=["get","getKey","getAll","getAllKeys","count"],pe=["put","add","delete","clear"],ge=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(ge.get(t))return ge.get(t);const c=t.replace(/FromIndex$/,""),g=t!==c,w=pe.includes(c);if(!(c in(g?IDBIndex:IDBObjectStore).prototype)||!w&&!fe.includes(c))return;const method=async function(e,...t){const I=this.transaction(e,w?"readwrite":"readonly");let _=I.store;return g&&(_=_.index(t.shift())),(await Promise.all([_[c](...t),w&&I.done]))[0]};return ge.set(t,method),method}!function replaceTraps(e){de=e(de)}((e=>({...e,get:(t,c,g)=>getMethod(t,c)||e.get(t,c,g),has:(t,c)=>!!getMethod(t,c)||e.has(t,c)})));const me="@firebase/installations",he="0.6.23",ve=1e4,be=`w:${he}`,Te="FIS_v2",ye=36e5,Ee=new ErrorFactory("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 isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const c=(await t.json()).error;return Ee.create("request-failed",{requestName:e,serverCode:c.code,serverMessage:c.message,serverStatus:c.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const c=getHeaders(e);return c.append("Authorization",function getAuthorizationHeader(e){return`${Te} ${e}`}(t)),c}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const Se=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return Se.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const we=new Map;function fidChanged(e,t){const c=getKey(e);callFidChangeCallbacks(c,t),function broadcastFidChange(e,t){const c=function getBroadcastChannel(){!Ie&&"BroadcastChannel"in self&&(Ie=new BroadcastChannel("[Firebase] FID Change"),Ie.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return Ie}();c&&c.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===we.size&&Ie&&(Ie.close(),Ie=null)}()}(c,t)}function callFidChangeCallbacks(e,t){const c=we.get(e);if(c)for(const e of c)e(t)}let Ie=null;const _e="firebase-installations-store";let Ae=null;function getDbPromise(){return Ae||(Ae=function openDB(e,t,{blocked:c,upgrade:g,blocking:w,terminated:I}={}){const _=indexedDB.open(e,t),k=wrap(_);return g&&_.addEventListener("upgradeneeded",(e=>{g(wrap(_.result),e.oldVersion,e.newVersion,wrap(_.transaction),e)})),c&&_.addEventListener("blocked",(e=>c(e.oldVersion,e.newVersion,e))),k.then((e=>{I&&e.addEventListener("close",(()=>I())),w&&e.addEventListener("versionchange",(e=>w(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),k}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(_e)}})),Ae}async function set(e,t){const c=getKey(e),g=(await getDbPromise()).transaction(_e,"readwrite"),w=g.objectStore(_e),I=await w.get(c);return await w.put(t,c),await g.done,I&&I.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),c=(await getDbPromise()).transaction(_e,"readwrite");await c.objectStore(_e).delete(t),await c.done}async function update(e,t){const c=getKey(e),g=(await getDbPromise()).transaction(_e,"readwrite"),w=g.objectStore(_e),I=await w.get(c),_=t(I);return void 0===_?await w.delete(c):await w.put(_,c),await g.done,!_||I&&I.fid===_.fid||fidChanged(e,_.fid),_}async function getInstallationEntry(e){let t;const c=await update(e.appConfig,(c=>{const g=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(c),w=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(Ee.create("app-offline"))}}const c={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},g=async function registerInstallation(e,t){try{const c=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:c}){const g=getInstallationsEndpoint(e),w=getHeaders(e),I=t.getImmediate({optional:!0});if(I){const e=await I.getHeartbeatsHeader();e&&w.append("x-firebase-client",e)}const _={fid:c,authVersion:Te,appId:e.appId,sdkVersion:be},k={method:"POST",headers:w,body:JSON.stringify(_)},C=await retryIfServerError((()=>fetch(g,k)));if(C.ok){const e=await C.json();return{fid:e.fid||c,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",C)}(e,t);return set(e.appConfig,c)}catch(c){throw isServerError(c)&&409===c.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),c}}(e,c);return{installationEntry:c,registrationPromise:g}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,g);return t=w.registrationPromise,w.installationEntry}));return""===c.fid?{installationEntry:await t}:{installationEntry:c,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:c}=await getInstallationEntry(e);return c||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw Ee.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+ve<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},c){const g=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,c),w=getHeadersWithAuth(e,c),I=t.getImmediate({optional:!0});if(I){const e=await I.getHeartbeatsHeader();e&&w.append("x-firebase-client",e)}const _={installation:{sdkVersion:be,appId:e.appId}},k={method:"POST",headers:w,body:JSON.stringify(_)},C=await retryIfServerError((()=>fetch(g,k)));if(C.ok){return extractAuthTokenInfoFromResponse(await C.json())}throw await getErrorFromResponse("Generate Auth Token",C)}async function refreshAuthToken(e,t=!1){let c;const g=await update(e.appConfig,(g=>{if(!isEntryRegistered(g))throw Ee.create("not-registered");const w=g.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+ye}(e)}(w))return g;if(1===w.requestStatus)return c=async function waitUntilAuthTokenRequest(e,t){let c=await updateAuthTokenRequest(e.appConfig);for(;1===c.authToken.requestStatus;)await sleep(100),c=await updateAuthTokenRequest(e.appConfig);const g=c.authToken;return 0===g.requestStatus?refreshAuthToken(e,t):g}(e,t),g;{if(!navigator.onLine)throw Ee.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(g);return c=async function fetchAuthTokenFromServer(e,t){try{const c=await generateAuthTokenRequest(e,t),g={...t,authToken:c};return await set(e.appConfig,g),c}catch(c){if(!isServerError(c)||401!==c.customData.serverCode&&404!==c.customData.serverCode){const c={...t,authToken:{requestStatus:0}};await set(e.appConfig,c)}else await remove(e.appConfig);throw c}}(e,t),t}}));return c?await c:g.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw Ee.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+ve<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const c=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(c);return(await refreshAuthToken(c,t)).token}function getMissingValueError(e){return Ee.create("missing-app-config-values",{valueName:e})}const ke="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),c=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const c of t)if(!e.options[c])throw getMissingValueError(c);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:c,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),c=_getProvider(t,ke).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:c,registrationPromise:g}=await getInstallationEntry(t);return g?g.catch(console.error):refreshAuthToken(t).catch(console.error),c.fid}(c),getToken:e=>getToken(c,e)}};!function registerInstallations(){t(new Component(ke,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(me,he),e(me,he,"esm2020");const Ce="@firebase/performance",Me="0.7.13",Re=Me,Pe="FB-PERF-TRACE-MEASURE",Le="_wt_",Ne="_fcp",Oe="_fid",De="_lcp",Fe="_inp",Be="_cls",qe="@firebase/performance/config",xe="@firebase/performance/configexpire",Ue="Performance",je=new ErrorFactory("performance",Ue,{"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."}),$e=new class Logger{constructor(e){this.name=e,this._logLevel=I,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in g))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?w[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,g.DEBUG,...e),this._logHandler(this,g.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,g.VERBOSE,...e),this._logHandler(this,g.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,g.INFO,...e),this._logHandler(this,g.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,g.WARN,...e),this._logHandler(this,g.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,g.ERROR,...e),this._logHandler(this,g.ERROR,...e)}}(Ue);let He,Ve,ze,We;$e.logLevel=g.INFO;class Api{constructor(e){if(this.window=e,!e)throw je.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay),this.onLCP=ot,this.onINP=rt,this.onCLS=D}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,c){this.performance&&this.performance.measure&&this.performance.measure(e,t,c)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}()?!!function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()||($e.info("IndexedDB is not supported by current browser"),!1):($e.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,t){if(!this.PerformanceObserver)return;new this.PerformanceObserver((e=>{for(const c of e.getEntries())t(c)})).observe({entryTypes:[e]})}static getInstance(){return void 0===He&&(He=new Api(Ve)),He}}function getIid(){return ze}function mergeStrings(e,t){const c=e.length-t.length;if(c<0||c>1)throw je.create("invalid String merger input");const g=[];for(let c=0;c<e.length;c++)g.push(e.charAt(c)),t.length>c&&g.push(t.charAt(c));return g.join("")}class SettingsService{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=mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=mergeStrings("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12,this.logMaxFlushSize=40}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===We&&(We=new SettingsService),We}}var Ke;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VISIBLE=1]="VISIBLE",e[e.HIDDEN=2]="HIDDEN"}(Ke||(Ke={}));const Ge=["firebase_","google_","ga_"],Je=new RegExp("^[a-zA-Z]\\w*$");function getServiceWorkerStatus(){const e=Api.getInstance().navigator;return e?.serviceWorker?e.serviceWorker.controller?2:3:1}function getVisibilityState(){switch(Api.getInstance().document.visibilityState){case"visible":return Ke.VISIBLE;case"hidden":return Ke.HIDDEN;default:return Ke.UNKNOWN}}function getEffectiveConnectionType(){const e=Api.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}function getAppId(e){const t=e.options?.appId;if(!t)throw je.create("no app id");return t}const Qe="0.0.1",Ze={loggingEnabled:!0},Xe="FIREBASE_INSTALLATIONS_AUTH";function getConfig(e,t){const c=function getStoredConfig(){const e=Api.getInstance().localStorage;if(!e)return;const t=e.getItem(xe);if(!t||!function configValid(e){return Number(e)>Date.now()}(t))return;const c=e.getItem(qe);if(!c)return;try{return JSON.parse(c)}catch{return}}();return c?(processConfig(c),Promise.resolve()):function getRemoteConfig(e,t){return function getAuthTokenPromise(e){const t=e.getToken();return t.then((e=>{})),t}(e.installations).then((c=>{const g=function getProjectId(e){const t=e.options?.projectId;if(!t)throw je.create("no project id");return t}(e.app),w=function getApiKey(e){const t=e.options?.apiKey;if(!t)throw je.create("no api key");return t}(e.app),I=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${g}/namespaces/fireperf:fetch?key=${w}`,{method:"POST",headers:{Authorization:`${Xe} ${c}`},body:JSON.stringify({app_instance_id:t,app_instance_id_token:c,app_id:getAppId(e.app),app_version:Re,sdk_version:Qe})});return fetch(I).then((e=>{if(e.ok)return e.json();throw je.create("RC response not ok")}))})).catch((()=>{$e.info(Ye)}))}(e,t).then(processConfig).then((e=>function storeConfig(e){const t=Api.getInstance().localStorage;if(!e||!t)return;t.setItem(qe,JSON.stringify(e)),t.setItem(xe,String(Date.now()+60*SettingsService.getInstance().configTimeToLive*60*1e3))}(e)),(()=>{}))}const Ye="Could not fetch config, will use default configs";function processConfig(e){if(!e)return e;const t=SettingsService.getInstance(),c=e.entries||{};return void 0!==c.fpr_enabled?t.loggingEnabled="true"===String(c.fpr_enabled):t.loggingEnabled=Ze.loggingEnabled,c.fpr_log_source?t.logSource=Number(c.fpr_log_source):Ze.logSource&&(t.logSource=Ze.logSource),c.fpr_log_endpoint_url?t.logEndPointUrl=c.fpr_log_endpoint_url:Ze.logEndPointUrl&&(t.logEndPointUrl=Ze.logEndPointUrl),c.fpr_log_transport_key?t.transportKey=c.fpr_log_transport_key:Ze.transportKey&&(t.transportKey=Ze.transportKey),void 0!==c.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(c.fpr_vc_network_request_sampling_rate):void 0!==Ze.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=Ze.networkRequestsSamplingRate),void 0!==c.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(c.fpr_vc_trace_sampling_rate):void 0!==Ze.tracesSamplingRate&&(t.tracesSamplingRate=Ze.tracesSamplingRate),c.fpr_log_max_flush_size?t.logMaxFlushSize=Number(c.fpr_log_max_flush_size):Ze.logMaxFlushSize&&(t.logMaxFlushSize=Ze.logMaxFlushSize),t.logTraceAfterSampling=shouldLogAfterSampling(t.tracesSamplingRate),t.logNetworkAfterSampling=shouldLogAfterSampling(t.networkRequestsSamplingRate),e}function shouldLogAfterSampling(e){return Math.random()<=e}let et,tt=1;function getInitializationPromise(e){return tt=2,et=et||function initializePerf(e){return function getDocumentReadyComplete(){const e=Api.getInstance().document;return new Promise((t=>{if(e&&"complete"!==e.readyState){const handler=()=>{"complete"===e.readyState&&(e.removeEventListener("readystatechange",handler),t())};e.addEventListener("readystatechange",handler)}else t()}))}().then((()=>function getIidPromise(e){const t=e.getId();return t.then((e=>{ze=e})),t}(e.installations))).then((t=>getConfig(e,t))).then((()=>changeInitializationStatus()),(()=>changeInitializationStatus()))}(e),et}function changeInitializationStatus(){tt=3}const it=1e4,at=new TextEncoder;let st,ct=3,ut=[],lt=!1;function processQueue(e){setTimeout((()=>{ct<=0||(ut.length>0&&function dispatchQueueEvents(){const e=ut.splice(0,1e3);(function postToFlEndpoint(e){const t=SettingsService.getInstance().getFlTransportFullUrl();return at.encode(e).length<=65536&&navigator.sendBeacon&&navigator.sendBeacon(t,e)?Promise.resolve():fetch(t,{method:"POST",body:e})})(buildPayload(e)).then((()=>{ct=3})).catch((()=>{ut=[...e,...ut],ct--,$e.info(`Tries left: ${ct}.`),processQueue(it)}))}(),processQueue(it))}),e)}function buildPayload(e){const t=e.map((e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)}))),c={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:SettingsService.getInstance().logSource,log_event:t};return JSON.stringify(c)}function transportHandler(e){return(...t)=>{!function addToQueue(e){if(!e.eventTime||!e.message)throw je.create("invalid cc log");ut=[...ut,e]}({message:e(...t),eventTime:Date.now()})}}function flushQueuedEvents(){const e=SettingsService.getInstance().getFlTransportFullUrl();for(;ut.length>0;){const t=ut.splice(-SettingsService.getInstance().logMaxFlushSize),c=buildPayload(t);if(!navigator.sendBeacon||!navigator.sendBeacon(e,c)){ut=[...ut,...t];break}}if(ut.length>0){const t=buildPayload(ut);fetch(e,{method:"POST",body:t}).catch((()=>{$e.info("Failed flushing queued events.")}))}}function sendLog(e,t){st||(st={send:transportHandler(serializer),flush:flushQueuedEvents}),st.send(e,t)}function logTrace(e){const t=SettingsService.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&Api.getInstance().requiredApisAvailable()&&(!function isPerfInitialized(){return 3===tt}()?getInitializationPromise(e.performanceController).then((()=>sendTraceLog(e)),(()=>sendTraceLog(e))):sendTraceLog(e))}function sendTraceLog(e){if(!getIid())return;const t=SettingsService.getInstance();t.loggingEnabled&&t.logTraceAfterSampling&&sendLog(e,1)}function serializer(e,t){return 0===t?function serializeNetworkRequest(e){const t={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},c={application_info:getApplicationInfo(e.performanceController.app),network_request_metric:t};return JSON.stringify(c)}(e):function serializeTrace(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);const c=e.getAttributes();0!==Object.keys(c).length&&(t.custom_attributes=c);const g={application_info:getApplicationInfo(e.performanceController.app),trace_metric:t};return JSON.stringify(g)}(e)}function getApplicationInfo(e){return{google_app_id:getAppId(e),app_instance_id:getIid(),web_app_info:{sdk_version:Re,page_url:Api.getInstance().getUrl(),service_worker_status:getServiceWorkerStatus(),visibility_state:getVisibilityState(),effective_connection_type:getEffectiveConnectionType()},application_process_state:0}}function createNetworkRequestEntry(e,t){const c=t;if(!c||void 0===c.responseStart)return;const g=Api.getInstance().getTimeOrigin(),w=Math.floor(1e3*(c.startTime+g)),I=c.responseStart?Math.floor(1e3*(c.responseStart-c.startTime)):void 0,_=Math.floor(1e3*(c.responseEnd-c.startTime));!function logNetworkRequest(e){const t=SettingsService.getInstance();if(!t.instrumentationEnabled)return;const c=e.url,g=t.logEndPointUrl.split("?")[0],w=t.flTransportEndpointUrl.split("?")[0];c!==g&&c!==w&&t.loggingEnabled&&t.logNetworkAfterSampling&&sendLog(e,0)}({performanceController:e,url:c.name&&c.name.split("?")[0],responsePayloadBytes:c.transferSize,startTimeUs:w,timeToResponseInitiatedUs:I,timeToResponseCompletedUs:_})}const dt=["_fp",Ne,Oe,De,Be,Fe];class Trace{constructor(e,t,c=!1,g){this.performanceController=e,this.name=t,this.isAuto=c,this.state=1,this.customAttributes={},this.counters={},this.api=Api.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=g||`${Pe}-${this.randomId}-${this.name}`,g&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw je.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw je.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(),logTrace(this)}record(e,t,c){if(e<=0)throw je.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw je.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),c&&c.attributes&&(this.customAttributes={...c.attributes}),c&&c.metrics)for(const e of Object.keys(c.metrics))isNaN(Number(c.metrics[e]))||(this.counters[e]=Math.floor(Number(c.metrics[e])));logTrace(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(!function isValidMetricName(e,t){return!(0===e.length||e.length>100)&&(t&&t.startsWith(Le)&&dt.indexOf(e)>-1||!e.startsWith("_"))}(e,this.name))throw je.create("invalid custom metric name",{customMetricName:e});this.counters[e]=function convertMetricValueToInteger(e){const t=Math.floor(e);return t<e&&$e.info(`Metric value should be an Integer, setting the value as : ${t}.`),t}(t??0)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){const c=function isValidCustomAttributeName(e){return!(0===e.length||e.length>40)&&(!Ge.some((t=>e.startsWith(t)))&&!!e.match(Je))}(e),g=function isValidCustomAttributeValue(e){return 0!==e.length&&e.length<=100}(t);if(c&&g)this.customAttributes[e]=t;else{if(!c)throw je.create("invalid attribute name",{attributeName:e});if(!g)throw je.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return{...this.customAttributes}}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){const e=this.api.getEntriesByName(this.traceMeasure),t=e&&e[0];t&&(this.durationUs=Math.floor(1e3*t.duration),this.startTimeUs=Math.floor(1e3*(t.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,c,g,w){const I=Api.getInstance().getUrl();if(!I)return;const _=new Trace(e,Le+I,!0),k=Math.floor(1e3*Api.getInstance().getTimeOrigin());_.setStartTime(k),t&&t[0]&&(_.setDuration(Math.floor(1e3*t[0].duration)),_.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),_.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),_.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));if(c){const e=c.find((e=>"first-paint"===e.name));e&&e.startTime&&_.putMetric("_fp",Math.floor(1e3*e.startTime));const t=c.find((e=>"first-contentful-paint"===e.name));t&&t.startTime&&_.putMetric(Ne,Math.floor(1e3*t.startTime)),w&&_.putMetric(Oe,Math.floor(1e3*w))}this.addWebVitalMetric(_,De,"lcp_element",g.lcp),this.addWebVitalMetric(_,Be,"cls_largestShiftTarget",g.cls),this.addWebVitalMetric(_,Fe,"inp_interactionTarget",g.inp),logTrace(_),function flushLogs(){st&&st.flush()}()}static addWebVitalMetric(e,t,c,g){g&&(e.putMetric(t,Math.floor(1e3*g.value)),g.elementAttribution&&(g.elementAttribution.length>100?e.putAttribute(c,g.elementAttribution.substring(0,100)):e.putAttribute(c,g.elementAttribution)))}static createUserTimingTrace(e,t){logTrace(new Trace(e,t,!1,t))}}let ft,pt={},gt=!1;function setupOobResources(e){getIid()&&(setTimeout((()=>function setupOobTraces(e){const t=Api.getInstance();"onpagehide"in window?t.document.addEventListener("pagehide",(()=>sendOobTrace(e))):t.document.addEventListener("unload",(()=>sendOobTrace(e)));t.document.addEventListener("visibilitychange",(()=>{"hidden"===t.document.visibilityState&&sendOobTrace(e)})),t.onFirstInputDelay&&t.onFirstInputDelay((e=>{ft=e}));t.onLCP((e=>{pt.lcp={value:e.value,elementAttribution:e.attribution?.element}})),t.onCLS((e=>{pt.cls={value:e.value,elementAttribution:e.attribution?.largestShiftTarget}})),t.onINP((e=>{pt.inp={value:e.value,elementAttribution:e.attribution?.interactionTarget}}))}(e)),0),setTimeout((()=>function setupNetworkRequests(e){const t=Api.getInstance(),c=t.getEntriesByType("resource");for(const t of c)createNetworkRequestEntry(e,t);t.setupObserver("resource",(t=>createNetworkRequestEntry(e,t)))}(e)),0),setTimeout((()=>function setupUserTimingTraces(e){const t=Api.getInstance(),c=t.getEntriesByType("measure");for(const t of c)createUserTimingTrace(e,t);t.setupObserver("measure",(t=>createUserTimingTrace(e,t)))}(e)),0))}function createUserTimingTrace(e,t){const c=t.name;c.substring(0,21)!==Pe&&Trace.createUserTimingTrace(e,c)}function sendOobTrace(e){if(!gt){gt=!0;const t=Api.getInstance(),c=t.getEntriesByType("navigation"),g=t.getEntriesByType("paint");setTimeout((()=>{Trace.createOobTrace(e,c,g,pt,ft)}),0)}}class PerformanceController{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==e?.dataCollectionEnabled&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==e?.instrumentationEnabled&&(this.instrumentationEnabled=e.instrumentationEnabled),Api.getInstance().requiredApisAvailable()?function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let c=!0;const g="validate-browser-context-for-indexeddb-analytics-module",w=self.indexedDB.open(g);w.onsuccess=()=>{w.result.close(),c||self.indexedDB.deleteDatabase(g),e(!0)},w.onupgradeneeded=()=>{c=!1},w.onerror=()=>{t(w.error?.message||"")}}catch(e){t(e)}}))}().then((e=>{e&&(!function setupTransportService(){lt||(processQueue(5500),lt=!0)}(),getInitializationPromise(this).then((()=>setupOobResources(this)),(()=>setupOobResources(this))),this.initialized=!0)})).catch((e=>{$e.info(`Environment doesn't support IndexedDB: ${e}`)})):$e.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){SettingsService.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return SettingsService.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){SettingsService.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return SettingsService.getInstance().dataCollectionEnabled}}function getPerformance(e=c()){e=getModularInstance(e);return _getProvider(e,"performance").getImmediate()}function initializePerformance(e,t){e=getModularInstance(e);const c=_getProvider(e,"performance");if(c.isInitialized()){const e=c.getImmediate();if(deepEqual(c.getOptions(),t??{}))return e;throw je.create("already initialized")}return c.initialize({options:t})}function trace(e,t){return e=getModularInstance(e),new Trace(e,t)}const factory=(e,{options:t})=>{const c=e.getProvider("app").getImmediate(),g=e.getProvider("installations-internal").getImmediate();if("[DEFAULT]"!==c.name)throw je.create("FB not default");if("undefined"==typeof window)throw je.create("no window");!function setupApi(e){Ve=e}(window);const w=new PerformanceController(c,g);return w._init(t),w};!function registerPerformance(){t(new Component("performance",factory,"PUBLIC")),e(Ce,Me),e(Ce,Me,"esm2020")}();export{getPerformance,initializePerformance,trace};
|
|
1
|
+
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as c}from"https://www.gstatic.com/firebasejs/12.17.1/firebase-app.js";class FirebaseError extends Error{constructor(e,t,c){super(t),this.code=e,this.customData=c,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,c){this.service=e,this.serviceName=t,this.errors=c}create(e,...t){const c=t[0]||{},g=`${this.service}/${e}`,w=this.errors[e],I=w?function replaceTemplate(e,t){try{let c=0,g="";for(;c<e.length;){const w=e.indexOf("{$",c);if(-1===w){g+=e.substring(c);break}const I=e.indexOf("}",w+2);if(-1===I){g+=e.substring(c);break}const _=e.substring(w+2,I),k=t[_];g+=e.substring(c,w)+(null!=k?String(k):`<${_}?>`),c=I+1}return g}catch(t){return e}}(w,c):"Error",_=`${this.serviceName}: ${I} (${g}).`;return new FirebaseError(g,_,c)}}function deepEqual(e,t){if(e===t)return!0;const c=Object.keys(e),g=Object.keys(t);for(const w of c){if(!g.includes(w))return!1;const c=e[w],I=t[w];if(isObject(c)&&isObject(I)){if(!deepEqual(c,I))return!1}else if(c!==I)return!1}for(const e of g)if(!c.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}var g;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(g||(g={}));const w={debug:g.DEBUG,verbose:g.VERBOSE,info:g.INFO,warn:g.WARN,error:g.ERROR,silent:g.SILENT},I=g.INFO,_={[g.DEBUG]:"log",[g.VERBOSE]:"log",[g.INFO]:"info",[g.WARN]:"warn",[g.ERROR]:"error"},defaultLogHandler=(e,t,...c)=>{if(t<e.logLevel)return;const g=(new Date).toISOString(),w=_[t];if(!w)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[w](`[${g}] ${e.name}:`,...c)};var k,C,n=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},r=function(e){if("loading"===document.readyState)return"loading";var t=n();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},i=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},a=function(e,t){var c="";try{for(;e&&9!==e.nodeType;){var g=e,w=g.id?"#"+g.id:i(g)+(g.classList&&g.classList.value&&g.classList.value.trim()&&g.classList.value.trim().length?"."+g.classList.value.trim().replace(/\s+/g,"."):"");if(c.length+w.length>(t||100)-1)return c||w;if(c=c?w+">"+c:w,g.id)break;e=g.parentNode}}catch(e){}return c},M=-1,u=function(e){addEventListener("pageshow",(function(t){t.persisted&&(M=t.timeStamp,e(t))}),!0)},s=function(){var e=n();return e&&e.activationStart||0},f=function(e,t){var c=n(),g="navigate";return M>=0?g="back-forward-cache":c&&(document.prerendering||s()>0?g="prerender":document.wasDiscarded?g="restore":c.type&&(g=c.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:g}},d=function(e,t,c){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var g=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return g.observe(Object.assign({type:e,buffered:!0},c||{})),g}}catch(e){}},l=function(e,t,c,g){var w,I;return function(_){t.value>=0&&(_||g)&&((I=t.value-(w||0))||void 0===w)&&(w=t.value,t.delta=I,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,c),e(t))}},m=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},p=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},v=function(e){var t=!1;return function(){t||(e(),t=!0)}},R=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},T=function(e){"hidden"===document.visibilityState&&R>-1&&(R="visibilitychange"===e.type?e.timeStamp:0,E())},y=function(){addEventListener("visibilitychange",T,!0),addEventListener("prerenderingchange",T,!0)},E=function(){removeEventListener("visibilitychange",T,!0),removeEventListener("prerenderingchange",T,!0)},S=function(){return R<0&&(R=h(),y(),u((function(){setTimeout((function(){R=h(),y()}),0)}))),{get firstHiddenTime(){return R}}},b=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},L=[1800,3e3],O=[.1,.25],D=function(e,t){!function(e,t){t=t||{},function(e,t){t=t||{},b((function(){var c,g=S(),w=f("FCP"),I=d("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(I.disconnect(),e.startTime<g.firstHiddenTime&&(w.value=Math.max(e.startTime-s(),0),w.entries.push(e),c(!0)))}))}));I&&(c=l(e,w,L,t.reportAllChanges),u((function(g){w=f("FCP"),c=l(e,w,L,t.reportAllChanges),m((function(){w.value=performance.now()-g.timeStamp,c(!0)}))})))}))}(v((function(){var c,g=f("CLS",0),w=0,I=[],o=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=I[0],c=I[I.length-1];w&&e.startTime-c.startTime<1e3&&e.startTime-t.startTime<5e3?(w+=e.value,I.push(e)):(w=e.value,I=[e])}})),w>g.value&&(g.value=w,g.entries=I,c())},_=d("layout-shift",o);_&&(c=l(e,g,O,t.reportAllChanges),p((function(){o(_.takeRecords()),c(!0)})),u((function(){w=0,g=f("CLS",0),c=l(e,g,O,t.reportAllChanges),m((function(){return c()}))})),setTimeout(c,0))})))}((function(t){var c=function(e){var t,c={};if(e.entries.length){var g=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(g&&g.sources&&g.sources.length){var w=(t=g.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];w&&(c={largestShiftTarget:a(w.node),largestShiftTime:g.startTime,largestShiftValue:g.value,largestShiftSource:w,largestShiftEntry:g,loadState:r(g.startTime)})}}return Object.assign(e,{attribution:c})}(t);e(c)}),t)},B=0,q=1/0,x=0,A=function(e){e.forEach((function(e){e.interactionId&&(q=Math.min(q,e.interactionId),x=Math.max(x,e.interactionId),B=x?(x-q)/7+1:0)}))},F=function(){return k?B:performance.interactionCount||0},P=function(){"interactionCount"in performance||k||(k=d("event",A,{type:"event",buffered:!0,durationThreshold:0}))},U=[],j=new Map,$=0,V=[],H=function(e){if(V.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=U[U.length-1],c=j.get(e.interactionId);if(c||U.length<10||e.duration>t.latency){if(c)e.duration>c.latency?(c.entries=[e],c.latency=e.duration):e.duration===c.latency&&e.startTime===c.entries[0].startTime&&c.entries.push(e);else{var g={id:e.interactionId,latency:e.duration,entries:[e]};j.set(g.id,g),U.push(g)}U.sort((function(e,t){return t.latency-e.latency})),U.length>10&&U.splice(10).forEach((function(e){return j.delete(e.id)}))}}},N=function(e){var t=self.requestIdleCallback||self.setTimeout,c=-1;return e=v(e),"hidden"===document.visibilityState?e():(c=t(e),p(e)),c},W=[200,500],z=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},b((function(){var c;P();var g,w=f("INP"),a=function(e){N((function(){e.forEach(H);var t=function(){var e=Math.min(U.length-1,Math.floor((F()-$)/50));return U[e]}();t&&t.latency!==w.value&&(w.value=t.latency,w.entries=t.entries,g())}))},I=d("event",a,{durationThreshold:null!==(c=t.durationThreshold)&&void 0!==c?c:40});g=l(e,w,W,t.reportAllChanges),I&&(I.observe({type:"first-input",buffered:!0}),p((function(){a(I.takeRecords()),g(!0)})),u((function(){$=F(),U.length=0,j.clear(),w=f("INP"),g=l(e,w,W,t.reportAllChanges)})))})))},K=[],G=[],J=0,Z=new WeakMap,ee=new Map,te=-1,Q=function(e){K=K.concat(e),X()},X=function(){te<0&&(te=N(Y))},Y=function(){ee.size>10&&ee.forEach((function(e,t){j.has(t)||ee.delete(t)}));var e=U.map((function(e){return Z.get(e.entries[0])})),t=G.length-50;G=G.filter((function(c,g){return g>=t||e.includes(c)}));for(var c=new Set,g=0;g<G.length;g++){var w=G[g];nt(w.startTime,w.processingEnd).forEach((function(e){c.add(e)}))}var I=K.length-1-50;K=K.filter((function(e,t){return e.startTime>J&&t>I||c.has(e)})),te=-1};V.push((function(e){e.interactionId&&e.target&&!ee.has(e.interactionId)&&ee.set(e.interactionId,e.target)}),(function(e){var t,c=e.startTime+e.duration;J=Math.max(J,e.processingEnd);for(var g=G.length-1;g>=0;g--){var w=G[g];if(Math.abs(c-w.renderTime)<=8){(t=w).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:c,entries:[e]},G.push(t)),(e.interactionId||"first-input"===e.entryType)&&Z.set(e,t),X()}));var nt=function(e,t){for(var c,g=[],w=0;c=K[w];w++)if(!(c.startTime+c.duration<e)){if(c.startTime>t)break;g.push(c)}return g},rt=function(e,t){C||(C=d("long-animation-frame",Q)),z((function(t){var c=function(e){var t=e.entries[0],c=Z.get(t),g=t.processingStart,w=c.processingEnd,I=c.entries.sort((function(e,t){return e.processingStart-t.processingStart})),_=nt(t.startTime,w),k=e.entries.find((function(e){return e.target})),C=k&&k.target||ee.get(t.interactionId),M=[t.startTime+t.duration,w].concat(_.map((function(e){return e.startTime+e.duration}))),R=Math.max.apply(Math,M),L={interactionTarget:a(C),interactionTargetElement:C,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:R,processedEventEntries:I,longAnimationFrameEntries:_,inputDelay:g-t.startTime,processingDuration:w-g,presentationDelay:Math.max(R-w,0),loadState:r(t.startTime)};return Object.assign(e,{attribution:L})}(t);e(c)}),t)},ne=[2500,4e3],re={},ot=function(e,t){!function(e,t){t=t||{},b((function(){var c,g=S(),w=f("LCP"),a=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<g.firstHiddenTime&&(w.value=Math.max(e.startTime-s(),0),w.entries=[e],c())}))},I=d("largest-contentful-paint",a);if(I){c=l(e,w,ne,t.reportAllChanges);var _=v((function(){re[w.id]||(a(I.takeRecords()),I.disconnect(),re[w.id]=!0,c(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return N(_)}),{once:!0,capture:!0})})),p(_),u((function(g){w=f("LCP"),c=l(e,w,ne,t.reportAllChanges),m((function(){w.value=performance.now()-g.timeStamp,re[w.id]=!0,c(!0)}))}))}}))}((function(t){var c=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var c=n();if(c){var g=c.activationStart||0,w=e.entries[e.entries.length-1],I=w.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===w.url}))[0],_=Math.max(0,c.responseStart-g),k=Math.max(_,I?(I.requestStart||I.startTime)-g:0),C=Math.max(k,I?I.responseEnd-g:0),M=Math.max(C,w.startTime-g);t={element:a(w.element),timeToFirstByte:_,resourceLoadDelay:k-_,resourceLoadDuration:C-k,elementRenderDelay:M-C,navigationEntry:c,lcpEntry:w},w.url&&(t.url=w.url),I&&(t.lcpResourceEntry=I)}}return Object.assign(e,{attribution:t})}(t);e(c)}),t)};class Component{constructor(e,t,c){this.name=e,this.instanceFactory=t,this.type=c,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let ie,ae;const oe=new WeakMap,se=new WeakMap,ce=new WeakMap,ue=new WeakMap,le=new WeakMap;let de={get(e,t,c){if(e instanceof IDBTransaction){if("done"===t)return se.get(e);if("objectStoreNames"===t)return e.objectStoreNames||ce.get(e);if("store"===t)return c.objectStoreNames[1]?void 0:c.objectStore(c.objectStoreNames[0])}return wrap(e[t])},set:(e,t,c)=>(e[t]=c,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return ae||(ae=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(oe.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...c){const g=e.call(unwrap(this),t,...c);return ce.set(g,t.sort?t.sort():[t]),wrap(g)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(se.has(e))return;const t=new Promise(((t,c)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{c(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));se.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return ie||(ie=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,de):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,c)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{c(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&oe.set(t,e)})).catch((()=>{})),le.set(t,e),t}(e);if(ue.has(e))return ue.get(e);const t=transformCachableValue(e);return t!==e&&(ue.set(e,t),le.set(t,e)),t}const unwrap=e=>le.get(e);const fe=["get","getKey","getAll","getAllKeys","count"],pe=["put","add","delete","clear"],ge=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(ge.get(t))return ge.get(t);const c=t.replace(/FromIndex$/,""),g=t!==c,w=pe.includes(c);if(!(c in(g?IDBIndex:IDBObjectStore).prototype)||!w&&!fe.includes(c))return;const method=async function(e,...t){const I=this.transaction(e,w?"readwrite":"readonly");let _=I.store;return g&&(_=_.index(t.shift())),(await Promise.all([_[c](...t),w&&I.done]))[0]};return ge.set(t,method),method}!function replaceTraps(e){de=e(de)}((e=>({...e,get:(t,c,g)=>getMethod(t,c)||e.get(t,c,g),has:(t,c)=>!!getMethod(t,c)||e.has(t,c)})));const me="@firebase/installations",he="0.6.23",ve=1e4,be=`w:${he}`,Te="FIS_v2",ye=36e5,Ee=new ErrorFactory("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 isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const c=(await t.json()).error;return Ee.create("request-failed",{requestName:e,serverCode:c.code,serverMessage:c.message,serverStatus:c.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const c=getHeaders(e);return c.append("Authorization",function getAuthorizationHeader(e){return`${Te} ${e}`}(t)),c}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const Se=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return Se.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const we=new Map;function fidChanged(e,t){const c=getKey(e);callFidChangeCallbacks(c,t),function broadcastFidChange(e,t){const c=function getBroadcastChannel(){!Ie&&"BroadcastChannel"in self&&(Ie=new BroadcastChannel("[Firebase] FID Change"),Ie.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return Ie}();c&&c.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===we.size&&Ie&&(Ie.close(),Ie=null)}()}(c,t)}function callFidChangeCallbacks(e,t){const c=we.get(e);if(c)for(const e of c)e(t)}let Ie=null;const _e="firebase-installations-store";let Ae=null;function getDbPromise(){return Ae||(Ae=function openDB(e,t,{blocked:c,upgrade:g,blocking:w,terminated:I}={}){const _=indexedDB.open(e,t),k=wrap(_);return g&&_.addEventListener("upgradeneeded",(e=>{g(wrap(_.result),e.oldVersion,e.newVersion,wrap(_.transaction),e)})),c&&_.addEventListener("blocked",(e=>c(e.oldVersion,e.newVersion,e))),k.then((e=>{I&&e.addEventListener("close",(()=>I())),w&&e.addEventListener("versionchange",(e=>w(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),k}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(_e)}})),Ae}async function set(e,t){const c=getKey(e),g=(await getDbPromise()).transaction(_e,"readwrite"),w=g.objectStore(_e),I=await w.get(c);return await w.put(t,c),await g.done,I&&I.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),c=(await getDbPromise()).transaction(_e,"readwrite");await c.objectStore(_e).delete(t),await c.done}async function update(e,t){const c=getKey(e),g=(await getDbPromise()).transaction(_e,"readwrite"),w=g.objectStore(_e),I=await w.get(c),_=t(I);return void 0===_?await w.delete(c):await w.put(_,c),await g.done,!_||I&&I.fid===_.fid||fidChanged(e,_.fid),_}async function getInstallationEntry(e){let t;const c=await update(e.appConfig,(c=>{const g=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(c),w=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(Ee.create("app-offline"))}}const c={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},g=async function registerInstallation(e,t){try{const c=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:c}){const g=getInstallationsEndpoint(e),w=getHeaders(e),I=t.getImmediate({optional:!0});if(I){const e=await I.getHeartbeatsHeader();e&&w.append("x-firebase-client",e)}const _={fid:c,authVersion:Te,appId:e.appId,sdkVersion:be},k={method:"POST",headers:w,body:JSON.stringify(_)},C=await retryIfServerError((()=>fetch(g,k)));if(C.ok){const e=await C.json();return{fid:e.fid||c,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",C)}(e,t);return set(e.appConfig,c)}catch(c){throw isServerError(c)&&409===c.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),c}}(e,c);return{installationEntry:c,registrationPromise:g}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,g);return t=w.registrationPromise,w.installationEntry}));return""===c.fid?{installationEntry:await t}:{installationEntry:c,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:c}=await getInstallationEntry(e);return c||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw Ee.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+ve<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},c){const g=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,c),w=getHeadersWithAuth(e,c),I=t.getImmediate({optional:!0});if(I){const e=await I.getHeartbeatsHeader();e&&w.append("x-firebase-client",e)}const _={installation:{sdkVersion:be,appId:e.appId}},k={method:"POST",headers:w,body:JSON.stringify(_)},C=await retryIfServerError((()=>fetch(g,k)));if(C.ok){return extractAuthTokenInfoFromResponse(await C.json())}throw await getErrorFromResponse("Generate Auth Token",C)}async function refreshAuthToken(e,t=!1){let c;const g=await update(e.appConfig,(g=>{if(!isEntryRegistered(g))throw Ee.create("not-registered");const w=g.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+ye}(e)}(w))return g;if(1===w.requestStatus)return c=async function waitUntilAuthTokenRequest(e,t){let c=await updateAuthTokenRequest(e.appConfig);for(;1===c.authToken.requestStatus;)await sleep(100),c=await updateAuthTokenRequest(e.appConfig);const g=c.authToken;return 0===g.requestStatus?refreshAuthToken(e,t):g}(e,t),g;{if(!navigator.onLine)throw Ee.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(g);return c=async function fetchAuthTokenFromServer(e,t){try{const c=await generateAuthTokenRequest(e,t),g={...t,authToken:c};return await set(e.appConfig,g),c}catch(c){if(!isServerError(c)||401!==c.customData.serverCode&&404!==c.customData.serverCode){const c={...t,authToken:{requestStatus:0}};await set(e.appConfig,c)}else await remove(e.appConfig);throw c}}(e,t),t}}));return c?await c:g.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw Ee.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+ve<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const c=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(c);return(await refreshAuthToken(c,t)).token}function getMissingValueError(e){return Ee.create("missing-app-config-values",{valueName:e})}const ke="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),c=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const c of t)if(!e.options[c])throw getMissingValueError(c);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:c,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),c=_getProvider(t,ke).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:c,registrationPromise:g}=await getInstallationEntry(t);return g?g.catch(console.error):refreshAuthToken(t).catch(console.error),c.fid}(c),getToken:e=>getToken(c,e)}};!function registerInstallations(){t(new Component(ke,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(me,he),e(me,he,"esm2020");const Ce="@firebase/performance",Me="0.7.13",Re=Me,Pe="FB-PERF-TRACE-MEASURE",Le="_wt_",Ne="_fcp",Oe="_fid",De="_lcp",Fe="_inp",Be="_cls",qe="@firebase/performance/config",xe="@firebase/performance/configexpire",Ue="Performance",je=new ErrorFactory("performance",Ue,{"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."}),$e=new class Logger{constructor(e){this.name=e,this._logLevel=I,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in g))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?w[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,g.DEBUG,...e),this._logHandler(this,g.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,g.VERBOSE,...e),this._logHandler(this,g.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,g.INFO,...e),this._logHandler(this,g.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,g.WARN,...e),this._logHandler(this,g.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,g.ERROR,...e),this._logHandler(this,g.ERROR,...e)}}(Ue);let He,Ve,ze,We;$e.logLevel=g.INFO;class Api{constructor(e){if(this.window=e,!e)throw je.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay),this.onLCP=ot,this.onINP=rt,this.onCLS=D}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,c){this.performance&&this.performance.measure&&this.performance.measure(e,t,c)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}()?!!function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()||($e.info("IndexedDB is not supported by current browser"),!1):($e.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,t){if(!this.PerformanceObserver)return;new this.PerformanceObserver((e=>{for(const c of e.getEntries())t(c)})).observe({entryTypes:[e]})}static getInstance(){return void 0===He&&(He=new Api(Ve)),He}}function getIid(){return ze}function mergeStrings(e,t){const c=e.length-t.length;if(c<0||c>1)throw je.create("invalid String merger input");const g=[];for(let c=0;c<e.length;c++)g.push(e.charAt(c)),t.length>c&&g.push(t.charAt(c));return g.join("")}class SettingsService{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=mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=mergeStrings("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12,this.logMaxFlushSize=40}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===We&&(We=new SettingsService),We}}var Ke;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VISIBLE=1]="VISIBLE",e[e.HIDDEN=2]="HIDDEN"}(Ke||(Ke={}));const Ge=["firebase_","google_","ga_"],Je=new RegExp("^[a-zA-Z]\\w*$");function getServiceWorkerStatus(){const e=Api.getInstance().navigator;return e?.serviceWorker?e.serviceWorker.controller?2:3:1}function getVisibilityState(){switch(Api.getInstance().document.visibilityState){case"visible":return Ke.VISIBLE;case"hidden":return Ke.HIDDEN;default:return Ke.UNKNOWN}}function getEffectiveConnectionType(){const e=Api.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}function getAppId(e){const t=e.options?.appId;if(!t)throw je.create("no app id");return t}const Qe="0.0.1",Ze={loggingEnabled:!0},Xe="FIREBASE_INSTALLATIONS_AUTH";function getConfig(e,t){const c=function getStoredConfig(){const e=Api.getInstance().localStorage;if(!e)return;const t=e.getItem(xe);if(!t||!function configValid(e){return Number(e)>Date.now()}(t))return;const c=e.getItem(qe);if(!c)return;try{return JSON.parse(c)}catch{return}}();return c?(processConfig(c),Promise.resolve()):function getRemoteConfig(e,t){return function getAuthTokenPromise(e){const t=e.getToken();return t.then((e=>{})),t}(e.installations).then((c=>{const g=function getProjectId(e){const t=e.options?.projectId;if(!t)throw je.create("no project id");return t}(e.app),w=function getApiKey(e){const t=e.options?.apiKey;if(!t)throw je.create("no api key");return t}(e.app),I=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${g}/namespaces/fireperf:fetch?key=${w}`,{method:"POST",headers:{Authorization:`${Xe} ${c}`},body:JSON.stringify({app_instance_id:t,app_instance_id_token:c,app_id:getAppId(e.app),app_version:Re,sdk_version:Qe})});return fetch(I).then((e=>{if(e.ok)return e.json();throw je.create("RC response not ok")}))})).catch((()=>{$e.info(Ye)}))}(e,t).then(processConfig).then((e=>function storeConfig(e){const t=Api.getInstance().localStorage;if(!e||!t)return;t.setItem(qe,JSON.stringify(e)),t.setItem(xe,String(Date.now()+60*SettingsService.getInstance().configTimeToLive*60*1e3))}(e)),(()=>{}))}const Ye="Could not fetch config, will use default configs";function processConfig(e){if(!e)return e;const t=SettingsService.getInstance(),c=e.entries||{};return void 0!==c.fpr_enabled?t.loggingEnabled="true"===String(c.fpr_enabled):t.loggingEnabled=Ze.loggingEnabled,c.fpr_log_source?t.logSource=Number(c.fpr_log_source):Ze.logSource&&(t.logSource=Ze.logSource),c.fpr_log_endpoint_url?t.logEndPointUrl=c.fpr_log_endpoint_url:Ze.logEndPointUrl&&(t.logEndPointUrl=Ze.logEndPointUrl),c.fpr_log_transport_key?t.transportKey=c.fpr_log_transport_key:Ze.transportKey&&(t.transportKey=Ze.transportKey),void 0!==c.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(c.fpr_vc_network_request_sampling_rate):void 0!==Ze.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=Ze.networkRequestsSamplingRate),void 0!==c.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(c.fpr_vc_trace_sampling_rate):void 0!==Ze.tracesSamplingRate&&(t.tracesSamplingRate=Ze.tracesSamplingRate),c.fpr_log_max_flush_size?t.logMaxFlushSize=Number(c.fpr_log_max_flush_size):Ze.logMaxFlushSize&&(t.logMaxFlushSize=Ze.logMaxFlushSize),t.logTraceAfterSampling=shouldLogAfterSampling(t.tracesSamplingRate),t.logNetworkAfterSampling=shouldLogAfterSampling(t.networkRequestsSamplingRate),e}function shouldLogAfterSampling(e){return Math.random()<=e}let et,tt=1;function getInitializationPromise(e){return tt=2,et=et||function initializePerf(e){return function getDocumentReadyComplete(){const e=Api.getInstance().document;return new Promise((t=>{if(e&&"complete"!==e.readyState){const handler=()=>{"complete"===e.readyState&&(e.removeEventListener("readystatechange",handler),t())};e.addEventListener("readystatechange",handler)}else t()}))}().then((()=>function getIidPromise(e){const t=e.getId();return t.then((e=>{ze=e})),t}(e.installations))).then((t=>getConfig(e,t))).then((()=>changeInitializationStatus()),(()=>changeInitializationStatus()))}(e),et}function changeInitializationStatus(){tt=3}const it=1e4,at=new TextEncoder;let st,ct=3,ut=[],lt=!1;function processQueue(e){setTimeout((()=>{ct<=0||(ut.length>0&&function dispatchQueueEvents(){const e=ut.splice(0,1e3);(function postToFlEndpoint(e){const t=SettingsService.getInstance().getFlTransportFullUrl();return at.encode(e).length<=65536&&navigator.sendBeacon&&navigator.sendBeacon(t,e)?Promise.resolve():fetch(t,{method:"POST",body:e})})(buildPayload(e)).then((()=>{ct=3})).catch((()=>{ut=[...e,...ut],ct--,$e.info(`Tries left: ${ct}.`),processQueue(it)}))}(),processQueue(it))}),e)}function buildPayload(e){const t=e.map((e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)}))),c={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:SettingsService.getInstance().logSource,log_event:t};return JSON.stringify(c)}function transportHandler(e){return(...t)=>{!function addToQueue(e){if(!e.eventTime||!e.message)throw je.create("invalid cc log");ut=[...ut,e]}({message:e(...t),eventTime:Date.now()})}}function flushQueuedEvents(){const e=SettingsService.getInstance().getFlTransportFullUrl();for(;ut.length>0;){const t=ut.splice(-SettingsService.getInstance().logMaxFlushSize),c=buildPayload(t);if(!navigator.sendBeacon||!navigator.sendBeacon(e,c)){ut=[...ut,...t];break}}if(ut.length>0){const t=buildPayload(ut);fetch(e,{method:"POST",body:t}).catch((()=>{$e.info("Failed flushing queued events.")}))}}function sendLog(e,t){st||(st={send:transportHandler(serializer),flush:flushQueuedEvents}),st.send(e,t)}function logTrace(e){const t=SettingsService.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&Api.getInstance().requiredApisAvailable()&&(!function isPerfInitialized(){return 3===tt}()?getInitializationPromise(e.performanceController).then((()=>sendTraceLog(e)),(()=>sendTraceLog(e))):sendTraceLog(e))}function sendTraceLog(e){if(!getIid())return;const t=SettingsService.getInstance();t.loggingEnabled&&t.logTraceAfterSampling&&sendLog(e,1)}function serializer(e,t){return 0===t?function serializeNetworkRequest(e){const t={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},c={application_info:getApplicationInfo(e.performanceController.app),network_request_metric:t};return JSON.stringify(c)}(e):function serializeTrace(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);const c=e.getAttributes();0!==Object.keys(c).length&&(t.custom_attributes=c);const g={application_info:getApplicationInfo(e.performanceController.app),trace_metric:t};return JSON.stringify(g)}(e)}function getApplicationInfo(e){return{google_app_id:getAppId(e),app_instance_id:getIid(),web_app_info:{sdk_version:Re,page_url:Api.getInstance().getUrl(),service_worker_status:getServiceWorkerStatus(),visibility_state:getVisibilityState(),effective_connection_type:getEffectiveConnectionType()},application_process_state:0}}function createNetworkRequestEntry(e,t){const c=t;if(!c||void 0===c.responseStart)return;const g=Api.getInstance().getTimeOrigin(),w=Math.floor(1e3*(c.startTime+g)),I=c.responseStart?Math.floor(1e3*(c.responseStart-c.startTime)):void 0,_=Math.floor(1e3*(c.responseEnd-c.startTime));!function logNetworkRequest(e){const t=SettingsService.getInstance();if(!t.instrumentationEnabled)return;const c=e.url,g=t.logEndPointUrl.split("?")[0],w=t.flTransportEndpointUrl.split("?")[0];c!==g&&c!==w&&t.loggingEnabled&&t.logNetworkAfterSampling&&sendLog(e,0)}({performanceController:e,url:c.name&&c.name.split("?")[0],responsePayloadBytes:c.transferSize,startTimeUs:w,timeToResponseInitiatedUs:I,timeToResponseCompletedUs:_})}const dt=["_fp",Ne,Oe,De,Be,Fe];class Trace{constructor(e,t,c=!1,g){this.performanceController=e,this.name=t,this.isAuto=c,this.state=1,this.customAttributes={},this.counters={},this.api=Api.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=g||`${Pe}-${this.randomId}-${this.name}`,g&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw je.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw je.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(),logTrace(this)}record(e,t,c){if(e<=0)throw je.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw je.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),c&&c.attributes&&(this.customAttributes={...c.attributes}),c&&c.metrics)for(const e of Object.keys(c.metrics))isNaN(Number(c.metrics[e]))||(this.counters[e]=Math.floor(Number(c.metrics[e])));logTrace(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(!function isValidMetricName(e,t){return!(0===e.length||e.length>100)&&(t&&t.startsWith(Le)&&dt.indexOf(e)>-1||!e.startsWith("_"))}(e,this.name))throw je.create("invalid custom metric name",{customMetricName:e});this.counters[e]=function convertMetricValueToInteger(e){const t=Math.floor(e);return t<e&&$e.info(`Metric value should be an Integer, setting the value as : ${t}.`),t}(t??0)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){const c=function isValidCustomAttributeName(e){return!(0===e.length||e.length>40)&&(!Ge.some((t=>e.startsWith(t)))&&!!e.match(Je))}(e),g=function isValidCustomAttributeValue(e){return 0!==e.length&&e.length<=100}(t);if(c&&g)this.customAttributes[e]=t;else{if(!c)throw je.create("invalid attribute name",{attributeName:e});if(!g)throw je.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return{...this.customAttributes}}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){const e=this.api.getEntriesByName(this.traceMeasure),t=e&&e[0];t&&(this.durationUs=Math.floor(1e3*t.duration),this.startTimeUs=Math.floor(1e3*(t.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,c,g,w){const I=Api.getInstance().getUrl();if(!I)return;const _=new Trace(e,Le+I,!0),k=Math.floor(1e3*Api.getInstance().getTimeOrigin());_.setStartTime(k),t&&t[0]&&(_.setDuration(Math.floor(1e3*t[0].duration)),_.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),_.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),_.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));if(c){const e=c.find((e=>"first-paint"===e.name));e&&e.startTime&&_.putMetric("_fp",Math.floor(1e3*e.startTime));const t=c.find((e=>"first-contentful-paint"===e.name));t&&t.startTime&&_.putMetric(Ne,Math.floor(1e3*t.startTime)),w&&_.putMetric(Oe,Math.floor(1e3*w))}this.addWebVitalMetric(_,De,"lcp_element",g.lcp),this.addWebVitalMetric(_,Be,"cls_largestShiftTarget",g.cls),this.addWebVitalMetric(_,Fe,"inp_interactionTarget",g.inp),logTrace(_),function flushLogs(){st&&st.flush()}()}static addWebVitalMetric(e,t,c,g){g&&(e.putMetric(t,Math.floor(1e3*g.value)),g.elementAttribution&&(g.elementAttribution.length>100?e.putAttribute(c,g.elementAttribution.substring(0,100)):e.putAttribute(c,g.elementAttribution)))}static createUserTimingTrace(e,t){logTrace(new Trace(e,t,!1,t))}}let ft,pt={},gt=!1;function setupOobResources(e){getIid()&&(setTimeout((()=>function setupOobTraces(e){const t=Api.getInstance();"onpagehide"in window?t.document.addEventListener("pagehide",(()=>sendOobTrace(e))):t.document.addEventListener("unload",(()=>sendOobTrace(e)));t.document.addEventListener("visibilitychange",(()=>{"hidden"===t.document.visibilityState&&sendOobTrace(e)})),t.onFirstInputDelay&&t.onFirstInputDelay((e=>{ft=e}));t.onLCP((e=>{pt.lcp={value:e.value,elementAttribution:e.attribution?.element}})),t.onCLS((e=>{pt.cls={value:e.value,elementAttribution:e.attribution?.largestShiftTarget}})),t.onINP((e=>{pt.inp={value:e.value,elementAttribution:e.attribution?.interactionTarget}}))}(e)),0),setTimeout((()=>function setupNetworkRequests(e){const t=Api.getInstance(),c=t.getEntriesByType("resource");for(const t of c)createNetworkRequestEntry(e,t);t.setupObserver("resource",(t=>createNetworkRequestEntry(e,t)))}(e)),0),setTimeout((()=>function setupUserTimingTraces(e){const t=Api.getInstance(),c=t.getEntriesByType("measure");for(const t of c)createUserTimingTrace(e,t);t.setupObserver("measure",(t=>createUserTimingTrace(e,t)))}(e)),0))}function createUserTimingTrace(e,t){const c=t.name;c.substring(0,21)!==Pe&&Trace.createUserTimingTrace(e,c)}function sendOobTrace(e){if(!gt){gt=!0;const t=Api.getInstance(),c=t.getEntriesByType("navigation"),g=t.getEntriesByType("paint");setTimeout((()=>{Trace.createOobTrace(e,c,g,pt,ft)}),0)}}class PerformanceController{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==e?.dataCollectionEnabled&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==e?.instrumentationEnabled&&(this.instrumentationEnabled=e.instrumentationEnabled),Api.getInstance().requiredApisAvailable()?function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let c=!0;const g="validate-browser-context-for-indexeddb-analytics-module",w=self.indexedDB.open(g);w.onsuccess=()=>{w.result.close(),c||self.indexedDB.deleteDatabase(g),e(!0)},w.onupgradeneeded=()=>{c=!1},w.onerror=()=>{t(w.error?.message||"")}}catch(e){t(e)}}))}().then((e=>{e&&(!function setupTransportService(){lt||(processQueue(5500),lt=!0)}(),getInitializationPromise(this).then((()=>setupOobResources(this)),(()=>setupOobResources(this))),this.initialized=!0)})).catch((e=>{$e.info(`Environment doesn't support IndexedDB: ${e}`)})):$e.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){SettingsService.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return SettingsService.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){SettingsService.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return SettingsService.getInstance().dataCollectionEnabled}}function getPerformance(e=c()){e=getModularInstance(e);return _getProvider(e,"performance").getImmediate()}function initializePerformance(e,t){e=getModularInstance(e);const c=_getProvider(e,"performance");if(c.isInitialized()){const e=c.getImmediate();if(deepEqual(c.getOptions(),t??{}))return e;throw je.create("already initialized")}return c.initialize({options:t})}function trace(e,t){return e=getModularInstance(e),new Trace(e,t)}const factory=(e,{options:t})=>{const c=e.getProvider("app").getImmediate(),g=e.getProvider("installations-internal").getImmediate();if("[DEFAULT]"!==c.name)throw je.create("FB not default");if("undefined"==typeof window)throw je.create("no window");!function setupApi(e){Ve=e}(window);const w=new PerformanceController(c,g);return w._init(t),w};!function registerPerformance(){t(new Component("performance",factory,"PUBLIC")),e(Ce,Me),e(Ce,Me,"esm2020")}();export{getPerformance,initializePerformance,trace};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-performance.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{registerVersion as e,_registerComponent as t,_getProvider,SDK_VERSION as i,getApp as s}from"https://www.gstatic.com/firebasejs/12.17.0/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],a=n?function replaceTemplate(e,t){try{let i=0,s="";for(;i<e.length;){const n=e.indexOf("{$",i);if(-1===n){s+=e.substring(i);break}const a=e.indexOf("}",n+2);if(-1===a){s+=e.substring(i);break}const r=e.substring(n+2,a),o=t[r];s+=e.substring(i,n)+(null!=o?String(o):`<${r}?>`),i=a+1}return s}catch(t){return e}}(n,i):"Error",r=`${this.serviceName}: ${a} (${s}).`;return new FirebaseError(s,r,i)}}function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const r={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},o=a.INFO,c={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=c[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=o,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?r[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}let l,u;const g=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap;let m={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||d.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return u||(u=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(g.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return d.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(h.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));h.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return l||(l=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,m):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&g.set(t,e)})).catch((()=>{})),p.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),p.set(t,e)),t}const unwrap=e=>p.get(e);const w=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],y=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(y.get(t))return y.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=v.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!w.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return y.set(t,method),method}!function replaceTraps(e){m=e(m)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const b="@firebase/installations",E="0.6.23",C=1e4,I=`w:${E}`,S="FIS_v2",T=36e5,R=new ErrorFactory("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 isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return R.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${S} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const _=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return _.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const k=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!M&&"BroadcastChannel"in self&&(M=new BroadcastChannel("[Firebase] FID Change"),M.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return M}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===k.size&&M&&(M.close(),M=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=k.get(e);if(i)for(const e of i)e(t)}let M=null;const F="firebase-installations-store";let A=null;function getDbPromise(){return A||(A=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(F)}})),A}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(F,"readwrite"),n=s.objectStore(F),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(F,"readwrite");await i.objectStore(F).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(F,"readwrite"),n=s.objectStore(F),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(R.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:S,appId:e.appId,sdkVersion:I},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw R.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+C<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:I,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw R.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+T}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw R.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw R.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+C<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return R.create("missing-app-config-values",{valueName:e})}const L="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,L).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(L,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(b,E),e(b,E,"esm2020");const x="@firebase/remote-config",D="0.9.1";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",B=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});const O=["1","true","t","yes","y","on"];class Value{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&O.indexOf(this._value.toLowerCase())>=0}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw B.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=s(),t={}){e=getModularInstance(e);const i=_getProvider(e,P);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw B.create("already-initialized")}i.initialize({options:t});const n=i.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t).updateActiveExperiments(i.experiments||[]);return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),n]),!0}function ensureInitialized(e){const t=getModularInstance(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then((()=>{t._isInitializationComplete=!0}))),t._initializePromise}async function fetchConfig(e){const t=getModularInstance(e),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys({...e,...t})}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,i)=>(t[i]=getValue(e,i),t)),{})}function getBoolean(e,t){return getValue(getModularInstance(e),t).asBoolean()}function getNumber(e,t){return getValue(getModularInstance(e),t).asNumber()}function getString(e,t){return getValue(getModularInstance(e),t).asString()}function getValue(e,t){const i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._logger.debug(`Returning static value for key "${t}". Define a default or remote value if this is unintentional.`),new Value("static"))}function setLogLevel(e,t){const i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=a.DEBUG;break;case"silent":i._logger.logLevel=a.SILENT;break;default:i._logger.logLevel=a.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},a={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),B.create(t,{originalErrorMessage:e?.message})}let u=l.status;const g=l.headers.get("ETag")||void 0;let h,d,f,p,m;if(200===l.status){let e;try{e=await l.json()}catch(e){throw B.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion,p=e.experimentDescriptions,m=e.rolloutMetadata}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[],m=[]),304!==u&&200!==u)throw B.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h,templateVersion:f,experiments:p,rollouts:m}}}class RetryingClient{constructor(e,t){this.client=e,this.storage=t}async fetch(e){const t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(e,{throttleEndTimeMillis:t,backoffCount:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(B.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(e.signal,t);try{const t=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),t}catch(t){if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t))throw t;const s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return B.create(t,{originalErrorMessage:i&&i?.message})}const N="app_namespace_store";class Storage{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(N,{keyPath:"compositeKey"})}}catch(e){t(B.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([N],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(N),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(B.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(N),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(B.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([N],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([N],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([N],"readwrite").objectStore(N),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(B.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw B.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const H="X-Goog-Api-Key",V="X-Goog-Firebase-Installations-Auth",$="featureDisabled",j="retryIntervalSeconds",q="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[H]:this.apiKey,[V]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:s})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t,i,s){const n=new Set,a=new Set(Object.keys(e||{})),r=new Set(Object.keys(t||{})),o=i.experiments||[],c=s?.experiments||[],l=this.createExperimentsMap(o),u=this.createExperimentsMap(c),g=i.rollouts||[],h=s?.rollouts||[],d=this.createRolloutsMap(g),f=this.createRolloutsMap(h);for(const i of a){if(!r.has(i)||e[i]!==t[i]){n.add(i);continue}if(l.has(i)!==u.has(i)){n.add(i);continue}const s=l.get(i),a=u.get(i);if(s&&a&&!this.areExperimentsEqual(s,a)){n.add(i);continue}if(d.has(i)!==f.has(i)){n.add(i);continue}const o=d.get(i),c=f.get(i);o&&c&&!this.areRolloutsEqual(o,c)&&n.add(i)}for(const e of r)a.has(e)||n.add(e);return n}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}areRolloutsEqual(e,t){if(e.size!==t.size)return!1;for(const[i,s]of e)if(t.get(i)!==s)return!1;return!0}createExperimentsMap(e){const t=new Map;for(const i of e)if(i.affectedParameterKeys&&!i.experimentId.startsWith("_exp_rollout"))for(const e of i.affectedParameterKeys)t.set(e,i);return t}createRolloutsMap(e){const t=new Map;for(const i of e){const e=i.rolloutId,s=i.variantId,n=i.affectedParameterKeys||[];for(const i of n){let n=t.get(i);n||(n=new Map,t.set(i,n)),n.set(e,s)}}return t}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.storage.getLastSuccessfulFetchResponse(),o=await this.cachingClient.fetch(e);let c=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(o,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==o.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==c&&(c={});const l=this.getChangedParams(o.config,c,o,r);if(0===l.size)return void this.logger.debug("Config was fetched, but no params changed.");const u={getUpdatedKeys:()=>new Set(l)};this.executeAllListenerCallbacks(u)}catch(e){const t=e instanceof Error?e.message:String(e),i=B.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}async autoFetch(e,t){if(0===e){const e=B.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if($ in e&&!0===e[$]){const e=B.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(q in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[q]);t&&i>t&&await this.autoFetch(3,i)}if(j in e){const t=Number(e[j]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(B.create("update-message-invalid",{originalErrorMessage:t}))}i=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===s||this.isStatusCodeRetryable(s));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=B.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=B.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(P,(function remoteConfigFactory(e,{options:t}){const s=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),r=e.getProvider("analytics-internal"),{projectId:o,apiKey:c,appId:l}=s.options;if(!o)throw B.create("registration-project-id");if(!c)throw B.create("registration-api-key");if(!l)throw B.create("registration-app-id");const u=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(l,s.name,u):new InMemoryStorage,h=new StorageCache(g),d=new Logger(x);d.logLevel=a.ERROR;const f=new RestClient(n,i,u,o,c,l),p=new RetryingClient(f,g),m=new CachingClient(p,g,h,d),w=new RealtimeHandler(n,g,i,u,o,c,l,d,h,m),v=new RemoteConfig(s,m,h,g,d,w,r);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(x,D),e(x,D,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
|
|
1
|
+
import{registerVersion as e,_registerComponent as t,_getProvider,SDK_VERSION as i,getApp as s}from"https://www.gstatic.com/firebasejs/12.17.1/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],a=n?function replaceTemplate(e,t){try{let i=0,s="";for(;i<e.length;){const n=e.indexOf("{$",i);if(-1===n){s+=e.substring(i);break}const a=e.indexOf("}",n+2);if(-1===a){s+=e.substring(i);break}const r=e.substring(n+2,a),o=t[r];s+=e.substring(i,n)+(null!=o?String(o):`<${r}?>`),i=a+1}return s}catch(t){return e}}(n,i):"Error",r=`${this.serviceName}: ${a} (${s}).`;return new FirebaseError(s,r,i)}}function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const r={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},o=a.INFO,c={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=c[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=o,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?r[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}let l,u;const g=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap;let m={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||d.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return u||(u=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(g.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return d.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(h.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));h.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return l||(l=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,m):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&g.set(t,e)})).catch((()=>{})),p.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),p.set(t,e)),t}const unwrap=e=>p.get(e);const w=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],y=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(y.get(t))return y.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=v.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!w.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return y.set(t,method),method}!function replaceTraps(e){m=e(m)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const b="@firebase/installations",E="0.6.23",C=1e4,I=`w:${E}`,S="FIS_v2",T=36e5,R=new ErrorFactory("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 isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return R.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${S} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const _=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return _.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const k=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!M&&"BroadcastChannel"in self&&(M=new BroadcastChannel("[Firebase] FID Change"),M.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return M}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===k.size&&M&&(M.close(),M=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=k.get(e);if(i)for(const e of i)e(t)}let M=null;const F="firebase-installations-store";let A=null;function getDbPromise(){return A||(A=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(F)}})),A}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(F,"readwrite"),n=s.objectStore(F),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(F,"readwrite");await i.objectStore(F).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(F,"readwrite"),n=s.objectStore(F),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(R.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:S,appId:e.appId,sdkVersion:I},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw R.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+C<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:I,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw R.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+T}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw R.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw R.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+C<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return R.create("missing-app-config-values",{valueName:e})}const L="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,L).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(L,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(b,E),e(b,E,"esm2020");const x="@firebase/remote-config",D="0.9.1";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",B=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});const O=["1","true","t","yes","y","on"];class Value{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&O.indexOf(this._value.toLowerCase())>=0}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw B.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=s(),t={}){e=getModularInstance(e);const i=_getProvider(e,P);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw B.create("already-initialized")}i.initialize({options:t});const n=i.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t).updateActiveExperiments(i.experiments||[]);return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),n]),!0}function ensureInitialized(e){const t=getModularInstance(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then((()=>{t._isInitializationComplete=!0}))),t._initializePromise}async function fetchConfig(e){const t=getModularInstance(e),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys({...e,...t})}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,i)=>(t[i]=getValue(e,i),t)),{})}function getBoolean(e,t){return getValue(getModularInstance(e),t).asBoolean()}function getNumber(e,t){return getValue(getModularInstance(e),t).asNumber()}function getString(e,t){return getValue(getModularInstance(e),t).asString()}function getValue(e,t){const i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._logger.debug(`Returning static value for key "${t}". Define a default or remote value if this is unintentional.`),new Value("static"))}function setLogLevel(e,t){const i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=a.DEBUG;break;case"silent":i._logger.logLevel=a.SILENT;break;default:i._logger.logLevel=a.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},a={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),B.create(t,{originalErrorMessage:e?.message})}let u=l.status;const g=l.headers.get("ETag")||void 0;let h,d,f,p,m;if(200===l.status){let e;try{e=await l.json()}catch(e){throw B.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion,p=e.experimentDescriptions,m=e.rolloutMetadata}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[],m=[]),304!==u&&200!==u)throw B.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h,templateVersion:f,experiments:p,rollouts:m}}}class RetryingClient{constructor(e,t){this.client=e,this.storage=t}async fetch(e){const t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(e,{throttleEndTimeMillis:t,backoffCount:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(B.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(e.signal,t);try{const t=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),t}catch(t){if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t))throw t;const s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return B.create(t,{originalErrorMessage:i&&i?.message})}const N="app_namespace_store";class Storage{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(N,{keyPath:"compositeKey"})}}catch(e){t(B.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([N],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(N),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(B.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(N),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(B.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([N],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([N],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([N],"readwrite").objectStore(N),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(B.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw B.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const H="X-Goog-Api-Key",V="X-Goog-Firebase-Installations-Auth",$="featureDisabled",j="retryIntervalSeconds",q="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[H]:this.apiKey,[V]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:s})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t,i,s){const n=new Set,a=new Set(Object.keys(e||{})),r=new Set(Object.keys(t||{})),o=i.experiments||[],c=s?.experiments||[],l=this.createExperimentsMap(o),u=this.createExperimentsMap(c),g=i.rollouts||[],h=s?.rollouts||[],d=this.createRolloutsMap(g),f=this.createRolloutsMap(h);for(const i of a){if(!r.has(i)||e[i]!==t[i]){n.add(i);continue}if(l.has(i)!==u.has(i)){n.add(i);continue}const s=l.get(i),a=u.get(i);if(s&&a&&!this.areExperimentsEqual(s,a)){n.add(i);continue}if(d.has(i)!==f.has(i)){n.add(i);continue}const o=d.get(i),c=f.get(i);o&&c&&!this.areRolloutsEqual(o,c)&&n.add(i)}for(const e of r)a.has(e)||n.add(e);return n}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}areRolloutsEqual(e,t){if(e.size!==t.size)return!1;for(const[i,s]of e)if(t.get(i)!==s)return!1;return!0}createExperimentsMap(e){const t=new Map;for(const i of e)if(i.affectedParameterKeys&&!i.experimentId.startsWith("_exp_rollout"))for(const e of i.affectedParameterKeys)t.set(e,i);return t}createRolloutsMap(e){const t=new Map;for(const i of e){const e=i.rolloutId,s=i.variantId,n=i.affectedParameterKeys||[];for(const i of n){let n=t.get(i);n||(n=new Map,t.set(i,n)),n.set(e,s)}}return t}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.storage.getLastSuccessfulFetchResponse(),o=await this.cachingClient.fetch(e);let c=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(o,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==o.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==c&&(c={});const l=this.getChangedParams(o.config,c,o,r);if(0===l.size)return void this.logger.debug("Config was fetched, but no params changed.");const u={getUpdatedKeys:()=>new Set(l)};this.executeAllListenerCallbacks(u)}catch(e){const t=e instanceof Error?e.message:String(e),i=B.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}async autoFetch(e,t){if(0===e){const e=B.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if($ in e&&!0===e[$]){const e=B.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(q in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[q]);t&&i>t&&await this.autoFetch(3,i)}if(j in e){const t=Number(e[j]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(B.create("update-message-invalid",{originalErrorMessage:t}))}i=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===s||this.isStatusCodeRetryable(s));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=B.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=B.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(P,(function remoteConfigFactory(e,{options:t}){const s=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),r=e.getProvider("analytics-internal"),{projectId:o,apiKey:c,appId:l}=s.options;if(!o)throw B.create("registration-project-id");if(!c)throw B.create("registration-api-key");if(!l)throw B.create("registration-app-id");const u=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(l,s.name,u):new InMemoryStorage,h=new StorageCache(g),d=new Logger(x);d.logLevel=a.ERROR;const f=new RestClient(n,i,u,o,c,l),p=new RetryingClient(f,g),m=new CachingClient(p,g,h,d),w=new RealtimeHandler(n,g,i,u,o,c,l,d,h,m),v=new RemoteConfig(s,m,h,g,d,w,r);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(x,D),e(x,D,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-remote-config.js.map
|