firebase
Advanced tools
Comparing version 10.12.3 to 10.12.4-20240716220314
@@ -5,3 +5,3 @@ import { registerVersion } from '@firebase/app'; | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -8,0 +8,0 @@ /** |
@@ -8,3 +8,3 @@ 'use strict'; | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -11,0 +11,0 @@ /** |
@@ -5,3 +5,3 @@ import firebase from '@firebase/app-compat'; | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -8,0 +8,0 @@ /** |
@@ -10,3 +10,3 @@ 'use strict'; | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -13,0 +13,0 @@ /** |
@@ -15,3 +15,3 @@ import firebase from '@firebase/app-compat'; | ||
var name$1 = "firebase"; | ||
var version$1 = "10.12.3"; | ||
var version$1 = "10.12.4-20240716220314"; | ||
@@ -37,3 +37,3 @@ /** | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -40,0 +40,0 @@ /** |
@@ -13,3 +13,3 @@ 'use strict'; | ||
var name$1 = "firebase"; | ||
var version$1 = "10.12.3"; | ||
var version$1 = "10.12.4-20240716220314"; | ||
@@ -35,3 +35,3 @@ /** | ||
var name = "firebase"; | ||
var version = "10.12.3"; | ||
var version = "10.12.4-20240716220314"; | ||
@@ -38,0 +38,0 @@ /** |
@@ -1,2 +0,16 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(ht,mt){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t,a,n=e(ht);(dt=t=t||{})[dt.DEBUG=0]="DEBUG",dt[dt.VERBOSE=1]="VERBOSE",dt[dt.INFO=2]="INFO",dt[dt.WARN=3]="WARN",dt[dt.ERROR=4]="ERROR",dt[dt.SILENT=5]="SILENT";const r={debug:t.DEBUG,verbose:t.VERBOSE,info:t.INFO,warn:t.WARN,error:t.ERROR,silent:t.SILENT},i=t.INFO,o={[t.DEBUG]:"log",[t.VERBOSE]:"log",[t.INFO]:"info",[t.WARN]:"warn",[t.ERROR]:"error"},s=(e,t,...n)=>{if(!(t<e.logLevel)){var a=(new Date).toISOString(),r=o[t];if(!r)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[r](`[${a}] ${e.name}:`,...n)}};function c(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function p(){try{return"object"==typeof indexedDB}catch(e){return}}function f(){return new Promise((t,n)=>{try{let e=!0;const a="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(a);r.onsuccess=()=>{r.result.close(),e||self.indexedDB.deleteDatabase(a),t(!0)},r.onupgradeneeded=()=>{e=!1},r.onerror=()=>{var e;n((null===(e=r.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function l(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class u extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,u.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,d.prototype.create)}}class d{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var a,n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],i=i?(a=n,i.replace(g,(e,t)=>{var n=a[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${r}).`;return new u(r,i,n)}}const g=/\{\$([^}]+)}/g,h=1e3,m=2,v=144e5,w=.5;function y(e,t=h,n=m){var a=t*Math.pow(n,e),r=Math.round(w*a*(Math.random()-.5)*2);return Math.min(v,a+r)}function I(e){return e&&e._delegate?e._delegate:e}class b{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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}}const E=(t,e)=>e.some(e=>t instanceof e);let _,T;const S=new WeakMap,C=new WeakMap,D=new WeakMap,L=new WeakMap,O=new WeakMap;let P={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return C.get(e);if("objectStoreNames"===t)return e.objectStoreNames||D.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return k(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function N(a){return a!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(T=T||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(a)?function(...e){return a.apply(R(this),e),k(S.get(this))}:function(...e){return k(a.apply(R(this),e))}:function(e,...t){var n=a.call(R(this),e,...t);return D.set(n,e.sort?e.sort():[e]),k(n)}}function A(e){return"function"==typeof e?N(e):(e instanceof IDBTransaction&&(i=e,C.has(i)||(t=new Promise((e,t)=>{const n=()=>{i.removeEventListener("complete",a),i.removeEventListener("error",r),i.removeEventListener("abort",r)},a=()=>{e(),n()},r=()=>{t(i.error||new DOMException("AbortError","AbortError")),n()};i.addEventListener("complete",a),i.addEventListener("error",r),i.addEventListener("abort",r)}),C.set(i,t))),E(e,_=_||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,P):e);var i,t}function k(e){if(e instanceof IDBRequest)return function(i){const e=new Promise((e,t)=>{const n=()=>{i.removeEventListener("success",a),i.removeEventListener("error",r)},a=()=>{e(k(i.result)),n()},r=()=>{t(i.error),n()};i.addEventListener("success",a),i.addEventListener("error",r)});return e.then(e=>{e instanceof IDBCursor&&S.set(e,i)}).catch(()=>{}),O.set(e,i),e}(e);if(L.has(e))return L.get(e);var t=A(e);return t!==e&&(L.set(e,t),O.set(t,e)),t}const R=e=>O.get(e);const j=["get","getKey","getAll","getAllKeys","count"],M=["put","add","delete","clear"],$=new Map;function B(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if($.get(t))return $.get(t);const r=t.replace(/FromIndex$/,""),i=t!==r,o=M.includes(r);if(r in(i?IDBIndex:IDBObjectStore).prototype&&(o||j.includes(r))){var n=async function(e,...t){var n=this.transaction(e,o?"readwrite":"readonly");let a=n.store;return i&&(a=a.index(t.shift())),(await Promise.all([a[r](...t),o&&n.done]))[0]};return $.set(t,n),n}}}P={...a=P,get:(e,t,n)=>B(e,t)||a.get(e,t,n),has:(e,t)=>!!B(e,t)||a.has(e,t)};var F="@firebase/installations",H="0.6.8";const x=1e4,V=`w:${H}`,q="FIS_v2",U="https://firebaseinstallations.googleapis.com/v1",W=36e5;const G=new d("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 K(e){return e instanceof u&&e.code.includes("request-failed")}function z({projectId:e}){return`${U}/projects/${e}/installations`}function J(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Y(e,t){var n=(await t.json()).error;return G.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function X({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Z(e,{refreshToken:t}){const n=X(e);return n.append("Authorization",(t=t,`${q} ${t}`)),n}async function Q(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function ee(t){return new Promise(e=>{setTimeout(e,t)})}const te=/^[cdef][\w-]{21}$/,ne="";function ae(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return te.test(e)?e:ne}catch(e){return ne}}function re(e){return`${e.appName}!${e.appId}`}const ie=new Map;function oe(e,t){var n=re(e);se(n,t),function(e,t){const n=function(){!ce&&"BroadcastChannel"in self&&(ce=new BroadcastChannel("[Firebase] FID Change"),ce.onmessage=e=>{se(e.data.key,e.data.fid)});return ce}();n&&n.postMessage({key:e,fid:t});0===ie.size&&ce&&(ce.close(),ce=null)}(n,t)}function se(e,t){var n=ie.get(e);if(n)for(const a of n)a(t)}let ce=null;const le="firebase-installations-store";let ue=null;function de(){return ue=ue||function(e,t,{blocked:n,upgrade:a,blocking:r,terminated:i}){const o=indexedDB.open(e,t),s=k(o);return a&&o.addEventListener("upgradeneeded",e=>{a(k(o.result),e.oldVersion,e.newVersion,k(o.transaction),e)}),n&&o.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(le)}}),ue}async function pe(e,t){var n=re(e);const a=await de(),r=a.transaction(le,"readwrite"),i=r.objectStore(le);var o=await i.get(n);return await i.put(t,n),await r.done,o&&o.fid===t.fid||oe(e,t.fid),t}async function fe(e){var t=re(e);const n=await de(),a=n.transaction(le,"readwrite");await a.objectStore(le).delete(t),await a.done}async function ge(e,t){var n=re(e);const a=await de(),r=a.transaction(le,"readwrite"),i=r.objectStore(le);var o=await i.get(n),s=t(o);return void 0===s?await i.delete(n):await i.put(s,n),await r.done,!s||o&&o.fid===s.fid||oe(e,s.fid),s}async function he(n){let a;var e=await ge(n.appConfig,e=>{var t=ve(e||{fid:ae(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await me(e.appConfig);for(;1===t.registrationStatus;)await ee(100),t=await me(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:a}=await he(e);return a||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(G.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var a={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const a=z(e),r=X(e),i=t.getImmediate({optional:!0});!i||(o=await i.getHeartbeatsHeader())&&r.append("x-firebase-client",o);var o={fid:n,authVersion:q,appId:e.appId,sdkVersion:V};const s={method:"POST",headers:r,body:JSON.stringify(o)},c=await Q(()=>fetch(a,s));if(c.ok){o=await c.json();return{fid:o.fid||n,registrationStatus:2,refreshToken:o.refreshToken,authToken:J(o.authToken)}}throw await Y("Create Installation",c)}(t,n);return pe(t.appConfig,e)}catch(e){throw K(e)&&409===e.customData.serverCode?await fe(t.appConfig):await pe(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,a);return{installationEntry:a,registrationPromise:n}}}(n,t);return a=t.registrationPromise,t.installationEntry});return e.fid===ne?{installationEntry:await a}:{installationEntry:e,registrationPromise:a}}function me(e){return ge(e,e=>{if(!e)throw G.create("installation-not-found");return ve(e)})}function ve(e){return 1===(t=e).registrationStatus&&t.registrationTime+x<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function we({appConfig:e,heartbeatServiceProvider:t},n){const a=([r,i]=[e,n["fid"]],`${z(r)}/${i}/authTokens:generate`);var r,i;const o=Z(e,n),s=t.getImmediate({optional:!0});!s||(c=await s.getHeartbeatsHeader())&&o.append("x-firebase-client",c);var c={installation:{sdkVersion:V,appId:e.appId}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await Q(()=>fetch(a,l));if(u.ok)return J(await u.json());throw await Y("Generate Auth Token",u)}async function ye(a,r=!1){let i;var e=await ge(a.appConfig,e=>{if(!be(e))throw G.create("not-registered");var t,n=e.authToken;if(r||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+W}(t)){if(1===n.requestStatus)return i=async function(e,t){let n=await Ie(e.appConfig);for(;1===n.authToken.requestStatus;)await ee(100),n=await Ie(e.appConfig);var a=n.authToken;return 0===a.requestStatus?ye(e,t):a}(a,r),e;if(!navigator.onLine)throw G.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return i=async function(t,n){try{var a=await we(t,n),e=Object.assign(Object.assign({},n),{authToken:a});return await pe(t.appConfig,e),a}catch(e){throw!K(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(a=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await pe(t.appConfig,a)):await fe(t.appConfig),e}}(a,n),n}return e});return i?await i:e.authToken}function Ie(e){return ge(e,e=>{if(!be(e))throw G.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+x<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function be(e){return void 0!==e&&2===e.registrationStatus}async function Ee(e,t=!1){var n,a=e;return await((n=(await he(a)).registrationPromise)&&await n),(await ye(a,t)).token}function _e(e){return G.create("missing-app-config-values",{valueName:e})}const Te="installations",Se=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw _e("App Configuration");if(!e.name)throw _e("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw _e(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:mt._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},Ce=e=>{var t=e.getProvider("app").getImmediate();const n=mt._getProvider(t,Te).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:a}=await he(t);return(a||ye(t)).catch(console.error),n.fid}(n),getToken:e=>Ee(n,e)}};mt._registerComponent(new b(Te,Se,"PUBLIC")),mt._registerComponent(new b("installations-internal",Ce,"PRIVATE")),mt.registerVersion(F,H),mt.registerVersion(F,H,"esm2017");const De="analytics",Le="firebase_id",Oe="origin",Pe="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Ne="https://www.googletagmanager.com/gtag/js",Ae=new class{constructor(e){this.name=e,this._logLevel=i,this._logHandler=s,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t))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,t.DEBUG,...e),this._logHandler(this,t.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.VERBOSE,...e),this._logHandler(this,t.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.INFO,...e),this._logHandler(this,t.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.WARN,...e),this._logHandler(this,t.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.ERROR,...e),this._logHandler(this,t.ERROR,...e)}}("@firebase/analytics"),ke=new d("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function Re(e){if(e.startsWith(Ne))return e;var t=ke.create("invalid-gtag-resource",{gtagURL:e});return Ae.warn(t.message),""}function je(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function Me(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:Re}),a=document.createElement("script");var r=`${Ne}?l=${e}&id=${t}`;a.src=n?null===n||void 0===n?void 0:n.createScriptURL(r):r,a.async=!0,document.head.appendChild(a)}function $e(p,f,g,h){return async function(e,...t){try{var n,a,r,i,o,s,c,l,u,d;"event"===e?([n,a]=t,await async function(e,n,a,r,i){try{let t=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const c=await je(a);for(const l of e){var o=c.find(e=>e.measurementId===l),s=o&&n[o.appId];if(!s){t=[];break}t.push(s)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",r,i||{})}catch(e){Ae.error(e)}}(p,f,g,n,a)):"config"===e?([r,i]=t,await async function(e,t,n,a,r,i){var o=a[r];try{if(o)await t[o];else{const c=await je(n);var s=c.find(e=>e.measurementId===r);s&&await t[s.appId]}}catch(e){Ae.error(e)}e("config",r,i)}(p,f,g,h,r,i)):"consent"===e?([o,s]=t,p("consent",o,s)):"get"===e?([c,l,u]=t,p("get",c,l,u)):"set"===e?([d]=t,p("set",d)):p(e,...t)}catch(e){Ae.error(e)}}}const Be=30;const Fe=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function He(e){var t,{appId:n,apiKey:a}=e,a={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":a})},n=Pe.replace("{app-id}",n);const r=await fetch(n,a);if(200===r.status||304===r.status)return r.json();{let e="";try{var i=await r.json();null!==(t=i.error)&&void 0!==t&&t.message&&(e=i.error.message)}catch(e){}throw ke.create("config-fetch-failed",{httpStatus:r.status,responseMessage:e})}}async function xe(e,t=Fe,n){var{appId:a,apiKey:r,measurementId:i}=e.options;if(!a)throw ke.create("no-app-id");if(!r){if(i)return{measurementId:i,appId:a};throw ke.create("no-api-key")}var o=t.getThrottleMetadata(a)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const s=new Ue;return setTimeout(async()=>{s.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:a},r,i=Fe){var o;const{appId:s,measurementId:c}=n;try{await Ve(r,e)}catch(e){if(c)return Ae.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:s,measurementId:c};throw e}try{const l=await He(n);return i.deleteThrottleMetadata(s),l}catch(e){const u=e;if(!qe(u)){if(i.deleteThrottleMetadata(s),c)return Ae.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null===u||void 0===u?void 0:u.message}]`),{appId:s,measurementId:c};throw e}const d=503===Number(null===(o=null===u||void 0===u?void 0:u.customData)||void 0===o?void 0:o.httpStatus)?y(a,i.intervalMillis,Be):y(a,i.intervalMillis),p={throttleEndTimeMillis:Date.now()+d,backoffCount:a+1};return i.setThrottleMetadata(s,p),Ae.debug(`Calling attemptFetch again in ${d} millis`),t(n,p,r,i)}}({appId:a,apiKey:r,measurementId:i},o,s,t)}function Ve(r,i){return new Promise((e,t)=>{var n=Math.max(i-Date.now(),0);const a=setTimeout(e,n);r.addEventListener(()=>{clearTimeout(a),t(ke.create("fetch-throttle",{throttleEndTimeMillis:i}))})})}function qe(e){if(!(e instanceof u&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class Ue{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function We(t,e,n,a,r,i,o){const s=xe(t);s.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Ae.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>Ae.error(e)),e.push(s);var c=async function(){if(!p())return Ae.warn(ke.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await f()}catch(e){return Ae.warn(ke.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return a.getId()}),[l,u]=await Promise.all([s,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(Ne)&&n.src.includes(e))return n}(i)&&Me(i,l.measurementId),r("js",new Date);const d=null!==(c=null==o?void 0:o.config)&&void 0!==c?c:{};return d[Oe]="firebase",d.update=!0,null!=u&&(d[Le]=u),r("config",l.measurementId,d),l.measurementId}class Ge{constructor(e){this.app=e}_delete(){return delete Ke[this.app.options.appId],Promise.resolve()}}let Ke={},ze=[];const Je={};let Ye="dataLayer",Xe="gtag",Ze,Qe,et=!1;function tt(e){if(et)throw ke.create("already-initialized");e.dataLayerName&&(Ye=e.dataLayerName),e.gtagName&&(Xe=e.gtagName)}function nt(e,t,n){!function(){const e=[];var t;c()&&e.push("This is a browser extension environment."),l()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=ke.create("invalid-analytics-context",{errorInfo:t}),Ae.warn(t.message))}();var a,r,i=e.options.appId;if(!i)throw ke.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw ke.create("no-api-key");Ae.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Ke[i])throw ke.create("already-exists",{id:i});return et||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(Ye),{wrappedGtag:a,gtagCore:r}=function(e,t,n,a,r){let i=function(){window[a].push(arguments)};return window[r]&&"function"==typeof window[r]&&(i=window[r]),window[r]=$e(i,e,t,n),{gtagCore:i,wrappedGtag:window[r]}}(Ke,ze,Je,Ye,Xe),Qe=a,Ze=r,et=!0),Ke[i]=We(e,ze,Je,t,Ze,Ye,n),new Ge(e)}async function at(){if(c())return!1;if(!l())return!1;if(!p())return!1;try{return await f()}catch(e){return!1}}function rt(e,t,n){e=I(e),async function(e,t,n,a){if(a&&a.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(Qe,Ke[e.app.options.appId],t,n).catch(e=>Ae.error(e))}function it(e,t,n){e=I(e),async function(e,t,n,a){if(a&&a.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(Qe,Ke[e.app.options.appId],t,n).catch(e=>Ae.error(e))}function ot(e,t,n){e=I(e),async function(e,t,n,a){if(a&&a.global){const r={};for(const i of Object.keys(n))r[`user_properties.${i}`]=n[i];return e("set",r),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(Qe,Ke[e.app.options.appId],t,n).catch(e=>Ae.error(e))}function st(e,t){e=I(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Ke[e.app.options.appId],t).catch(e=>Ae.error(e))}function ct(e,t,n,a){e=I(e),async function(e,t,n,a,r){var i;r&&r.global?e("event",n,a):(i=await t,e("event",n,Object.assign(Object.assign({},a),{send_to:i})))}(Qe,Ke[e.app.options.appId],t,n,a).catch(e=>Ae.error(e))}const lt="@firebase/analytics";mt._registerComponent(new b(De,(e,{options:t})=>{return nt(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),mt._registerComponent(new b("analytics-internal",function(e){try{const a=e.getProvider(De).getImmediate();return{logEvent:(e,t,n)=>ct(a,e,t,n)}}catch(e){throw ke.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),mt.registerVersion(lt,"0.10.5"),mt.registerVersion(lt,"0.10.5","esm2017");var ut,dt,pt;class ft{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){ct(this._delegate,e,t,n)}setCurrentScreen(e,t){rt(this._delegate,e,t)}setUserId(e,t){it(this._delegate,e,t)}setUserProperties(e,t){ot(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){st(this._delegate,e)}}(dt=ut=ut||{}).ADD_SHIPPING_INFO="add_shipping_info",dt.ADD_PAYMENT_INFO="add_payment_info",dt.ADD_TO_CART="add_to_cart",dt.ADD_TO_WISHLIST="add_to_wishlist",dt.BEGIN_CHECKOUT="begin_checkout",dt.CHECKOUT_PROGRESS="checkout_progress",dt.EXCEPTION="exception",dt.GENERATE_LEAD="generate_lead",dt.LOGIN="login",dt.PAGE_VIEW="page_view",dt.PURCHASE="purchase",dt.REFUND="refund",dt.REMOVE_FROM_CART="remove_from_cart",dt.SCREEN_VIEW="screen_view",dt.SEARCH="search",dt.SELECT_CONTENT="select_content",dt.SELECT_ITEM="select_item",dt.SELECT_PROMOTION="select_promotion",dt.SET_CHECKOUT_OPTION="set_checkout_option",dt.SHARE="share",dt.SIGN_UP="sign_up",dt.TIMING_COMPLETE="timing_complete",dt.VIEW_CART="view_cart",dt.VIEW_ITEM="view_item",dt.VIEW_ITEM_LIST="view_item_list",dt.VIEW_PROMOTION="view_promotion",dt.VIEW_SEARCH_RESULTS="view_search_results";const gt=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new ft(t,n)};pt={Analytics:ft,settings:tt,isSupported:at,EventName:ut},n.default.INTERNAL.registerComponent(new b("analytics-compat",gt,"PUBLIC").setServiceProps(pt).setMultipleInstances(!0)),n.default.registerVersion("@firebase/analytics-compat","0.2.11")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-analytics-compat.js - be sure to load firebase-app.js first.")}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(Ct,Ot){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t,r,n=e(Ct);(_t=t=t||{})[_t.DEBUG=0]="DEBUG",_t[_t.VERBOSE=1]="VERBOSE",_t[_t.INFO=2]="INFO",_t[_t.WARN=3]="WARN",_t[_t.ERROR=4]="ERROR",_t[_t.SILENT=5]="SILENT";const a={debug:t.DEBUG,verbose:t.VERBOSE,info:t.INFO,warn:t.WARN,error:t.ERROR,silent:t.SILENT},i=t.INFO,o={[t.DEBUG]:"log",[t.VERBOSE]:"log",[t.INFO]:"info",[t.WARN]:"warn",[t.ERROR]:"error"},s=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),a=o[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${r}] ${e.name}:`,...n)}};const c={};function l(e,t){if(n=e,!Array.isArray(n)||!Array.isArray(n.raw)||(n.length!==n.raw.length||!p&&n===n.raw||!(p&&!f||u(n)))||t+1!==e.length)throw new TypeError(` | ||
############################## ERROR ############################## | ||
It looks like you are trying to call a template tag function (fn\`...\`) | ||
using the normal function syntax (fn(...)), which is not supported. | ||
The functions in the safevalues library are not designed to be called | ||
like normal functions, and doing so invalidates the security guarantees | ||
that safevalues provides. | ||
If you are stuck and not sure how to proceed, please reach out to us | ||
instead through: | ||
- https://github.com/google/safevalues/issues | ||
############################## ERROR ##############################`);var n}function u(e){return Object.isFrozen(e)&&Object.isFrozen(e.raw)}function d(e){return-1===e.toString().indexOf("`")}const p=d(e=>e``)||d(e=>e`\0`)||d(e=>e`\n`)||d(e=>e`\u0000`),f=u``&&u`\0`&&u`\n`&&u`\u0000`;let h="google#safe";function g(){var e;return h,null!==(e=function(){if("undefined"!=typeof window)return window.trustedTypes}())&&void 0!==e?e:null}let m;class w{constructor(e,t){!function(e){if("production"!==process.env.NODE_ENV&&e!==c)throw new Error("Bad secret")}(t),this.privateDoNotAccessOrElseWrappedResourceUrl=e}toString(){return this.privateDoNotAccessOrElseWrappedResourceUrl.toString()}}function v(e){var t=e,n=null===(n=function(){var e,t;if(void 0===m)try{m=null!==(t=null===(e=g())||void 0===e?void 0:e.createPolicy(h,{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))&&void 0!==t?t:null}catch(e){m=null}return m}())||void 0===n?void 0:n.createScriptURL(t);return null!=n?n:new w(t,c)}function y(e,...t){if("production"!==process.env.NODE_ENV&&l(e,t.length),0===t.length)return v(e[0]);var n,r=e[0].toLowerCase();if("production"!==process.env.NODE_ENV){if(/^data:/.test(r))throw new Error("Data URLs cannot have expressions in the template literal input.");if(!(function(e){if(/^https:\/\//.test(e)||/^\/\//.test(e)){var t=e.indexOf("//")+2,n=e.indexOf("/",t);if(n<=t)throw new Error("Can't interpolate data in a url's origin, Please make sure to fully specify the origin, terminated with '/'.");n=e.substring(t,n);if(!/^[0-9a-z.:-]+$/i.test(n))throw new Error("The origin contains unsupported characters.");if(!/^[^:]*(:[0-9]+)?$/i.test(n))throw new Error("Invalid port number.");if(!/(^|\.)[a-z][^.]*$/i.test(n))throw new Error("The top-level domain must start with a letter.");return 1}}(r)||function(e){if(/^\//.test(e)){if("/"===e||1<e.length&&"/"!==e[1]&&"\\"!==e[1])return 1;throw new Error("The path start in the url is invalid.")}}(r)||(n=r,new RegExp("^[^:\\s\\\\/]+/").test(n))||function(e){if(/^about:blank/.test(e)){if("about:blank"!==e&&!/^about:blank#/.test(e))throw new Error("The about url is invalid.");return 1}}(r)))throw new Error("Trying to interpolate expressions in an unsupported url format.")}let a=e[0];for(let i=0;i<t.length;i++)a+=encodeURIComponent(t[i])+e[i+1];return v(a)}function I(e){return function(e,t){var n;const r=t.document,a=null===(n=r.querySelector)||void 0===n?void 0:n.call(r,`${e}[nonce]`);if(a)return a.nonce||a.getAttribute("nonce")||"";return""}("script",e)}function b(e,t,n){var r;e.src=function(e){var t;if(null!==(t=g())&&void 0!==t&&t.isScriptURL(e))return e;if(e instanceof w)return e.privateDoNotAccessOrElseWrappedResourceUrl;{let e="";throw"production"!==process.env.NODE_ENV&&(e="Unexpected type when unwrapping TrustedResourceUrl"),new Error(e)}}(t),null!=n&&n.omitNonce||(r=I((e=e).ownerDocument&&e.ownerDocument.defaultView||window))&&e.setAttribute("nonce",r)}function E(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function _(){try{return"object"==typeof indexedDB}catch(e){return}}function T(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},a.onupgradeneeded=()=>{e=!1},a.onerror=()=>{var e;n((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function S(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class D extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,D.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,C.prototype.create)}}class C{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},a=`${this.service}/${e}`,i=this.errors[e],i=i?(r=n,i.replace(O,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${a}).`;return new D(a,i,n)}}const O=/\{\$([^}]+)}/g,N=1e3,L=2,A=144e5,R=.5;function P(e,t=N,n=L){var r=t*Math.pow(n,e),a=Math.round(R*r*(Math.random()-.5)*2);return Math.min(A,r+a)}function k(e){return e&&e._delegate?e._delegate:e}class j{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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}}const M=(t,e)=>e.some(e=>t instanceof e);let $,x;const B=new WeakMap,F=new WeakMap,H=new WeakMap,V=new WeakMap,U=new WeakMap;let q={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return F.get(e);if("objectStoreNames"===t)return e.objectStoreNames||H.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return z(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function W(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(x=x||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(K(this),e),z(B.get(this))}:function(...e){return z(r.apply(K(this),e))}:function(e,...t){var n=r.call(K(this),e,...t);return H.set(n,e.sort?e.sort():[e]),z(n)}}function G(e){return"function"==typeof e?W(e):(e instanceof IDBTransaction&&(i=e,F.has(i)||(t=new Promise((e,t)=>{const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",a),i.removeEventListener("abort",a)},r=()=>{e(),n()},a=()=>{t(i.error||new DOMException("AbortError","AbortError")),n()};i.addEventListener("complete",r),i.addEventListener("error",a),i.addEventListener("abort",a)}),F.set(i,t))),M(e,$=$||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,q):e);var i,t}function z(e){if(e instanceof IDBRequest)return function(i){const e=new Promise((e,t)=>{const n=()=>{i.removeEventListener("success",r),i.removeEventListener("error",a)},r=()=>{e(z(i.result)),n()},a=()=>{t(i.error),n()};i.addEventListener("success",r),i.addEventListener("error",a)});return e.then(e=>{e instanceof IDBCursor&&B.set(e,i)}).catch(()=>{}),U.set(e,i),e}(e);if(V.has(e))return V.get(e);var t=G(e);return t!==e&&(V.set(e,t),U.set(t,e)),t}const K=e=>U.get(e);const J=["get","getKey","getAll","getAllKeys","count"],Y=["put","add","delete","clear"],X=new Map;function Z(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(X.get(t))return X.get(t);const a=t.replace(/FromIndex$/,""),i=t!==a,o=Y.includes(a);if(a in(i?IDBIndex:IDBObjectStore).prototype&&(o||J.includes(a))){var n=async function(e,...t){var n=this.transaction(e,o?"readwrite":"readonly");let r=n.store;return i&&(r=r.index(t.shift())),(await Promise.all([r[a](...t),o&&n.done]))[0]};return X.set(t,n),n}}}q={...r=q,get:(e,t,n)=>Z(e,t)||r.get(e,t,n),has:(e,t)=>!!Z(e,t)||r.has(e,t)};var Q="@firebase/installations",ee="0.6.8";const te=1e4,ne="w:0.6.8",re="FIS_v2",ae="https://firebaseinstallations.googleapis.com/v1",ie=36e5;const oe=new C("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 se(e){return e instanceof D&&e.code.includes("request-failed")}function ce({projectId:e}){return`${ae}/projects/${e}/installations`}function le(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function ue(e,t){var n=(await t.json()).error;return oe.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function de({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function pe(e,{refreshToken:t}){const n=de(e);return n.append("Authorization",(t=t,`${re} ${t}`)),n}async function fe(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function he(t){return new Promise(e=>{setTimeout(e,t)})}const ge=/^[cdef][\w-]{21}$/,me="";function we(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return ge.test(e)?e:me}catch(e){return me}}function ve(e){return`${e.appName}!${e.appId}`}const ye=new Map;function Ie(e,t){var n=ve(e);be(n,t),function(e,t){const n=function(){!Ee&&"BroadcastChannel"in self&&(Ee=new BroadcastChannel("[Firebase] FID Change"),Ee.onmessage=e=>{be(e.data.key,e.data.fid)});return Ee}();n&&n.postMessage({key:e,fid:t});0===ye.size&&Ee&&(Ee.close(),Ee=null)}(n,t)}function be(e,t){var n=ye.get(e);if(n)for(const r of n)r(t)}let Ee=null;const _e="firebase-installations-store";let Te=null;function Se(){return Te=Te||function(e,t,{blocked:n,upgrade:r,blocking:a,terminated:i}){const o=indexedDB.open(e,t),s=z(o);return r&&o.addEventListener("upgradeneeded",e=>{r(z(o.result),e.oldVersion,e.newVersion,z(o.transaction),e)}),n&&o.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),a&&e.addEventListener("versionchange",e=>a(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(_e)}}),Te}async function De(e,t){var n=ve(e);const r=await Se(),a=r.transaction(_e,"readwrite"),i=a.objectStore(_e);var o=await i.get(n);return await i.put(t,n),await a.done,o&&o.fid===t.fid||Ie(e,t.fid),t}async function Ce(e){var t=ve(e);const n=await Se(),r=n.transaction(_e,"readwrite");await r.objectStore(_e).delete(t),await r.done}async function Oe(e,t){var n=ve(e);const r=await Se(),a=r.transaction(_e,"readwrite"),i=a.objectStore(_e);var o=await i.get(n),s=t(o);return void 0===s?await i.delete(n):await i.put(s,n),await a.done,!s||o&&o.fid===s.fid||Ie(e,s.fid),s}async function Ne(n){let r;var e=await Oe(n.appConfig,e=>{var t=Ae(e||{fid:we(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Le(e.appConfig);for(;1===t.registrationStatus;)await he(100),t=await Le(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await Ne(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(oe.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=ce(e),a=de(e),i=t.getImmediate({optional:!0});!i||(o=await i.getHeartbeatsHeader())&&a.append("x-firebase-client",o);var o={fid:n,authVersion:re,appId:e.appId,sdkVersion:ne};const s={method:"POST",headers:a,body:JSON.stringify(o)},c=await fe(()=>fetch(r,s));if(c.ok){o=await c.json();return{fid:o.fid||n,registrationStatus:2,refreshToken:o.refreshToken,authToken:le(o.authToken)}}throw await ue("Create Installation",c)}(t,n);return De(t.appConfig,e)}catch(e){throw se(e)&&409===e.customData.serverCode?await Ce(t.appConfig):await De(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===me?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Le(e){return Oe(e,e=>{if(!e)throw oe.create("installation-not-found");return Ae(e)})}function Ae(e){return 1===(t=e).registrationStatus&&t.registrationTime+te<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Re({appConfig:e,heartbeatServiceProvider:t},n){const r=([a,i]=[e,n["fid"]],`${ce(a)}/${i}/authTokens:generate`);var a,i;const o=pe(e,n),s=t.getImmediate({optional:!0});!s||(c=await s.getHeartbeatsHeader())&&o.append("x-firebase-client",c);var c={installation:{sdkVersion:ne,appId:e.appId}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await fe(()=>fetch(r,l));if(u.ok)return le(await u.json());throw await ue("Generate Auth Token",u)}async function Pe(r,a=!1){let i;var e=await Oe(r.appConfig,e=>{if(!je(e))throw oe.create("not-registered");var t,n=e.authToken;if(a||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+ie}(t)){if(1===n.requestStatus)return i=async function(e,t){let n=await ke(e.appConfig);for(;1===n.authToken.requestStatus;)await he(100),n=await ke(e.appConfig);var r=n.authToken;return 0===r.requestStatus?Pe(e,t):r}(r,a),e;if(!navigator.onLine)throw oe.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return i=async function(t,n){try{var r=await Re(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await De(t.appConfig,e),r}catch(e){throw!se(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await De(t.appConfig,r)):await Ce(t.appConfig),e}}(r,n),n}return e});return i?await i:e.authToken}function ke(e){return Oe(e,e=>{if(!je(e))throw oe.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+te<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function je(e){return void 0!==e&&2===e.registrationStatus}async function Me(e,t=!1){var n,r=e;return await((n=(await Ne(r)).registrationPromise)&&await n),(await Pe(r,t)).token}function $e(e){return oe.create("missing-app-config-values",{valueName:e})}const xe="installations",Be=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw $e("App Configuration");if(!e.name)throw $e("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw $e(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:Ot._getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},Fe=e=>{var t=e.getProvider("app").getImmediate();const n=Ot._getProvider(t,xe).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await Ne(t);return(r||Pe(t)).catch(console.error),n.fid}(n),getToken:e=>Me(n,e)}};Ot._registerComponent(new j(xe,Be,"PUBLIC")),Ot._registerComponent(new j("installations-internal",Fe,"PRIVATE")),Ot.registerVersion(Q,ee),Ot.registerVersion(Q,ee,"esm2017");const He="analytics",Ve="firebase_id",Ue="origin",qe="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",We=new class{constructor(e){this.name=e,this._logLevel=i,this._logHandler=s,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,t.DEBUG,...e),this._logHandler(this,t.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.VERBOSE,...e),this._logHandler(this,t.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.INFO,...e),this._logHandler(this,t.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.WARN,...e),this._logHandler(this,t.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.ERROR,...e),this._logHandler(this,t.ERROR,...e)}}("@firebase/analytics");function Ge(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function ze(p,f,h,g){return async function(e,...t){try{var n,r,a,i,o,s,c,l,u,d;"event"===e?([n,r]=t,await async function(e,n,r,a,i){try{let t=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const c=await Ge(r);for(const l of e){var o=c.find(e=>e.measurementId===l),s=o&&n[o.appId];if(!s){t=[];break}t.push(s)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",a,i||{})}catch(e){We.error(e)}}(p,f,h,n,r)):"config"===e?([a,i]=t,await async function(e,t,n,r,a,i){var o=r[a];try{if(o)await t[o];else{const c=await Ge(n);var s=c.find(e=>e.measurementId===a);s&&await t[s.appId]}}catch(e){We.error(e)}e("config",a,i)}(p,f,h,g,a,i)):"consent"===e?([o,s]=t,p("consent",o,s)):"get"===e?([c,l,u]=t,p("get",c,l,u)):"set"===e?([d]=t,p("set",d)):p(e,...t)}catch(e){We.error(e)}}}const Ke=new C("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."}),Je=30;const Ye=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function Xe(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=qe.replace("{app-id}",n);const a=await fetch(n,r);if(200===a.status||304===a.status)return a.json();{let e="";try{var i=await a.json();null!==(t=i.error)&&void 0!==t&&t.message&&(e=i.error.message)}catch(e){}throw Ke.create("config-fetch-failed",{httpStatus:a.status,responseMessage:e})}}async function Ze(e,t=Ye,n){var{appId:r,apiKey:a,measurementId:i}=e.options;if(!r)throw Ke.create("no-app-id");if(!a){if(i)return{measurementId:i,appId:r};throw Ke.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const s=new tt;return setTimeout(async()=>{s.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},a,i=Ye){var o;const{appId:s,measurementId:c}=n;try{await Qe(a,e)}catch(e){if(c)return We.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:s,measurementId:c};throw e}try{const l=await Xe(n);return i.deleteThrottleMetadata(s),l}catch(e){const u=e;if(!et(u)){if(i.deleteThrottleMetadata(s),c)return We.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null===u||void 0===u?void 0:u.message}]`),{appId:s,measurementId:c};throw e}const d=503===Number(null===(o=null===u||void 0===u?void 0:u.customData)||void 0===o?void 0:o.httpStatus)?P(r,i.intervalMillis,Je):P(r,i.intervalMillis),p={throttleEndTimeMillis:Date.now()+d,backoffCount:r+1};return i.setThrottleMetadata(s,p),We.debug(`Calling attemptFetch again in ${d} millis`),t(n,p,a,i)}}({appId:r,apiKey:a,measurementId:i},o,s,t)}function Qe(a,i){return new Promise((e,t)=>{var n=Math.max(i-Date.now(),0);const r=setTimeout(e,n);a.addEventListener(()=>{clearTimeout(r),t(Ke.create("fetch-throttle",{throttleEndTimeMillis:i}))})})}function et(e){if(!(e instanceof D&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class tt{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function nt(t,e,n,r,a,i,o){const s=Ze(t);s.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&We.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>We.error(e)),e.push(s);var c=async function(){if(!_())return We.warn(Ke.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await T()}catch(e){return We.warn(Ke.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([s,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes("https://www.googletagmanager.com/gtag/js")&&n.src.includes(e))return n}(i)&&function(e,t){const n=document.createElement("script");var r=y`https://www.googletagmanager.com/gtag/js?l=${e}&id=${t}`;b(n,r),n.async=!0,document.head.appendChild(n)}(i,l.measurementId),a("js",new Date);const d=null!==(c=null==o?void 0:o.config)&&void 0!==c?c:{};return d[Ue]="firebase",d.update=!0,null!=u&&(d[Ve]=u),a("config",l.measurementId,d),l.measurementId}class rt{constructor(e){this.app=e}_delete(){return delete at[this.app.options.appId],Promise.resolve()}}let at={},it=[];const ot={};let st="dataLayer",ct="gtag",lt,ut,dt=!1;function pt(e){if(dt)throw Ke.create("already-initialized");e.dataLayerName&&(st=e.dataLayerName),e.gtagName&&(ct=e.gtagName)}function ft(e,t,n){!function(){const e=[];var t;E()&&e.push("This is a browser extension environment."),S()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Ke.create("invalid-analytics-context",{errorInfo:t}),We.warn(t.message))}();var r,a,i=e.options.appId;if(!i)throw Ke.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Ke.create("no-api-key");We.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=at[i])throw Ke.create("already-exists",{id:i});return dt||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(st),{wrappedGtag:r,gtagCore:a}=function(e,t,n,r,a){let i=function(){window[r].push(arguments)};return window[a]&&"function"==typeof window[a]&&(i=window[a]),window[a]=ze(i,e,t,n),{gtagCore:i,wrappedGtag:window[a]}}(at,it,ot,st,ct),ut=r,lt=a,dt=!0),at[i]=nt(e,it,ot,t,lt,st,n),new rt(e)}async function ht(){if(E())return!1;if(!S())return!1;if(!_())return!1;try{return await T()}catch(e){return!1}}function gt(e,t,n){e=k(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(ut,at[e.app.options.appId],t,n).catch(e=>We.error(e))}function mt(e,t,n){e=k(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(ut,at[e.app.options.appId],t,n).catch(e=>We.error(e))}function wt(e,t,n){e=k(e),async function(e,t,n,r){if(r&&r.global){const a={};for(const i of Object.keys(n))a[`user_properties.${i}`]=n[i];return e("set",a),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(ut,at[e.app.options.appId],t,n).catch(e=>We.error(e))}function vt(e,t){e=k(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(at[e.app.options.appId],t).catch(e=>We.error(e))}function yt(e,t,n,r){e=k(e),async function(e,t,n,r,a){var i;a&&a.global?e("event",n,r):(i=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:i})))}(ut,at[e.app.options.appId],t,n,r).catch(e=>We.error(e))}const It="@firebase/analytics",bt="0.10.6-20240716220314";Ot._registerComponent(new j(He,(e,{options:t})=>{return ft(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),Ot._registerComponent(new j("analytics-internal",function(e){try{const r=e.getProvider(He).getImmediate();return{logEvent:(e,t,n)=>yt(r,e,t,n)}}catch(e){throw Ke.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),Ot.registerVersion(It,bt),Ot.registerVersion(It,bt,"esm2017");var Et,_t,Tt;class St{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){yt(this._delegate,e,t,n)}setCurrentScreen(e,t){gt(this._delegate,e,t)}setUserId(e,t){mt(this._delegate,e,t)}setUserProperties(e,t){wt(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){vt(this._delegate,e)}}(_t=Et=Et||{}).ADD_SHIPPING_INFO="add_shipping_info",_t.ADD_PAYMENT_INFO="add_payment_info",_t.ADD_TO_CART="add_to_cart",_t.ADD_TO_WISHLIST="add_to_wishlist",_t.BEGIN_CHECKOUT="begin_checkout",_t.CHECKOUT_PROGRESS="checkout_progress",_t.EXCEPTION="exception",_t.GENERATE_LEAD="generate_lead",_t.LOGIN="login",_t.PAGE_VIEW="page_view",_t.PURCHASE="purchase",_t.REFUND="refund",_t.REMOVE_FROM_CART="remove_from_cart",_t.SCREEN_VIEW="screen_view",_t.SEARCH="search",_t.SELECT_CONTENT="select_content",_t.SELECT_ITEM="select_item",_t.SELECT_PROMOTION="select_promotion",_t.SET_CHECKOUT_OPTION="set_checkout_option",_t.SHARE="share",_t.SIGN_UP="sign_up",_t.TIMING_COMPLETE="timing_complete",_t.VIEW_CART="view_cart",_t.VIEW_ITEM="view_item",_t.VIEW_ITEM_LIST="view_item_list",_t.VIEW_PROMOTION="view_promotion",_t.VIEW_SEARCH_RESULTS="view_search_results";const Dt=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new St(t,n)};Tt={Analytics:St,settings:pt,isSupported:ht,EventName:Et},n.default.INTERNAL.registerComponent(new j("analytics-compat",Dt,"PUBLIC").setServiceProps(Tt).setMultipleInstances(!0)),n.default.registerVersion("@firebase/analytics-compat","0.2.12-20240716220314")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-analytics-compat.js - be sure to load firebase-app.js first.")}}); | ||
//# sourceMappingURL=firebase-analytics-compat.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";var r;!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"}(r||(r={}));const a={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},i=r.INFO,o={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),a=o[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${r}] ${e.name}:`,...n)};function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,a=this.errors[e],i=a?function replaceTemplate(e,t){return e.replace(s,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(a,n):"Error",o=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,o,n)}}const s=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;const n=e[a],i=t[a];if(isObject(n)&&isObject(i)){if(!deepEqual(n,i))return!1}else if(n!==i)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,n=2){const r=t*Math.pow(n,e),a=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+a)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 c,l;const u=new WeakMap,d=new WeakMap,p=new WeakMap,f=new WeakMap,g=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||p.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 l||(l=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(u.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return p.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return c||(c=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,h):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&u.set(t,e)})).catch((()=>{})),g.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),g.set(t,e)),t}const unwrap=e=>g.get(e);const m=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!m.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,a?"readwrite":"readonly");let o=i.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),a&&i.done]))[0]};return w.set(t,method),method}!function replaceTraps(e){h=e(h)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const I="@firebase/installations",v=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 n=(await t.json()).error;return v.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 b=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return b.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const E=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!T&&"BroadcastChannel"in self&&(T=new BroadcastChannel("[Firebase] FID Change"),T.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return T}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===E.size&&T&&(T.close(),T=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=E.get(e);if(n)for(const e of n)e(t)}let T=null;const C="firebase-installations-store";let D=null;function getDbPromise(){return D||(D=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:i}={}){const o=indexedDB.open(e,t),s=wrap(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(C)}})),D}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(C,"readwrite"),a=r.objectStore(C),i=await a.get(n);return await a.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(C,"readwrite");await n.objectStore(C).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(C,"readwrite"),a=r.objectStore(C),i=await a.get(n),o=t(i);return void 0===o?await a.delete(n):await a.put(o,n),await r.done,!o||i&&i.fid===o.fid||fidChanged(e,o.fid),o}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(v.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw v.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw v.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw v.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw v.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return v.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(I,"0.6.8"),e(I,"0.6.8","esm2017");const S="https://www.googletagmanager.com/gtag/js",A=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 r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}("@firebase/analytics"),k=new ErrorFactory("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function createGtagTrustedTypesScriptURL(e){if(!e.startsWith(S)){const t=k.create("invalid-gtag-resource",{gtagURL:e});return A.warn(t.message),""}return e}function promiseAllSettled(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function insertScriptTag(e,t){const n=function createTrustedTypesPolicy(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:createGtagTrustedTypesScriptURL}),r=document.createElement("script"),a=`${S}?l=${e}&id=${t}`;r.src=n?null==n?void 0:n.createScriptURL(a):a,r.async=!0,document.head.appendChild(r)}function wrapGtag(e,t,n,r){return async function gtagWrapper(a,...i){try{if("event"===a){const[r,a]=i;await async function gtagOnEvent(e,t,n,r,a){try{let i=[];if(a&&a.send_to){let e=a.send_to;Array.isArray(e)||(e=[e]);const r=await promiseAllSettled(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),a=e&&t[e.appId];if(!a){i=[];break}i.push(a)}}0===i.length&&(i=Object.values(t)),await Promise.all(i),e("event",r,a||{})}catch(e){A.error(e)}}(e,t,n,r,a)}else if("config"===a){const[a,o]=i;await async function gtagOnConfig(e,t,n,r,a,i){const o=r[a];try{if(o)await t[o];else{const e=(await promiseAllSettled(n)).find((e=>e.measurementId===a));e&&await t[e.appId]}}catch(e){A.error(e)}e("config",a,i)}(e,t,n,r,a,o)}else if("consent"===a){const[t,n]=i;e("consent",t,n)}else if("get"===a){const[t,n,r]=i;e("get",t,n,r)}else if("set"===a){const[t]=i;e("set",t)}else e(a,...i)}catch(e){A.error(e)}}}const R=new class RetryData{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function getHeaders(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function fetchDynamicConfigWithRetry(e,t=R,n){const{appId:r,apiKey:a,measurementId:i}=e.options;if(!r)throw k.create("no-app-id");if(!a){if(i)return{measurementId:i,appId:r};throw k.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},s=new AnalyticsAbortSignal;return setTimeout((async()=>{s.abort()}),void 0!==n?n:6e4),attemptFetchDynamicConfigWithRetry({appId:r,apiKey:a,measurementId:i},o,s,t)}async function attemptFetchDynamicConfigWithRetry(e,{throttleEndTimeMillis:t,backoffCount:n},r,a=R){var i;const{appId:o,measurementId:s}=e;try{await function setAbortableTimeout(e,t){return new Promise(((n,r)=>{const a=Math.max(t-Date.now(),0),i=setTimeout(n,a);e.addEventListener((()=>{clearTimeout(i),r(k.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(s)return A.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:s};throw e}try{const t=await async function fetchDynamicConfig(e){var t;const{appId:n,apiKey:r}=e,a={method:"GET",headers:getHeaders(r)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,a);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw k.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return a.deleteThrottleMetadata(o),t}catch(t){const c=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}(c)){if(a.deleteThrottleMetadata(o),s)return A.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==c?void 0:c.message}]`),{appId:o,measurementId:s};throw t}const l=503===Number(null===(i=null==c?void 0:c.customData)||void 0===i?void 0:i.httpStatus)?calculateBackoffMillis(n,a.intervalMillis,30):calculateBackoffMillis(n,a.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:n+1};return a.setThrottleMetadata(o,u),A.debug(`Calling attemptFetch again in ${l} millis`),attemptFetchDynamicConfigWithRetry(e,u,r,a)}}class AnalyticsAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let F,O;function _setConsentDefaultForInit(e){O=e}function _setDefaultEventParametersForInit(e){F=e}async function _initializeAnalytics(e,t,n,r,a,i,o){var s;const c=fetchDynamicConfigWithRetry(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&A.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>A.error(e))),t.push(c);const l=async function validateIndexedDB(){if(!isIndexedDBAvailable())return A.warn(k.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await validateIndexedDBOpenable()}catch(e){return A.warn(k.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,d]=await Promise.all([c,l]);(function findGtagScriptOnPage(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(S)&&n.src.includes(e))return n;return null})(i)||insertScriptTag(i,u.measurementId),O&&(a("consent","default",O),_setConsentDefaultForInit(void 0)),a("js",new Date);const p=null!==(s=null==o?void 0:o.config)&&void 0!==s?s:{};return p.origin="firebase",p.update=!0,null!=d&&(p.firebase_id=d),a("config",u.measurementId,p),F&&(a("set",F),_setDefaultEventParametersForInit(void 0)),u.measurementId}class AnalyticsService{constructor(e){this.app=e}_delete(){return delete P[this.app.options.appId],Promise.resolve()}}let P={},M=[];const L={};let B,j,$="dataLayer",x="gtag",_=!1;function settings(e){if(_)throw k.create("already-initialized");e.dataLayerName&&($=e.dataLayerName),e.gtagName&&(x=e.gtagName)}function factory(e,t,n){!function warnOnBrowserContextMismatch(){const e=[];if(isBrowserExtension()&&e.push("This is a browser extension environment."),areCookiesEnabled()||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=k.create("invalid-analytics-context",{errorInfo:t});A.warn(n.message)}}();const r=e.options.appId;if(!r)throw k.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw k.create("no-api-key");A.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=P[r])throw k.create("already-exists",{id:r});if(!_){!function getOrCreateDataLayer(e){let t=[];return Array.isArray(window[e])?t=window[e]:window[e]=t,t}($);const{wrappedGtag:e,gtagCore:t}=function wrapOrCreateGtag(e,t,n,r,a){let gtagCore=function(...e){window[r].push(arguments)};return window[a]&&"function"==typeof window[a]&&(gtagCore=window[a]),window[a]=wrapGtag(gtagCore,e,t,n),{gtagCore:gtagCore,wrappedGtag:window[a]}}(P,M,L,$,x);j=e,B=t,_=!0}P[r]=_initializeAnalytics(e,M,L,t,B,$,n);return new AnalyticsService(e)}function getAnalytics(e=n()){e=getModularInstance(e);const t=_getProvider(e,"analytics");return t.isInitialized()?t.getImmediate():initializeAnalytics(e)}function initializeAnalytics(e,t={}){const n=_getProvider(e,"analytics");if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(t,n.getOptions()))return e;throw k.create("already-initialized")}return n.initialize({options:t})}async function isSupported(){if(isBrowserExtension())return!1;if(!areCookiesEnabled())return!1;if(!isIndexedDBAvailable())return!1;try{return await validateIndexedDBOpenable()}catch(e){return!1}}function setCurrentScreen(e,t,n){e=getModularInstance(e),async function setCurrentScreen$1(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(j,P[e.app.options.appId],t,n).catch((e=>A.error(e)))}async function getGoogleAnalyticsClientId(e){return e=getModularInstance(e),async function internalGetGoogleAnalyticsClientId(e,t){const n=await t;return new Promise(((t,r)=>{e("get",n,"client_id",(e=>{e||r(k.create("no-client-id")),t(e)}))}))}(j,P[e.app.options.appId])}function setUserId(e,t,n){e=getModularInstance(e),async function setUserId$1(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(j,P[e.app.options.appId],t,n).catch((e=>A.error(e)))}function setUserProperties(e,t,n){e=getModularInstance(e),async function setUserProperties$1(e,t,n,r){if(r&&r.global){const t={};for(const e of Object.keys(n))t[`user_properties.${e}`]=n[e];return e("set",t),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(j,P[e.app.options.appId],t,n).catch((e=>A.error(e)))}function setAnalyticsCollectionEnabled(e,t){e=getModularInstance(e),async function setAnalyticsCollectionEnabled$1(e,t){const n=await e;window[`ga-disable-${n}`]=!t}(P[e.app.options.appId],t).catch((e=>A.error(e)))}function setDefaultEventParameters(e){j?j("set",e):_setDefaultEventParametersForInit(e)}function logEvent(e,t,n,r){e=getModularInstance(e),async function logEvent$1(e,t,n,r,a){if(a&&a.global)e("event",n,r);else{const a=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:a}))}}(j,P[e.app.options.appId],t,n,r).catch((e=>A.error(e)))}function setConsent(e){j?j("consent","update",e):_setConsentDefaultForInit(e)}const q="@firebase/analytics";!function registerAnalytics(){t(new Component("analytics",((e,{options:t})=>factory(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),t(new Component("analytics-internal",(function internalFactory(e){try{const t=e.getProvider("analytics").getImmediate();return{logEvent:(e,n,r)=>logEvent(t,e,n,r)}}catch(e){throw k.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),e(q,"0.10.5"),e(q,"0.10.5","esm2017")}();export{getAnalytics,getGoogleAnalyticsClientId,initializeAnalytics,isSupported,logEvent,setAnalyticsCollectionEnabled,setConsent,setCurrentScreen,setDefaultEventParameters,setUserId,setUserProperties,settings}; | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";var r;!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"}(r||(r={}));const a={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},i=r.INFO,o={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),a=o[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${r}] ${e.name}:`,...n)};const s={};function assertIsTemplateObject(e,t){if(!function isTemplateObject(e){if(!Array.isArray(e)||!Array.isArray(e.raw))return!1;if(e.length!==e.raw.length)return!1;if(!c&&e===e.raw)return!1;if((!c||l)&&!checkFrozen(e))return!1;return!0}(e)||t+1!==e.length)throw new TypeError("\n ############################## ERROR ##############################\n\n It looks like you are trying to call a template tag function (fn`...`)\n using the normal function syntax (fn(...)), which is not supported.\n\n The functions in the safevalues library are not designed to be called\n like normal functions, and doing so invalidates the security guarantees\n that safevalues provides.\n\n If you are stuck and not sure how to proceed, please reach out to us\n instead through:\n - https://github.com/google/safevalues/issues\n\n ############################## ERROR ##############################")}function checkFrozen(e){return Object.isFrozen(e)&&Object.isFrozen(e.raw)}function checkTranspiled(e){return-1===e.toString().indexOf("`")}const c=checkTranspiled((e=>e``))||checkTranspiled((e=>e`\0`))||checkTranspiled((e=>e`\n`))||checkTranspiled((e=>e`\u0000`)),l=checkFrozen``&&checkFrozen`\0`&&checkFrozen`\n`&&checkFrozen`\u0000`;let u;function getTrustedTypes(){var e;return null!==(e=function trustedTypes(){if("undefined"!=typeof window)return window.trustedTypes}())&&void 0!==e?e:null}class ResourceUrlImpl{constructor(e,t){!function ensureTokenIsValid(e){if("production"!==process.env.NODE_ENV&&e!==s)throw new Error("Bad secret")}(t),this.privateDoNotAccessOrElseWrappedResourceUrl=e}toString(){return this.privateDoNotAccessOrElseWrappedResourceUrl.toString()}}function createResourceUrlInternal(e){var t;const n=e,r=null===(t=function getTrustedTypesPolicy(){var e,t;if(void 0===u)try{u=null!==(t=null===(e=getTrustedTypes())||void 0===e?void 0:e.createPolicy("google#safe",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))&&void 0!==t?t:null}catch(e){u=null}return u}())||void 0===t?void 0:t.createScriptURL(n);return null!=r?r:new ResourceUrlImpl(n,s)}function trustedResourceUrl(e,...t){if("production"!==process.env.NODE_ENV&&assertIsTemplateObject(e,t.length),0===t.length)return createResourceUrlInternal(e[0]);const n=e[0].toLowerCase();if("production"!==process.env.NODE_ENV){if(/^data:/.test(n))throw new Error("Data URLs cannot have expressions in the template literal input.");if(!(function hasValidOrigin(e){if(!/^https:\/\//.test(e)&&!/^\/\//.test(e))return!1;const t=e.indexOf("//")+2,n=e.indexOf("/",t);if(n<=t)throw new Error("Can't interpolate data in a url's origin, Please make sure to fully specify the origin, terminated with '/'.");const r=e.substring(t,n);if(!/^[0-9a-z.:-]+$/i.test(r))throw new Error("The origin contains unsupported characters.");if(!/^[^:]*(:[0-9]+)?$/i.test(r))throw new Error("Invalid port number.");if(!/(^|\.)[a-z][^.]*$/i.test(r))throw new Error("The top-level domain must start with a letter.");return!0}(n)||function isValidPathStart(e){if(!/^\//.test(e))return!1;if("/"===e||e.length>1&&"/"!==e[1]&&"\\"!==e[1])return!0;throw new Error("The path start in the url is invalid.")}(n)||function isValidRelativePathStart(e){return new RegExp("^[^:\\s\\\\/]+/").test(e)}(n)||function isValidAboutUrl(e){if(!/^about:blank/.test(e))return!1;if("about:blank"!==e&&!/^about:blank#/.test(e))throw new Error("The about url is invalid.");return!0}(n)))throw new Error("Trying to interpolate expressions in an unsupported url format.")}let r=e[0];for(let n=0;n<t.length;n++)r+=encodeURIComponent(t[n])+e[n+1];return createResourceUrlInternal(r)}function setSrc(e,t,n){e.src=function unwrapResourceUrl(e){var t;if(null===(t=getTrustedTypes())||void 0===t?void 0:t.isScriptURL(e))return e;if(e instanceof ResourceUrlImpl)return e.privateDoNotAccessOrElseWrappedResourceUrl;{let e="";throw"production"!==process.env.NODE_ENV&&(e="Unexpected type when unwrapping TrustedResourceUrl"),new Error(e)}}(t),(null==n?void 0:n.omitNonce)||function setNonceForScriptElement(e){const t=function getScriptNonce(e){return function getNonceFor(e,t){var n;const r=t.document,a=null===(n=r.querySelector)||void 0===n?void 0:n.call(r,`${e}[nonce]`);return a&&(a.nonce||a.getAttribute("nonce"))||""}("script",e)}(e.ownerDocument&&e.ownerDocument.defaultView||window);t&&e.setAttribute("nonce",t)}(e)}function isBrowserExtension(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,a=this.errors[e],i=a?function replaceTemplate(e,t){return e.replace(d,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(a,n):"Error",o=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,o,n)}}const d=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;const n=e[a],i=t[a];if(isObject(n)&&isObject(i)){if(!deepEqual(n,i))return!1}else if(n!==i)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,n=2){const r=t*Math.pow(n,e),a=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+a)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 p,f;const g=new WeakMap,h=new WeakMap,m=new WeakMap,w=new WeakMap,y=new WeakMap;let v={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||m.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 f||(f=[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,...n){const r=e.call(unwrap(this),t,...n);return m.set(r,t.sort?t.sort():[t]),wrap(r)}}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,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(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 p||(p=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,v):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&g.set(t,e)})).catch((()=>{})),y.set(t,e),t}(e);if(w.has(e))return w.get(e);const t=transformCachableValue(e);return t!==e&&(w.set(e,t),y.set(t,e)),t}const unwrap=e=>y.get(e);const I=["get","getKey","getAll","getAllKeys","count"],b=["put","add","delete","clear"],E=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(E.get(t))return E.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=b.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!I.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,a?"readwrite":"readonly");let o=i.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),a&&i.done]))[0]};return E.set(t,method),method}!function replaceTraps(e){v=e(v)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const T="@firebase/installations",k=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 n=(await t.json()).error;return k.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 D=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return D.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const C=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!A&&"BroadcastChannel"in self&&(A=new BroadcastChannel("[Firebase] FID Change"),A.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return A}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===C.size&&A&&(A.close(),A=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=C.get(e);if(n)for(const e of n)e(t)}let A=null;const S="firebase-installations-store";let R=null;function getDbPromise(){return R||(R=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:i}={}){const o=indexedDB.open(e,t),s=wrap(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(S)}})),R}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),a=r.objectStore(S),i=await a.get(n);return await a.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(S,"readwrite");await n.objectStore(S).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),a=r.objectStore(S),i=await a.get(n),o=t(i);return void 0===o?await a.delete(n):await a.put(o,n),await r.done,!o||i&&i.fid===o.fid||fidChanged(e,o.fid),o}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(k.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw k.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const o={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(o)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw k.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw k.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw k.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return k.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(T,"0.6.8"),e(T,"0.6.8","esm2017");const F=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 r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}("@firebase/analytics");function promiseAllSettled(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}function wrapGtag(e,t,n,r){return async function gtagWrapper(a,...i){try{if("event"===a){const[r,a]=i;await async function gtagOnEvent(e,t,n,r,a){try{let i=[];if(a&&a.send_to){let e=a.send_to;Array.isArray(e)||(e=[e]);const r=await promiseAllSettled(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),a=e&&t[e.appId];if(!a){i=[];break}i.push(a)}}0===i.length&&(i=Object.values(t)),await Promise.all(i),e("event",r,a||{})}catch(e){F.error(e)}}(e,t,n,r,a)}else if("config"===a){const[a,o]=i;await async function gtagOnConfig(e,t,n,r,a,i){const o=r[a];try{if(o)await t[o];else{const e=(await promiseAllSettled(n)).find((e=>e.measurementId===a));e&&await t[e.appId]}}catch(e){F.error(e)}e("config",a,i)}(e,t,n,r,a,o)}else if("consent"===a){const[t,n]=i;e("consent",t,n)}else if("get"===a){const[t,n,r]=i;e("get",t,n,r)}else if("set"===a){const[t]=i;e("set",t)}else e(a,...i)}catch(e){F.error(e)}}}const O=new ErrorFactory("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});const P=new class RetryData{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function getHeaders(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function fetchDynamicConfigWithRetry(e,t=P,n){const{appId:r,apiKey:a,measurementId:i}=e.options;if(!r)throw O.create("no-app-id");if(!a){if(i)return{measurementId:i,appId:r};throw O.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},s=new AnalyticsAbortSignal;return setTimeout((async()=>{s.abort()}),void 0!==n?n:6e4),attemptFetchDynamicConfigWithRetry({appId:r,apiKey:a,measurementId:i},o,s,t)}async function attemptFetchDynamicConfigWithRetry(e,{throttleEndTimeMillis:t,backoffCount:n},r,a=P){var i;const{appId:o,measurementId:s}=e;try{await function setAbortableTimeout(e,t){return new Promise(((n,r)=>{const a=Math.max(t-Date.now(),0),i=setTimeout(n,a);e.addEventListener((()=>{clearTimeout(i),r(O.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(s)return F.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:s};throw e}try{const t=await async function fetchDynamicConfig(e){var t;const{appId:n,apiKey:r}=e,a={method:"GET",headers:getHeaders(r)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,a);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw O.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return a.deleteThrottleMetadata(o),t}catch(t){const c=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}(c)){if(a.deleteThrottleMetadata(o),s)return F.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${s} provided in the "measurementId" field in the local Firebase config. [${null==c?void 0:c.message}]`),{appId:o,measurementId:s};throw t}const l=503===Number(null===(i=null==c?void 0:c.customData)||void 0===i?void 0:i.httpStatus)?calculateBackoffMillis(n,a.intervalMillis,30):calculateBackoffMillis(n,a.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:n+1};return a.setThrottleMetadata(o,u),F.debug(`Calling attemptFetch again in ${l} millis`),attemptFetchDynamicConfigWithRetry(e,u,r,a)}}class AnalyticsAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}let M,x;function _setConsentDefaultForInit(e){x=e}function _setDefaultEventParametersForInit(e){M=e}async function _initializeAnalytics(e,t,n,r,a,i,o){var s;const c=fetchDynamicConfigWithRetry(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&F.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>F.error(e))),t.push(c);const l=async function validateIndexedDB(){if(!isIndexedDBAvailable())return F.warn(O.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await validateIndexedDBOpenable()}catch(e){return F.warn(O.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[u,d]=await Promise.all([c,l]);(function findGtagScriptOnPage(e){const t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes("https://www.googletagmanager.com/gtag/js")&&n.src.includes(e))return n;return null})(i)||function insertScriptTag(e,t){const n=document.createElement("script");setSrc(n,trustedResourceUrl`https://www.googletagmanager.com/gtag/js?l=${e}&id=${t}`),n.async=!0,document.head.appendChild(n)}(i,u.measurementId),x&&(a("consent","default",x),_setConsentDefaultForInit(void 0)),a("js",new Date);const p=null!==(s=null==o?void 0:o.config)&&void 0!==s?s:{};return p.origin="firebase",p.update=!0,null!=d&&(p.firebase_id=d),a("config",u.measurementId,p),M&&(a("set",M),_setDefaultEventParametersForInit(void 0)),u.measurementId}class AnalyticsService{constructor(e){this.app=e}_delete(){return delete L[this.app.options.appId],Promise.resolve()}}let L={},j=[];const B={};let $,N,_="dataLayer",q="gtag",H=!1;function settings(e){if(H)throw O.create("already-initialized");e.dataLayerName&&(_=e.dataLayerName),e.gtagName&&(q=e.gtagName)}function factory(e,t,n){!function warnOnBrowserContextMismatch(){const e=[];if(isBrowserExtension()&&e.push("This is a browser extension environment."),areCookiesEnabled()||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=O.create("invalid-analytics-context",{errorInfo:t});F.warn(n.message)}}();const r=e.options.appId;if(!r)throw O.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw O.create("no-api-key");F.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=L[r])throw O.create("already-exists",{id:r});if(!H){!function getOrCreateDataLayer(e){let t=[];return Array.isArray(window[e])?t=window[e]:window[e]=t,t}(_);const{wrappedGtag:e,gtagCore:t}=function wrapOrCreateGtag(e,t,n,r,a){let gtagCore=function(...e){window[r].push(arguments)};return window[a]&&"function"==typeof window[a]&&(gtagCore=window[a]),window[a]=wrapGtag(gtagCore,e,t,n),{gtagCore:gtagCore,wrappedGtag:window[a]}}(L,j,B,_,q);N=e,$=t,H=!0}L[r]=_initializeAnalytics(e,j,B,t,$,_,n);return new AnalyticsService(e)}function getAnalytics(e=n()){e=getModularInstance(e);const t=_getProvider(e,"analytics");return t.isInitialized()?t.getImmediate():initializeAnalytics(e)}function initializeAnalytics(e,t={}){const n=_getProvider(e,"analytics");if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(t,n.getOptions()))return e;throw O.create("already-initialized")}return n.initialize({options:t})}async function isSupported(){if(isBrowserExtension())return!1;if(!areCookiesEnabled())return!1;if(!isIndexedDBAvailable())return!1;try{return await validateIndexedDBOpenable()}catch(e){return!1}}function setCurrentScreen(e,t,n){e=getModularInstance(e),async function setCurrentScreen$1(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(N,L[e.app.options.appId],t,n).catch((e=>F.error(e)))}async function getGoogleAnalyticsClientId(e){return e=getModularInstance(e),async function internalGetGoogleAnalyticsClientId(e,t){const n=await t;return new Promise(((t,r)=>{e("get",n,"client_id",(e=>{e||r(O.create("no-client-id")),t(e)}))}))}(N,L[e.app.options.appId])}function setUserId(e,t,n){e=getModularInstance(e),async function setUserId$1(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(N,L[e.app.options.appId],t,n).catch((e=>F.error(e)))}function setUserProperties(e,t,n){e=getModularInstance(e),async function setUserProperties$1(e,t,n,r){if(r&&r.global){const t={};for(const e of Object.keys(n))t[`user_properties.${e}`]=n[e];return e("set",t),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(N,L[e.app.options.appId],t,n).catch((e=>F.error(e)))}function setAnalyticsCollectionEnabled(e,t){e=getModularInstance(e),async function setAnalyticsCollectionEnabled$1(e,t){const n=await e;window[`ga-disable-${n}`]=!t}(L[e.app.options.appId],t).catch((e=>F.error(e)))}function setDefaultEventParameters(e){N?N("set",e):_setDefaultEventParametersForInit(e)}function logEvent(e,t,n,r){e=getModularInstance(e),async function logEvent$1(e,t,n,r,a){if(a&&a.global)e("event",n,r);else{const a=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:a}))}}(N,L[e.app.options.appId],t,n,r).catch((e=>F.error(e)))}function setConsent(e){N?N("consent","update",e):_setConsentDefaultForInit(e)}const U="@firebase/analytics";!function registerAnalytics(){t(new Component("analytics",((e,{options:t})=>factory(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),t(new Component("analytics-internal",(function internalFactory(e){try{const t=e.getProvider("analytics").getImmediate();return{logEvent:(e,n,r)=>logEvent(t,e,n,r)}}catch(e){throw O.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),e(U,"0.10.6-20240716220314"),e(U,"0.10.6-20240716220314","esm2017")}();export{getAnalytics,getGoogleAnalyticsClientId,initializeAnalytics,isSupported,logEvent,setAnalyticsCollectionEnabled,setConsent,setCurrentScreen,setDefaultEventParameters,setUserId,setUserProperties,settings}; | ||
//# sourceMappingURL=firebase-analytics.js.map |
@@ -1,4 +0,18 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(Ce,Se){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t,r,n=e(Ce);const o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const o=[];for(let l=0;l<r.length;l+=3){var a=r[l],i=l+1<r.length,s=i?r[l+1]:0,c=l+2<r.length,h=c?r[l+2]:0;let e=(15&s)<<2|h>>6,t=63&h;c||(t=64,i||(e=64)),o.push(n[a>>2],n[(3&a)<<4|s>>4],n[e],n[t])}return o.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(t){const r=[];let n=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&o+1<t.length&&56320==(64512&t.charCodeAt(o+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++o)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){var o,a,i=e[r++];i<128?t[n++]=String.fromCharCode(i):191<i&&i<224?(o=e[r++],t[n++]=String.fromCharCode((31&i)<<6|63&o)):239<i&&i<365?(a=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t[n++]=String.fromCharCode(55296+(a>>10)),t[n++]=String.fromCharCode(56320+(1023&a))):(o=e[r++],a=e[r++],t[n++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&a))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_;const n=[];for(let c=0;c<e.length;){var o=r[e.charAt(c++)],a=c<e.length?r[e.charAt(c)]:0;++c;var i=c<e.length?r[e.charAt(c)]:64;++c;var s=c<e.length?r[e.charAt(c)]:64;if(++c,null==o||null==a||null==i||null==s)throw new h;n.push(o<<2|a>>4),64!==i&&(n.push(a<<4&240|i>>2),64!==s&&n.push(i<<6&192|s))}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class h extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const i=function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function a(){try{return"object"==typeof indexedDB}catch(e){return}}class c extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,c.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,l.prototype.create)}}class l{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},o=`${this.service}/${e}`,a=this.errors[e],a=a?(n=r,a.replace(p,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",a=`${this.serviceName}: ${a} (${o}).`;return new c(o,a,r)}}const p=/\{\$([^}]+)}/g;function u(e){return JSON.parse(e)}function d(e){const t=function(e){let t={},r={},n={},o="";try{var a=e.split(".");t=u(i(a[0])||""),r=u(i(a[1])||""),o=a[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:o}}(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}function g(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,r="x"===e?t:3&t|8;return r.toString(16)})}const f=144e5,v=.5;class E{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}(r=t=t||{})[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT";const _={debug:t.DEBUG,verbose:t.VERBOSE,info:t.INFO,warn:t.WARN,error:t.ERROR,silent:t.SILENT},w=t.INFO,m={[t.DEBUG]:"log",[t.VERBOSE]:"log",[t.INFO]:"info",[t.WARN]:"warn",[t.ERROR]:"error"},k=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),o=m[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)}};const b=new Map,y={activated:!1,tokenObservers:[]},A={initialized:!1,enabled:!1};function T(e){return b.get(e)||Object.assign({},y)}const C="https://content-firebaseappcheck.googleapis.com/v1",S="exchangeDebugToken",R={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class P{constructor(e,t,r,n,o){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=o,this.pending=null,o<(this.nextErrorWaitInterval=n))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new s,this.pending.promise.catch(e=>{}),t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new s,this.pending.promise.catch(e=>{}),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const I=new l("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","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}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function D(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function O(e){if(!T(e).activated)throw I.create("use-before-activation",{appName:e.name})}function x(e){var t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),t=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=N(r)+"d:"),n&&(a+=N(n)+"h:"),a+=N(o)+"m:"+N(t)+"s",a}function N(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function M({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&(n["X-Firebase-Client"]=c);var a={method:"POST",body:JSON.stringify(t),headers:n};let i;try{i=await fetch(e,a)}catch(e){throw I.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==i.status)throw I.create("fetch-status-error",{httpStatus:i.status});let s;try{s=await i.json()}catch(e){throw I.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}var c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw I.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${s.ttl}`});a=1e3*Number(c[1]),c=Date.now();return{token:s.token,expireTimeMillis:c+a,issuedAtTimeMillis:c}}function L(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${C}/projects/${r}/apps/${n}:${S}?key=${o}`,body:{debug_token:t}}}const B="firebase-app-check-database",H=1,$="firebase-app-check-store",j="debug-token";let W=null;function F(){return W||(W=new Promise((t,r)=>{try{const e=indexedDB.open(B,H);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;r(I.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore($,{keyPath:"compositeKey"})}}catch(e){r(I.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}),W)}async function V(e,t){const r=await F(),n=r.transaction($,"readwrite"),o=n.objectStore($),a=o.put({compositeKey:e,value:t});return new Promise((t,r)=>{a.onsuccess=e=>{t()},n.onerror=e=>{var t;r(I.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function K(e){const t=await F(),o=t.transaction($,"readonly"),r=o.objectStore($),a=r.get(e);return new Promise((r,n)=>{a.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},o.onerror=e=>{var t;n(I.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function z(e){return`${e.options.appId}-${e.name}`}const U=new class{constructor(e){this.name=e,this._logLevel=w,this._logHandler=k,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?_[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,t.DEBUG,...e),this._logHandler(this,t.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.VERBOSE,...e),this._logHandler(this,t.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.INFO,...e),this._logHandler(this,t.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.WARN,...e),this._logHandler(this,t.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.ERROR,...e),this._logHandler(this,t.ERROR,...e)}}("@firebase/app-check");async function q(t){if(a()){let e=void 0;try{e=await K(z(t))}catch(e){U.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function G(e,t){return a()?V(z(e),t).catch(e=>{U.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function X(){let e=void 0;try{e=await K(j)}catch(e){}if(e)return e;var t,r=g();return t=r,V(j,t).catch(e=>U.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),r}function J(){return A.enabled}async function Y(){var e=A;if(e.enabled&&e.token)return e.token.promise;throw Error(` | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(Be,He){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t,r,n=e(Be);const o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const o=[];for(let h=0;h<r.length;h+=3){var a=r[h],i=h+1<r.length,s=i?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&s)<<2|l>>6,t=63&l;c||(t=64,i||(e=64)),o.push(n[a>>2],n[(3&a)<<4|s>>4],n[e],n[t])}return o.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(t){const r=[];let n=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&o+1<t.length&&56320==(64512&t.charCodeAt(o+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++o)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){var o,a,i=e[r++];i<128?t[n++]=String.fromCharCode(i):191<i&&i<224?(o=e[r++],t[n++]=String.fromCharCode((31&i)<<6|63&o)):239<i&&i<365?(a=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t[n++]=String.fromCharCode(55296+(a>>10)),t[n++]=String.fromCharCode(56320+(1023&a))):(o=e[r++],a=e[r++],t[n++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&a))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_;const n=[];for(let c=0;c<e.length;){var o=r[e.charAt(c++)],a=c<e.length?r[e.charAt(c)]:0;++c;var i=c<e.length?r[e.charAt(c)]:64;++c;var s=c<e.length?r[e.charAt(c)]:64;if(++c,null==o||null==a||null==i||null==s)throw new l;n.push(o<<2|a>>4),64!==i&&(n.push(a<<4&240|i>>2),64!==s&&n.push(i<<6&192|s))}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const i=function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function a(){try{return"object"==typeof indexedDB}catch(e){return}}class c extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,c.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,h.prototype.create)}}class h{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},o=`${this.service}/${e}`,a=this.errors[e],a=a?(n=r,a.replace(u,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",a=`${this.serviceName}: ${a} (${o}).`;return new c(o,a,r)}}const u=/\{\$([^}]+)}/g;function p(e){return JSON.parse(e)}function d(e){const t=function(e){let t={},r={},n={},o="";try{var a=e.split(".");t=p(i(a[0])||""),r=p(i(a[1])||""),o=a[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:o}}(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}function f(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,r="x"===e?t:3&t|8;return r.toString(16)})}const g=144e5,v=.5;class w{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}(r=t=t||{})[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT";const E={debug:t.DEBUG,verbose:t.VERBOSE,info:t.INFO,warn:t.WARN,error:t.ERROR,silent:t.SILENT},m=t.INFO,b={[t.DEBUG]:"log",[t.VERBOSE]:"log",[t.INFO]:"info",[t.WARN]:"warn",[t.ERROR]:"error"},_=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),o=b[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)}};const k={};function y(e,t){if(r=e,!Array.isArray(r)||!Array.isArray(r.raw)||(r.length!==r.raw.length||!S&&r===r.raw||!(S&&!C||A(r)))||t+1!==e.length)throw new TypeError(` | ||
############################## ERROR ############################## | ||
It looks like you are trying to call a template tag function (fn\`...\`) | ||
using the normal function syntax (fn(...)), which is not supported. | ||
The functions in the safevalues library are not designed to be called | ||
like normal functions, and doing so invalidates the security guarantees | ||
that safevalues provides. | ||
If you are stuck and not sure how to proceed, please reach out to us | ||
instead through: | ||
- https://github.com/google/safevalues/issues | ||
############################## ERROR ##############################`);var r}function A(e){return Object.isFrozen(e)&&Object.isFrozen(e.raw)}function T(e){return-1===e.toString().indexOf("`")}const S=T(e=>e``)||T(e=>e`\0`)||T(e=>e`\n`)||T(e=>e`\u0000`),C=A``&&A`\0`&&A`\n`&&A`\u0000`;function R(){var e;return null!==(e=function(){if("undefined"!=typeof window)return window.trustedTypes}())&&void 0!==e?e:null}let P;class O{constructor(e,t){!function(e){if("production"!==process.env.NODE_ENV&&e!==k)throw new Error("Bad secret")}(t),this.privateDoNotAccessOrElseWrappedResourceUrl=e}toString(){return this.privateDoNotAccessOrElseWrappedResourceUrl.toString()}}function D(e){var t=e,r=null===(r=function(){var e,t;if(void 0===P)try{P=null!==(t=null===(e=R())||void 0===e?void 0:e.createPolicy("google#safe",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))&&void 0!==t?t:null}catch(e){P=null}return P}())||void 0===r?void 0:r.createScriptURL(t);return null!=r?r:new O(t,k)}function N(e,...t){if("production"!==process.env.NODE_ENV&&y(e,t.length),0===t.length)return D(e[0]);var r,n=e[0].toLowerCase();if("production"!==process.env.NODE_ENV){if(/^data:/.test(n))throw new Error("Data URLs cannot have expressions in the template literal input.");if(!(function(e){if(/^https:\/\//.test(e)||/^\/\//.test(e)){var t=e.indexOf("//")+2,r=e.indexOf("/",t);if(r<=t)throw new Error("Can't interpolate data in a url's origin, Please make sure to fully specify the origin, terminated with '/'.");r=e.substring(t,r);if(!/^[0-9a-z.:-]+$/i.test(r))throw new Error("The origin contains unsupported characters.");if(!/^[^:]*(:[0-9]+)?$/i.test(r))throw new Error("Invalid port number.");if(!/(^|\.)[a-z][^.]*$/i.test(r))throw new Error("The top-level domain must start with a letter.");return 1}}(n)||function(e){if(/^\//.test(e)){if("/"===e||1<e.length&&"/"!==e[1]&&"\\"!==e[1])return 1;throw new Error("The path start in the url is invalid.")}}(n)||(r=n,new RegExp("^[^:\\s\\\\/]+/").test(r))||function(e){if(/^about:blank/.test(e)){if("about:blank"!==e&&!/^about:blank#/.test(e))throw new Error("The about url is invalid.");return 1}}(n)))throw new Error("Trying to interpolate expressions in an unsupported url format.")}let o=e[0];for(let a=0;a<t.length;a++)o+=encodeURIComponent(t[a])+e[a+1];return D(o)}function I(e){return function(e,t){var r;const n=t.document,o=null===(r=n.querySelector)||void 0===r?void 0:r.call(n,`${e}[nonce]`);if(o)return o.nonce||o.getAttribute("nonce")||"";return""}("script",e)}function x(e,t,r){var n;e.src=function(e){var t;if(null!==(t=R())&&void 0!==t&&t.isScriptURL(e))return e;if(e instanceof O)return e.privateDoNotAccessOrElseWrappedResourceUrl;{let e="";throw"production"!==process.env.NODE_ENV&&(e="Unexpected type when unwrapping TrustedResourceUrl"),new Error(e)}}(t),null!=r&&r.omitNonce||(n=I((e=e).ownerDocument&&e.ownerDocument.defaultView||window))&&e.setAttribute("nonce",n)}const L=new Map,M={activated:!1,tokenObservers:[]},B={initialized:!1,enabled:!1};function H(e){return L.get(e)||Object.assign({},M)}const $="https://content-firebaseappcheck.googleapis.com/v1",W="exchangeDebugToken",j={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class F{constructor(e,t,r,n,o){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=o,this.pending=null,o<(this.nextErrorWaitInterval=n))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new s,this.pending.promise.catch(e=>{}),t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new s,this.pending.promise.catch(e=>{}),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const V=new h("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","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}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function U(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function z(e){if(!H(e).activated)throw V.create("use-before-activation",{appName:e.name})}function K(e){var t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),t=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=q(r)+"d:"),n&&(a+=q(n)+"h:"),a+=q(o)+"m:"+q(t)+"s",a}function q(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function G({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&(n["X-Firebase-Client"]=c);var a={method:"POST",body:JSON.stringify(t),headers:n};let i;try{i=await fetch(e,a)}catch(e){throw V.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==i.status)throw V.create("fetch-status-error",{httpStatus:i.status});let s;try{s=await i.json()}catch(e){throw V.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}var c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw V.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${s.ttl}`});a=1e3*Number(c[1]),c=Date.now();return{token:s.token,expireTimeMillis:c+a,issuedAtTimeMillis:c}}function X(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${$}/projects/${r}/apps/${n}:${W}?key=${o}`,body:{debug_token:t}}}const J="firebase-app-check-database",Y=1,Z="firebase-app-check-store",Q="debug-token";let ee=null;function te(){return ee||(ee=new Promise((t,r)=>{try{const e=indexedDB.open(J,Y);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;r(V.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(Z,{keyPath:"compositeKey"})}}catch(e){r(V.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}),ee)}async function re(e,t){const r=await te(),n=r.transaction(Z,"readwrite"),o=n.objectStore(Z),a=o.put({compositeKey:e,value:t});return new Promise((t,r)=>{a.onsuccess=e=>{t()},n.onerror=e=>{var t;r(V.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function ne(e){const t=await te(),o=t.transaction(Z,"readonly"),r=o.objectStore(Z),a=r.get(e);return new Promise((r,n)=>{a.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},o.onerror=e=>{var t;n(V.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function oe(e){return`${e.options.appId}-${e.name}`}const ae=new class{constructor(e){this.name=e,this._logLevel=m,this._logHandler=_,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?E[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,t.DEBUG,...e),this._logHandler(this,t.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.VERBOSE,...e),this._logHandler(this,t.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.INFO,...e),this._logHandler(this,t.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.WARN,...e),this._logHandler(this,t.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.ERROR,...e),this._logHandler(this,t.ERROR,...e)}}("@firebase/app-check");async function ie(t){if(a()){let e=void 0;try{e=await ne(oe(t))}catch(e){ae.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function se(e,t){return a()?re(oe(e),t).catch(e=>{ae.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function ce(){let e=void 0;try{e=await ne(Q)}catch(e){}if(e)return e;var t,r=f();return t=r,re(Q,t).catch(e=>ae.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),r}function le(){return B.enabled}async function he(){var e=B;if(e.enabled&&e.token)return e.token.promise;throw Error(` | ||
Can't get debug token in production mode. | ||
`)}function Z(){var e=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}();const t=A;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const r=new s;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(X())}}const Q={error:"UNKNOWN_ERROR"};async function ee(e,t=!1){var r=e.app;O(r);const n=T(r);let o=n.token,a=void 0;if(o&&!ae(o)&&(n.token=void 0,o=void 0),o||(s=await n.cachedTokenPromise)&&(ae(s)?o=s:await G(r,void 0)),!t&&o&&ae(o))return{token:o.token};let i=!1;if(J()){n.exchangeTokenPromise||(n.exchangeTokenPromise=M(L(r,await Y()),e.heartbeatServiceProvider).finally(()=>{n.exchangeTokenPromise=void 0}),i=!0);var s=await n.exchangeTokenPromise;return await G(r,s),{token:(n.token=s).token}}try{n.exchangeTokenPromise||(n.exchangeTokenPromise=n.provider.getToken().finally(()=>{n.exchangeTokenPromise=void 0}),i=!0),o=await T(r).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?U.warn(e.message):U.error(e),a=e}let c;return o?a?c=ae(o)?{token:o.token,internalError:a}:ie(a):(c={token:o.token},n.token=o,await G(r,o)):c=ie(a),i&&oe(r,c),c}function te(e,t,r,n){var o=e["app"];const a=T(o);o={next:r,error:n,type:t};if(a.tokenObservers=[...a.tokenObservers,o],a.token&&ae(a.token)){const i=a.token;Promise.resolve().then(()=>{r({token:i.token}),ne(e)}).catch(()=>{})}a.cachedTokenPromise.then(()=>ne(e))}function re(e,t){const r=T(e);var n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function ne(e){var t=e["app"];const r=T(t);let n=r.tokenRefresher;n||(n=function(r){const n=r["app"];return new P(async()=>{var e=T(n);let t;if(t=e.token?await ee(r,!0):await ee(r),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=T(n);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},R.RETRIAL_MIN_WAIT,R.RETRIAL_MAX_WAIT)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function oe(e,t){for(const r of T(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function ae(e){return 0<e.expireTimeMillis-Date.now()}function ie(e){return{token:(t=Q,o.encodeString(JSON.stringify(t),!1)),error:e};var t}class se{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=T(this.app)["tokenObservers"];for(const t of e)re(this.app,t.next);return Promise.resolve()}}function ce(t){return{getToken:e=>ee(t,e),getLimitedUseToken:()=>async function(e){var t=e.app;O(t);const r=T(t)["provider"];if(J()){var n=(await M(L(t,await Y()),e.heartbeatServiceProvider))["token"];return{token:n}}return{token:n=(await r.getToken())["token"]}}(t),addTokenListener:e=>te(t,"INTERNAL",e),removeTokenListener:e=>re(t.app,e)}}const he="https://www.google.com/recaptcha/api.js",le="https://www.google.com/recaptcha/enterprise.js";function pe(t,r){const n=new s,e=T(t);e.reCAPTCHAState={initialized:n};const o=ge(t);var a=D(!1);return a?de(t,r,a,o,n):function(e){const t=document.createElement("script");t.src=he,t.onload=e,document.head.appendChild(t)}(()=>{var e=D(!1);if(!e)throw new Error("no recaptcha");de(t,r,e,o,n)}),n.promise}function ue(t,r){const n=new s,e=T(t);e.reCAPTCHAState={initialized:n};const o=ge(t);var a=D(!0);return a?de(t,r,a,o,n):function(e){const t=document.createElement("script");t.src=le,t.onload=e,document.head.appendChild(t)}(()=>{var e=D(!0);if(!e)throw new Error("no recaptcha");de(t,r,e,o,n)}),n.promise}function de(e,t,r,n,o){r.ready(()=>{!function(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{T(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{T(e).reCAPTCHAState.succeeded=!1}}),a=T(e);a.reCAPTCHAState=Object.assign(Object.assign({},a.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)})}function ge(e){var t=`fire_app_check_${e.name}`;const r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function fe(n){O(n);const o=await T(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const r=T(n).reCAPTCHAState;o.ready(()=>{e(o.execute(r.widgetId,{action:"fire_app_check"}))})})}class ve{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;me(this._throttleData);var t=await fe(this._app).catch(e=>{throw I.create("recaptcha-error")});if(null===(e=T(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw I.create("recaptcha-error");let r;try{r=await M(function(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${C}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=we(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),I.create("throttled",{time:x(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,r}initialize(e){this._app=e,this._heartbeatServiceProvider=Se._getProvider(e,"heartbeat"),pe(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof ve&&this._siteKey===e._siteKey}}class Ee{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;me(this._throttleData);var t=await fe(this._app).catch(e=>{throw I.create("recaptcha-error")});if(null===(e=T(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw I.create("recaptcha-error");let r;try{r=await M(function(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${C}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=we(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),I.create("throttled",{time:x(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,r}initialize(e){this._app=e,this._heartbeatServiceProvider=Se._getProvider(e,"heartbeat"),ue(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Ee&&this._siteKey===e._siteKey}}class _e{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=d(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof _e&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function we(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var r,n,o=t?t.backoffCount:0,n=(t=2,r=1e3*Math.pow(t,o),n=Math.round(v*r*(Math.random()-.5)*2),Math.min(f,r+n));return{backoffCount:o+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}function me(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw I.create("throttled",{time:x(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function ke(e=Se.getApp(),t){var r;e=(r=e)&&r._delegate?r._delegate:r;const n=Se._getProvider(e,"app-check");if(A.initialized||Z(),J()&&Y().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var o=n.getImmediate();const a=n.getOptions();if(a.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&a.provider.isEqual(t.provider))return o;throw I.create("already-initialized",{appName:e.name})}o=n.initialize({options:t});return function(t,e,r){const n=function(e,t){return b.set(e,t),b.get(e)}(t,Object.assign({},y));n.activated=!0,n.provider=e,n.cachedTokenPromise=q(t).then(e=>(e&&ae(e)&&(n.token=e,oe(t,{token:e.token})),e)),n.isTokenAutoRefreshEnabled=void 0===r?t.automaticDataCollectionEnabled:r,n.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),T(e).isTokenAutoRefreshEnabled&&te(o,"INTERNAL",()=>{}),o}const be="app-check-internal";Se._registerComponent(new E("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return t=r,e=n,new se(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(be).initialize()})),Se._registerComponent(new E(be,e=>{return ce(e.getProvider("app-check").getImmediate())},"PUBLIC").setInstantiationMode("EXPLICIT")),Se.registerVersion("@firebase/app-check","0.8.5");const ye=new l("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class Ae{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new ve(e):e instanceof Ee||e instanceof ve||e instanceof _e?e:new _e({getToken:e.getToken}),this._delegate=ke(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw ye.create("use-before-activation",{appName:this.app.name});!function(e,t){const r=T(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}(this._delegate,e)}getToken(e){if(!this._delegate)throw ye.create("use-before-activation",{appName:this.app.name});return async function(e,t){var r=await ee(e,t);if(r.error)throw r.error;return{token:r.token}}(this._delegate,e)}onTokenChanged(e,t,r){if(!this._delegate)throw ye.create("use-before-activation",{appName:this.app.name});return function(e,t,r){let n=()=>{},o=()=>{};return n=null!=t.next?t.next.bind(t):t,null!=t.error?o=t.error.bind(t):r&&(o=r),te(e,"EXTERNAL",n,o),()=>re(e.app,n)}(this._delegate,e,t)}}const Te=e=>{var t=e.getProvider("app-compat").getImmediate();return new Ae(t)};n.default.INTERNAL.registerComponent(new E("appCheck-compat",Te,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Ee,ReCaptchaV3Provider:ve,CustomProvider:_e})),n.default.registerVersion("@firebase/app-check-compat","0.3.12")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-app-check-compat.js - be sure to load firebase-app.js first.")}}); | ||
`)}function ue(){var e=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}();const t=B;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const r=new s;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(ce())}}const pe={error:"UNKNOWN_ERROR"};async function de(e,t=!1){var r=e.app;z(r);const n=H(r);let o=n.token,a=void 0;if(o&&!Ee(o)&&(n.token=void 0,o=void 0),o||(s=await n.cachedTokenPromise)&&(Ee(s)?o=s:await se(r,void 0)),!t&&o&&Ee(o))return{token:o.token};let i=!1;if(le()){n.exchangeTokenPromise||(n.exchangeTokenPromise=G(X(r,await he()),e.heartbeatServiceProvider).finally(()=>{n.exchangeTokenPromise=void 0}),i=!0);var s=await n.exchangeTokenPromise;return await se(r,s),{token:(n.token=s).token}}try{n.exchangeTokenPromise||(n.exchangeTokenPromise=n.provider.getToken().finally(()=>{n.exchangeTokenPromise=void 0}),i=!0),o=await H(r).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?ae.warn(e.message):ae.error(e),a=e}let c;return o?a?c=Ee(o)?{token:o.token,internalError:a}:me(a):(c={token:o.token},n.token=o,await se(r,o)):c=me(a),i&&we(r,c),c}function fe(e,t,r,n){var o=e["app"];const a=H(o);o={next:r,error:n,type:t};if(a.tokenObservers=[...a.tokenObservers,o],a.token&&Ee(a.token)){const i=a.token;Promise.resolve().then(()=>{r({token:i.token}),ve(e)}).catch(()=>{})}a.cachedTokenPromise.then(()=>ve(e))}function ge(e,t){const r=H(e);var n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function ve(e){var t=e["app"];const r=H(t);let n=r.tokenRefresher;n||(n=function(r){const n=r["app"];return new F(async()=>{var e=H(n);let t;if(t=e.token?await de(r,!0):await de(r),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=H(n);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},j.RETRIAL_MIN_WAIT,j.RETRIAL_MAX_WAIT)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function we(e,t){for(const r of H(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function Ee(e){return 0<e.expireTimeMillis-Date.now()}function me(e){return{token:(t=pe,o.encodeString(JSON.stringify(t),!1)),error:e};var t}class be{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=H(this.app)["tokenObservers"];for(const t of e)ge(this.app,t.next);return Promise.resolve()}}function _e(t){return{getToken:e=>de(t,e),getLimitedUseToken:()=>async function(e){var t=e.app;z(t);const r=H(t)["provider"];if(le()){var n=(await G(X(t,await he()),e.heartbeatServiceProvider))["token"];return{token:n}}return{token:n=(await r.getToken())["token"]}}(t),addTokenListener:e=>fe(t,"INTERNAL",e),removeTokenListener:e=>ge(t.app,e)}}function ke(t,r){const n=new s,e=H(t);e.reCAPTCHAState={initialized:n};const o=Te(t);var a=U(!1);return a?Ae(t,r,a,o,n):function(e){const t=document.createElement("script");x(t,N`https://www.google.com/recaptcha/api.js`),t.onload=e,document.head.appendChild(t)}(()=>{var e=U(!1);if(!e)throw new Error("no recaptcha");Ae(t,r,e,o,n)}),n.promise}function ye(t,r){const n=new s,e=H(t);e.reCAPTCHAState={initialized:n};const o=Te(t);var a=U(!0);return a?Ae(t,r,a,o,n):function(e){const t=document.createElement("script");x(t,N`https://www.google.com/recaptcha/enterprise.js`),t.onload=e,document.head.appendChild(t)}(()=>{var e=U(!0);if(!e)throw new Error("no recaptcha");Ae(t,r,e,o,n)}),n.promise}function Ae(e,t,r,n,o){r.ready(()=>{!function(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{H(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{H(e).reCAPTCHAState.succeeded=!1}}),a=H(e);a.reCAPTCHAState=Object.assign(Object.assign({},a.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)})}function Te(e){var t=`fire_app_check_${e.name}`;const r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function Se(n){z(n);const o=await H(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const r=H(n).reCAPTCHAState;o.ready(()=>{e(o.execute(r.widgetId,{action:"fire_app_check"}))})})}class Ce{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;De(this._throttleData);var t=await Se(this._app).catch(e=>{throw V.create("recaptcha-error")});if(null===(e=H(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw V.create("recaptcha-error");let r;try{r=await G(function(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${$}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Oe(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),V.create("throttled",{time:K(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,r}initialize(e){this._app=e,this._heartbeatServiceProvider=He._getProvider(e,"heartbeat"),ke(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Ce&&this._siteKey===e._siteKey}}class Re{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;De(this._throttleData);var t=await Se(this._app).catch(e=>{throw V.create("recaptcha-error")});if(null===(e=H(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw V.create("recaptcha-error");let r;try{r=await G(function(e,t){var{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${$}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Oe(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),V.create("throttled",{time:K(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,r}initialize(e){this._app=e,this._heartbeatServiceProvider=He._getProvider(e,"heartbeat"),ye(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Re&&this._siteKey===e._siteKey}}class Pe{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=d(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof Pe&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Oe(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var r,n,o=t?t.backoffCount:0,n=(t=2,r=1e3*Math.pow(t,o),n=Math.round(v*r*(Math.random()-.5)*2),Math.min(g,r+n));return{backoffCount:o+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}function De(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw V.create("throttled",{time:K(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Ne(e=He.getApp(),t){var r;e=(r=e)&&r._delegate?r._delegate:r;const n=He._getProvider(e,"app-check");if(B.initialized||ue(),le()&&he().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var o=n.getImmediate();const a=n.getOptions();if(a.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&a.provider.isEqual(t.provider))return o;throw V.create("already-initialized",{appName:e.name})}o=n.initialize({options:t});return function(t,e,r){const n=function(e,t){return L.set(e,t),L.get(e)}(t,Object.assign({},M));n.activated=!0,n.provider=e,n.cachedTokenPromise=ie(t).then(e=>(e&&Ee(e)&&(n.token=e,we(t,{token:e.token})),e)),n.isTokenAutoRefreshEnabled=void 0===r?t.automaticDataCollectionEnabled:r,n.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),H(e).isTokenAutoRefreshEnabled&&fe(o,"INTERNAL",()=>{}),o}const Ie="app-check-internal";He._registerComponent(new w("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return t=r,e=n,new be(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(Ie).initialize()})),He._registerComponent(new w(Ie,e=>{return _e(e.getProvider("app-check").getImmediate())},"PUBLIC").setInstantiationMode("EXPLICIT")),He.registerVersion("@firebase/app-check","0.8.6-20240716220314");const xe=new h("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class Le{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new Ce(e):e instanceof Re||e instanceof Ce||e instanceof Pe?e:new Pe({getToken:e.getToken}),this._delegate=Ne(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw xe.create("use-before-activation",{appName:this.app.name});!function(e,t){const r=H(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}(this._delegate,e)}getToken(e){if(!this._delegate)throw xe.create("use-before-activation",{appName:this.app.name});return async function(e,t){var r=await de(e,t);if(r.error)throw r.error;return{token:r.token}}(this._delegate,e)}onTokenChanged(e,t,r){if(!this._delegate)throw xe.create("use-before-activation",{appName:this.app.name});return function(e,t,r){let n=()=>{},o=()=>{};return n=null!=t.next?t.next.bind(t):t,null!=t.error?o=t.error.bind(t):r&&(o=r),fe(e,"EXTERNAL",n,o),()=>ge(e.app,n)}(this._delegate,e,t)}}const Me=e=>{var t=e.getProvider("app-compat").getImmediate();return new Le(t)};n.default.INTERNAL.registerComponent(new w("appCheck-compat",Me,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Re,ReCaptchaV3Provider:Ce,CustomProvider:Pe})),n.default.registerVersion("@firebase/app-check-compat","0.3.13-20240716220314")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-app-check-compat.js - be sure to load firebase-app.js first.")}}); | ||
//# sourceMappingURL=firebase-app-check-compat.js.map |
@@ -1,3 +0,3 @@ | ||
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";const n={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],i=t+1<e.length,a=i?e[t+1]:0,s=t+2<e.length,c=s?e[t+2]:0,h=o>>2,l=(3&o)<<4|a>>4;let u=(15&a)<<2|c>>6,d=63&c;s||(d=64,i||(u=64)),n.push(r[h],r[l],r[u],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){const i=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(i>>10)),t[n++]=String.fromCharCode(56320+(1023&i))}else{const i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],i=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const s=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==i||null==a||null==s)throw new DecodeBase64StringError;const c=o<<2|i>>4;if(n.push(c),64!==a){const e=i<<4&240|a>>2;if(n.push(e),64!==s){const e=a<<6&192|s;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",s=`${this.serviceName}: ${a} (${n}).`;return new FirebaseError(n,s,r)}}const o=/\{\$([^}]+)}/g;function jsonEval(e){return JSON.parse(e)}const issuedAtTime=function(e){const t=function(e){let t={},r={},n={},o="";try{const i=e.split(".");t=jsonEval(base64Decode(i[0])||""),r=jsonEval(base64Decode(i[1])||""),o=i[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:o}}(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 i;!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"}(i||(i={}));const a={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},s=i.INFO,c={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const h=new Map,l={activated:!1,tokenObservers:[]},u={initialized:!1,enabled:!1};function getStateReference(e){return h.get(e)||Object.assign({},l)}function getDebugState(){return u}const d="https://content-firebaseappcheck.googleapis.com/v1",p=3e4,g=96e4;class Refresher{constructor(e,t,r,n,o){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=o,this.pending=null,this.nextErrorWaitInterval=n,n>o)throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch((()=>{}))}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new Deferred,this.pending.promise.catch((e=>{})),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(this.getNextRun(e)),this.pending.resolve(),await this.pending.promise,this.pending=new Deferred,this.pending.promise.catch((e=>{})),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch((()=>{}))}catch(e){this.retryPolicy(e)?this.process(!1).catch((()=>{})):this.stop()}}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();{const e=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),e}}}const f=new ErrorFactory("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","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}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function getRecaptcha(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ensureActivated(e){if(!getStateReference(e).activated)throw f.create("use-before-activation",{appName:e.name})}function getDurationString(e){const t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),i=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=pad(r)+"d:"),n&&(a+=pad(n)+"h:"),a+=pad(o)+"m:"+pad(i)+"s",a}function pad(e){return 0===e?"00":e>=10?e.toString():"0"+e}async function exchangeToken({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&(n["X-Firebase-Client"]=e)}const i={method:"POST",body:JSON.stringify(t),headers:n};let a,s;try{a=await fetch(e,i)}catch(e){throw f.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw f.create("fetch-status-error",{httpStatus:a.status});try{s=await a.json()}catch(e){throw f.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}const c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw f.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${s.ttl}`});const h=1e3*Number(c[1]),l=Date.now();return{token:s.token,expireTimeMillis:l+h,issuedAtTimeMillis:l}}function getExchangeDebugTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeDebugToken?key=${o}`,body:{debug_token:t}}}const k="firebase-app-check-store";let T=null;function getDBPromise(){return T||(T=new Promise(((e,t)=>{try{const r=indexedDB.open("firebase-app-check-database",1);r.onsuccess=t=>{e(t.target.result)},r.onerror=e=>{var r;t(f.create("storage-open",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))},r.onupgradeneeded=e=>{const t=e.target.result;if(0===e.oldVersion)t.createObjectStore(k,{keyPath:"compositeKey"})}}catch(e){t(f.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})),T)}async function write(e,t){const r=(await getDBPromise()).transaction(k,"readwrite"),n=r.objectStore(k).put({compositeKey:e,value:t});return new Promise(((e,t)=>{n.onsuccess=t=>{e()},r.onerror=e=>{var r;t(f.create("storage-set",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))}}))}async function read(e){const t=(await getDBPromise()).transaction(k,"readonly"),r=t.objectStore(k).get(e);return new Promise(((e,n)=>{r.onsuccess=t=>{const r=t.target.result;e(r?r.value:void 0)},t.onerror=e=>{var t;n(f.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}}))}function computeKey(e){return`${e.options.appId}-${e.name}`}const E=new class Logger{constructor(e){this.name=e,this._logLevel=s,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("@firebase/app-check");async function readTokenFromStorage(e){if(isIndexedDBAvailable()){let t;try{t=await function readTokenFromIndexedDB(e){return read(computeKey(e))}(e)}catch(e){E.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return t}}function writeTokenToStorage(e,t){return isIndexedDBAvailable()?function writeTokenToIndexedDB(e,t){return write(computeKey(e),t)}(e,t).catch((e=>{E.warn(`Failed to write token to IndexedDB. Error: ${e}`)})):Promise.resolve()}async function readOrCreateDebugTokenFromStorage(){let e;try{e=await function readDebugTokenFromIndexedDB(){return read("debug-token")}()}catch(e){}if(e)return e;{const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return function writeDebugTokenToIndexedDB(e){return write("debug-token",e)}(e).catch((e=>E.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`))),e}}function isDebugMode(){return getDebugState().enabled}async function getDebugToken(){const e=getDebugState();if(e.enabled&&e.token)return e.token.promise;throw Error("\n Can't get debug token in production mode.\n ")}function initializeDebugMode(){const e=function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}(),t=getDebugState();if(t.initialized=!0,"string"!=typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==e.FIREBASE_APPCHECK_DEBUG_TOKEN)return;t.enabled=!0;const r=new Deferred;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(readOrCreateDebugTokenFromStorage())}const m={error:"UNKNOWN_ERROR"};async function getToken$2(e,t=!1){const r=e.app;ensureActivated(r);const n=getStateReference(r);let o,i=n.token;if(i&&!isValid(i)&&(n.token=void 0,i=void 0),!i){const e=await n.cachedTokenPromise;e&&(isValid(e)?i=e:await writeTokenToStorage(r,void 0))}if(!t&&i&&isValid(i))return{token:i.token};let a,s=!1;if(isDebugMode()){n.exchangeTokenPromise||(n.exchangeTokenPromise=exchangeToken(getExchangeDebugTokenRequest(r,await getDebugToken()),e.heartbeatServiceProvider).finally((()=>{n.exchangeTokenPromise=void 0})),s=!0);const t=await n.exchangeTokenPromise;return await writeTokenToStorage(r,t),n.token=t,{token:t.token}}try{n.exchangeTokenPromise||(n.exchangeTokenPromise=n.provider.getToken().finally((()=>{n.exchangeTokenPromise=void 0})),s=!0),i=await getStateReference(r).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?E.warn(e.message):E.error(e),o=e}return i?o?a=isValid(i)?{token:i.token,internalError:o}:makeDummyTokenResult(o):(a={token:i.token},n.token=i,await writeTokenToStorage(r,i)):a=makeDummyTokenResult(o),s&¬ifyTokenListeners(r,a),a}async function getLimitedUseToken$1(e){const t=e.app;ensureActivated(t);const{provider:r}=getStateReference(t);if(isDebugMode()){const r=await getDebugToken(),{token:n}=await exchangeToken(getExchangeDebugTokenRequest(t,r),e.heartbeatServiceProvider);return{token:n}}{const{token:e}=await r.getToken();return{token:e}}}function addTokenListener(e,t,r,n){const{app:o}=e,i=getStateReference(o),a={next:r,error:n,type:t};if(i.tokenObservers=[...i.tokenObservers,a],i.token&&isValid(i.token)){const t=i.token;Promise.resolve().then((()=>{r({token:t.token}),initTokenRefresher(e)})).catch((()=>{}))}i.cachedTokenPromise.then((()=>initTokenRefresher(e)))}function removeTokenListener(e,t){const r=getStateReference(e),n=r.tokenObservers.filter((e=>e.next!==t));0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function initTokenRefresher(e){const{app:t}=e,r=getStateReference(t);let n=r.tokenRefresher;n||(n=function createTokenRefresher(e){const{app:t}=e;return new Refresher((async()=>{let r;if(r=getStateReference(t).token?await getToken$2(e,!0):await getToken$2(e),r.error)throw r.error;if(r.internalError)throw r.internalError}),(()=>!0),(()=>{const e=getStateReference(t);if(e.token){let t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5;const r=e.token.expireTimeMillis-3e5;return t=Math.min(t,r),Math.max(0,t-Date.now())}return 0}),p,g)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function notifyTokenListeners(e,t){const r=getStateReference(e).tokenObservers;for(const e of r)try{"EXTERNAL"===e.type&&null!=t.error?e.error(t.error):e.next(t)}catch(e){}}function isValid(e){return e.expireTimeMillis-Date.now()>0}function makeDummyTokenResult(e){return{token:(t=m,n.encodeString(JSON.stringify(t),!1)),error:e};var t}class AppCheckService{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){const{tokenObservers:e}=getStateReference(this.app);for(const t of e)removeTokenListener(this.app,t.next);return Promise.resolve()}}function initializeV3(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!1);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAV3Script(e){const t=document.createElement("script");t.src="https://www.google.com/recaptcha/api.js",t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!1);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function initializeEnterprise(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!0);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAEnterpriseScript(e){const t=document.createElement("script");t.src="https://www.google.com/recaptcha/enterprise.js",t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!0);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function queueWidgetRender(e,t,r,n,o){r.ready((()=>{!function renderInvisibleWidget(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{getStateReference(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{getStateReference(e).reCAPTCHAState.succeeded=!1}}),i=getStateReference(e);i.reCAPTCHAState=Object.assign(Object.assign({},i.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)}))}function makeDiv(e){const t=`fire_app_check_${e.name}`,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function getToken$1(e){ensureActivated(e);const t=getStateReference(e).reCAPTCHAState,r=await t.initialized.promise;return new Promise(((t,n)=>{const o=getStateReference(e).reCAPTCHAState;r.ready((()=>{t(r.execute(o.widgetId,{action:"fire_app_check"}))}))}))}class ReCaptchaV3Provider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaV3TokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("throttled",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeV3(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaV3Provider&&this._siteKey===e._siteKey}}class ReCaptchaEnterpriseProvider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw f.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw f.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaEnterpriseTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${d}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),f.create("throttled",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeEnterprise(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaEnterpriseProvider&&this._siteKey===e._siteKey}}class CustomProvider{constructor(e){this._customProviderOptions=e}async getToken(){const e=await this._customProviderOptions.getToken(),t=issuedAtTime(e.token),r=null!==t&&t<Date.now()&&t>0?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:r})}initialize(e){this._app=e}isEqual(e){return e instanceof CustomProvider&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function setBackoff(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};{const r=t?t.backoffCount:0,n=function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),o=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+o)}(r,1e3,2);return{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}}function throwIfThrottled(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw f.create("throttled",{time:getDurationString(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function initializeAppCheck(t=e(),r){t=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(t);const n=_getProvider(t,"app-check");if(getDebugState().initialized||initializeDebugMode(),isDebugMode()&&getDebugToken().then((e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`))),n.isInitialized()){const e=n.getImmediate(),o=n.getOptions();if(o.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&o.provider.isEqual(r.provider))return e;throw f.create("already-initialized",{appName:t.name})}const o=n.initialize({options:r});return function _activate(e,t,r){const n=function setInitialState(e,t){return h.set(e,t),h.get(e)}(e,Object.assign({},l));n.activated=!0,n.provider=t,n.cachedTokenPromise=readTokenFromStorage(e).then((t=>(t&&isValid(t)&&(n.token=t,notifyTokenListeners(e,{token:t.token})),t))),n.isTokenAutoRefreshEnabled=void 0===r?e.automaticDataCollectionEnabled:r,n.provider.initialize(e)}(t,r.provider,r.isTokenAutoRefreshEnabled),getStateReference(t).isTokenAutoRefreshEnabled&&addTokenListener(o,"INTERNAL",(()=>{})),o}function setTokenAutoRefreshEnabled(e,t){const r=getStateReference(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}async function getToken(e,t){const r=await getToken$2(e,t);if(r.error)throw r.error;return{token:r.token}}function getLimitedUseToken(e){return getLimitedUseToken$1(e)}function onTokenChanged(e,t,r,n){let nextFn=()=>{},errorFn=()=>{};return nextFn=null!=t.next?t.next.bind(t):t,null!=t.error?errorFn=t.error.bind(t):r&&(errorFn=r),addTokenListener(e,"EXTERNAL",nextFn,errorFn),()=>removeTokenListener(e.app,nextFn)}!function registerAppCheck(){t(new Component("app-check",(e=>function factory(e,t){return new AppCheckService(e,t)}(e.getProvider("app").getImmediate(),e.getProvider("heartbeat"))),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("app-check-internal").initialize()}))),t(new Component("app-check-internal",(e=>function internalFactory(e){return{getToken:t=>getToken$2(e,t),getLimitedUseToken:()=>getLimitedUseToken$1(e),addTokenListener:t=>addTokenListener(e,"INTERNAL",t),removeTokenListener:t=>removeTokenListener(e.app,t)}}(e.getProvider("app-check").getImmediate())),"PUBLIC").setInstantiationMode("EXPLICIT")),r("@firebase/app-check","0.8.5")}();export{CustomProvider,ReCaptchaEnterpriseProvider,ReCaptchaV3Provider,getLimitedUseToken,getToken,initializeAppCheck,onTokenChanged,setTokenAutoRefreshEnabled}; | ||
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";const n={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],i=t+1<e.length,a=i?e[t+1]:0,s=t+2<e.length,c=s?e[t+2]:0,l=o>>2,u=(3&o)<<4|a>>4;let h=(15&a)<<2|c>>6,d=63&c;s||(d=64,i||(h=64)),n.push(r[l],r[u],r[h],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){const i=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(i>>10)),t[n++]=String.fromCharCode(56320+(1023&i))}else{const i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],i=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const s=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==i||null==a||null==s)throw new DecodeBase64StringError;const c=o<<2|i>>4;if(n.push(c),64!==a){const e=i<<4&240|a>>2;if(n.push(e),64!==s){const e=a<<6&192|s;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,r))}}}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",s=`${this.serviceName}: ${a} (${n}).`;return new FirebaseError(n,s,r)}}const o=/\{\$([^}]+)}/g;function jsonEval(e){return JSON.parse(e)}const issuedAtTime=function(e){const t=function(e){let t={},r={},n={},o="";try{const i=e.split(".");t=jsonEval(base64Decode(i[0])||""),r=jsonEval(base64Decode(i[1])||""),o=i[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:o}}(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null};class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 i;!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"}(i||(i={}));const a={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},s=i.INFO,c={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${n}] ${e.name}:`,...r)};const l={};function assertIsTemplateObject(e,t){if(!function isTemplateObject(e){if(!Array.isArray(e)||!Array.isArray(e.raw))return!1;if(e.length!==e.raw.length)return!1;if(!u&&e===e.raw)return!1;if((!u||h)&&!checkFrozen(e))return!1;return!0}(e)||t+1!==e.length)throw new TypeError("\n ############################## ERROR ##############################\n\n It looks like you are trying to call a template tag function (fn`...`)\n using the normal function syntax (fn(...)), which is not supported.\n\n The functions in the safevalues library are not designed to be called\n like normal functions, and doing so invalidates the security guarantees\n that safevalues provides.\n\n If you are stuck and not sure how to proceed, please reach out to us\n instead through:\n - https://github.com/google/safevalues/issues\n\n ############################## ERROR ##############################")}function checkFrozen(e){return Object.isFrozen(e)&&Object.isFrozen(e.raw)}function checkTranspiled(e){return-1===e.toString().indexOf("`")}const u=checkTranspiled((e=>e``))||checkTranspiled((e=>e`\0`))||checkTranspiled((e=>e`\n`))||checkTranspiled((e=>e`\u0000`)),h=checkFrozen``&&checkFrozen`\0`&&checkFrozen`\n`&&checkFrozen`\u0000`;let d;function getTrustedTypes(){var e;return null!==(e=function trustedTypes(){if("undefined"!=typeof window)return window.trustedTypes}())&&void 0!==e?e:null}class ResourceUrlImpl{constructor(e,t){!function ensureTokenIsValid(e){if("production"!==process.env.NODE_ENV&&e!==l)throw new Error("Bad secret")}(t),this.privateDoNotAccessOrElseWrappedResourceUrl=e}toString(){return this.privateDoNotAccessOrElseWrappedResourceUrl.toString()}}function createResourceUrlInternal(e){var t;const r=e,n=null===(t=function getTrustedTypesPolicy(){var e,t;if(void 0===d)try{d=null!==(t=null===(e=getTrustedTypes())||void 0===e?void 0:e.createPolicy("google#safe",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))&&void 0!==t?t:null}catch(e){d=null}return d}())||void 0===t?void 0:t.createScriptURL(r);return null!=n?n:new ResourceUrlImpl(r,l)}function trustedResourceUrl(e,...t){if("production"!==process.env.NODE_ENV&&assertIsTemplateObject(e,t.length),0===t.length)return createResourceUrlInternal(e[0]);const r=e[0].toLowerCase();if("production"!==process.env.NODE_ENV){if(/^data:/.test(r))throw new Error("Data URLs cannot have expressions in the template literal input.");if(!(function hasValidOrigin(e){if(!/^https:\/\//.test(e)&&!/^\/\//.test(e))return!1;const t=e.indexOf("//")+2,r=e.indexOf("/",t);if(r<=t)throw new Error("Can't interpolate data in a url's origin, Please make sure to fully specify the origin, terminated with '/'.");const n=e.substring(t,r);if(!/^[0-9a-z.:-]+$/i.test(n))throw new Error("The origin contains unsupported characters.");if(!/^[^:]*(:[0-9]+)?$/i.test(n))throw new Error("Invalid port number.");if(!/(^|\.)[a-z][^.]*$/i.test(n))throw new Error("The top-level domain must start with a letter.");return!0}(r)||function isValidPathStart(e){if(!/^\//.test(e))return!1;if("/"===e||e.length>1&&"/"!==e[1]&&"\\"!==e[1])return!0;throw new Error("The path start in the url is invalid.")}(r)||function isValidRelativePathStart(e){return new RegExp("^[^:\\s\\\\/]+/").test(e)}(r)||function isValidAboutUrl(e){if(!/^about:blank/.test(e))return!1;if("about:blank"!==e&&!/^about:blank#/.test(e))throw new Error("The about url is invalid.");return!0}(r)))throw new Error("Trying to interpolate expressions in an unsupported url format.")}let n=e[0];for(let r=0;r<t.length;r++)n+=encodeURIComponent(t[r])+e[r+1];return createResourceUrlInternal(n)}function setSrc(e,t,r){e.src=function unwrapResourceUrl(e){var t;if(null===(t=getTrustedTypes())||void 0===t?void 0:t.isScriptURL(e))return e;if(e instanceof ResourceUrlImpl)return e.privateDoNotAccessOrElseWrappedResourceUrl;{let e="";throw"production"!==process.env.NODE_ENV&&(e="Unexpected type when unwrapping TrustedResourceUrl"),new Error(e)}}(t),(null==r?void 0:r.omitNonce)||function setNonceForScriptElement(e){const t=function getScriptNonce(e){return function getNonceFor(e,t){var r;const n=t.document,o=null===(r=n.querySelector)||void 0===r?void 0:r.call(n,`${e}[nonce]`);return o&&(o.nonce||o.getAttribute("nonce"))||""}("script",e)}(e.ownerDocument&&e.ownerDocument.defaultView||window);t&&e.setAttribute("nonce",t)}(e)}const p=new Map,g={activated:!1,tokenObservers:[]},f={initialized:!1,enabled:!1};function getStateReference(e){return p.get(e)||Object.assign({},g)}function getDebugState(){return f}const k="https://content-firebaseappcheck.googleapis.com/v1",T=3e4,w=96e4;class Refresher{constructor(e,t,r,n,o){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=o,this.pending=null,this.nextErrorWaitInterval=n,n>o)throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch((()=>{}))}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new Deferred,this.pending.promise.catch((e=>{})),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(this.getNextRun(e)),this.pending.resolve(),await this.pending.promise,this.pending=new Deferred,this.pending.promise.catch((e=>{})),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch((()=>{}))}catch(e){this.retryPolicy(e)?this.process(!1).catch((()=>{})):this.stop()}}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();{const e=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),e}}}const E=new ErrorFactory("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","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}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function getRecaptcha(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ensureActivated(e){if(!getStateReference(e).activated)throw E.create("use-before-activation",{appName:e.name})}function getDurationString(e){const t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),o=Math.floor((t-3600*r*24-3600*n)/60),i=t-3600*r*24-3600*n-60*o;let a="";return r&&(a+=pad(r)+"d:"),n&&(a+=pad(n)+"h:"),a+=pad(o)+"m:"+pad(i)+"s",a}function pad(e){return 0===e?"00":e>=10?e.toString():"0"+e}async function exchangeToken({url:e,body:t},r){const n={"Content-Type":"application/json"},o=r.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&(n["X-Firebase-Client"]=e)}const i={method:"POST",body:JSON.stringify(t),headers:n};let a,s;try{a=await fetch(e,i)}catch(e){throw E.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw E.create("fetch-status-error",{httpStatus:a.status});try{s=await a.json()}catch(e){throw E.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}const c=s.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw E.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${s.ttl}`});const l=1e3*Number(c[1]),u=Date.now();return{token:s.token,expireTimeMillis:u+l,issuedAtTimeMillis:u}}function getExchangeDebugTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${k}/projects/${r}/apps/${n}:exchangeDebugToken?key=${o}`,body:{debug_token:t}}}const v="firebase-app-check-store";let m=null;function getDBPromise(){return m||(m=new Promise(((e,t)=>{try{const r=indexedDB.open("firebase-app-check-database",1);r.onsuccess=t=>{e(t.target.result)},r.onerror=e=>{var r;t(E.create("storage-open",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))},r.onupgradeneeded=e=>{const t=e.target.result;if(0===e.oldVersion)t.createObjectStore(v,{keyPath:"compositeKey"})}}catch(e){t(E.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})),m)}async function write(e,t){const r=(await getDBPromise()).transaction(v,"readwrite"),n=r.objectStore(v).put({compositeKey:e,value:t});return new Promise(((e,t)=>{n.onsuccess=t=>{e()},r.onerror=e=>{var r;t(E.create("storage-set",{originalErrorMessage:null===(r=e.target.error)||void 0===r?void 0:r.message}))}}))}async function read(e){const t=(await getDBPromise()).transaction(v,"readonly"),r=t.objectStore(v).get(e);return new Promise(((e,n)=>{r.onsuccess=t=>{const r=t.target.result;e(r?r.value:void 0)},t.onerror=e=>{var t;n(E.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}}))}function computeKey(e){return`${e.options.appId}-${e.name}`}const b=new class Logger{constructor(e){this.name=e,this._logLevel=s,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("@firebase/app-check");async function readTokenFromStorage(e){if(isIndexedDBAvailable()){let t;try{t=await function readTokenFromIndexedDB(e){return read(computeKey(e))}(e)}catch(e){b.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return t}}function writeTokenToStorage(e,t){return isIndexedDBAvailable()?function writeTokenToIndexedDB(e,t){return write(computeKey(e),t)}(e,t).catch((e=>{b.warn(`Failed to write token to IndexedDB. Error: ${e}`)})):Promise.resolve()}async function readOrCreateDebugTokenFromStorage(){let e;try{e=await function readDebugTokenFromIndexedDB(){return read("debug-token")}()}catch(e){}if(e)return e;{const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return function writeDebugTokenToIndexedDB(e){return write("debug-token",e)}(e).catch((e=>b.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`))),e}}function isDebugMode(){return getDebugState().enabled}async function getDebugToken(){const e=getDebugState();if(e.enabled&&e.token)return e.token.promise;throw Error("\n Can't get debug token in production mode.\n ")}function initializeDebugMode(){const e=function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}(),t=getDebugState();if(t.initialized=!0,"string"!=typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==e.FIREBASE_APPCHECK_DEBUG_TOKEN)return;t.enabled=!0;const r=new Deferred;t.token=r,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?r.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):r.resolve(readOrCreateDebugTokenFromStorage())}const y={error:"UNKNOWN_ERROR"};async function getToken$2(e,t=!1){const r=e.app;ensureActivated(r);const n=getStateReference(r);let o,i=n.token;if(i&&!isValid(i)&&(n.token=void 0,i=void 0),!i){const e=await n.cachedTokenPromise;e&&(isValid(e)?i=e:await writeTokenToStorage(r,void 0))}if(!t&&i&&isValid(i))return{token:i.token};let a,s=!1;if(isDebugMode()){n.exchangeTokenPromise||(n.exchangeTokenPromise=exchangeToken(getExchangeDebugTokenRequest(r,await getDebugToken()),e.heartbeatServiceProvider).finally((()=>{n.exchangeTokenPromise=void 0})),s=!0);const t=await n.exchangeTokenPromise;return await writeTokenToStorage(r,t),n.token=t,{token:t.token}}try{n.exchangeTokenPromise||(n.exchangeTokenPromise=n.provider.getToken().finally((()=>{n.exchangeTokenPromise=void 0})),s=!0),i=await getStateReference(r).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?b.warn(e.message):b.error(e),o=e}return i?o?a=isValid(i)?{token:i.token,internalError:o}:makeDummyTokenResult(o):(a={token:i.token},n.token=i,await writeTokenToStorage(r,i)):a=makeDummyTokenResult(o),s&¬ifyTokenListeners(r,a),a}async function getLimitedUseToken$1(e){const t=e.app;ensureActivated(t);const{provider:r}=getStateReference(t);if(isDebugMode()){const r=await getDebugToken(),{token:n}=await exchangeToken(getExchangeDebugTokenRequest(t,r),e.heartbeatServiceProvider);return{token:n}}{const{token:e}=await r.getToken();return{token:e}}}function addTokenListener(e,t,r,n){const{app:o}=e,i=getStateReference(o),a={next:r,error:n,type:t};if(i.tokenObservers=[...i.tokenObservers,a],i.token&&isValid(i.token)){const t=i.token;Promise.resolve().then((()=>{r({token:t.token}),initTokenRefresher(e)})).catch((()=>{}))}i.cachedTokenPromise.then((()=>initTokenRefresher(e)))}function removeTokenListener(e,t){const r=getStateReference(e),n=r.tokenObservers.filter((e=>e.next!==t));0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function initTokenRefresher(e){const{app:t}=e,r=getStateReference(t);let n=r.tokenRefresher;n||(n=function createTokenRefresher(e){const{app:t}=e;return new Refresher((async()=>{let r;if(r=getStateReference(t).token?await getToken$2(e,!0):await getToken$2(e),r.error)throw r.error;if(r.internalError)throw r.internalError}),(()=>!0),(()=>{const e=getStateReference(t);if(e.token){let t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5;const r=e.token.expireTimeMillis-3e5;return t=Math.min(t,r),Math.max(0,t-Date.now())}return 0}),T,w)}(e),r.tokenRefresher=n),!n.isRunning()&&r.isTokenAutoRefreshEnabled&&n.start()}function notifyTokenListeners(e,t){const r=getStateReference(e).tokenObservers;for(const e of r)try{"EXTERNAL"===e.type&&null!=t.error?e.error(t.error):e.next(t)}catch(e){}}function isValid(e){return e.expireTimeMillis-Date.now()>0}function makeDummyTokenResult(e){return{token:(t=y,n.encodeString(JSON.stringify(t),!1)),error:e};var t}class AppCheckService{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){const{tokenObservers:e}=getStateReference(this.app);for(const t of e)removeTokenListener(this.app,t.next);return Promise.resolve()}}function initializeV3(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!1);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAV3Script(e){const t=document.createElement("script");setSrc(t,trustedResourceUrl`https://www.google.com/recaptcha/api.js`),t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!1);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function initializeEnterprise(e,t){const r=new Deferred;getStateReference(e).reCAPTCHAState={initialized:r};const n=makeDiv(e),o=getRecaptcha(!0);return o?queueWidgetRender(e,t,o,n,r):function loadReCAPTCHAEnterpriseScript(e){const t=document.createElement("script");setSrc(t,trustedResourceUrl`https://www.google.com/recaptcha/enterprise.js`),t.onload=e,document.head.appendChild(t)}((()=>{const o=getRecaptcha(!0);if(!o)throw new Error("no recaptcha");queueWidgetRender(e,t,o,n,r)})),r.promise}function queueWidgetRender(e,t,r,n,o){r.ready((()=>{!function renderInvisibleWidget(e,t,r,n){const o=r.render(n,{sitekey:t,size:"invisible",callback:()=>{getStateReference(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{getStateReference(e).reCAPTCHAState.succeeded=!1}}),i=getStateReference(e);i.reCAPTCHAState=Object.assign(Object.assign({},i.reCAPTCHAState),{widgetId:o})}(e,t,r,n),o.resolve(r)}))}function makeDiv(e){const t=`fire_app_check_${e.name}`,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function getToken$1(e){ensureActivated(e);const t=getStateReference(e).reCAPTCHAState,r=await t.initialized.promise;return new Promise(((t,n)=>{const o=getStateReference(e).reCAPTCHAState;r.ready((()=>{t(r.execute(o.widgetId,{action:"fire_app_check"}))}))}))}class ReCaptchaV3Provider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw E.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw E.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaV3TokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${k}/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=${o}`,body:{recaptcha_v3_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),E.create("throttled",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeV3(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaV3Provider&&this._siteKey===e._siteKey}}class ReCaptchaEnterpriseProvider{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e,t,r;throwIfThrottled(this._throttleData);const n=await getToken$1(this._app).catch((e=>{throw E.create("recaptcha-error")}));if(!(null===(e=getStateReference(this._app).reCAPTCHAState)||void 0===e?void 0:e.succeeded))throw E.create("recaptcha-error");let o;try{o=await exchangeToken(function getExchangeRecaptchaEnterpriseTokenRequest(e,t){const{projectId:r,appId:n,apiKey:o}=e.options;return{url:`${k}/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=${o}`,body:{recaptcha_enterprise_token:t}}}(this._app,n),this._heartbeatServiceProvider)}catch(e){throw(null===(t=e.code)||void 0===t?void 0:t.includes("fetch-status-error"))?(this._throttleData=setBackoff(Number(null===(r=e.customData)||void 0===r?void 0:r.httpStatus),this._throttleData),E.create("throttled",{time:getDurationString(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,o}initialize(e){this._app=e,this._heartbeatServiceProvider=_getProvider(e,"heartbeat"),initializeEnterprise(e,this._siteKey).catch((()=>{}))}isEqual(e){return e instanceof ReCaptchaEnterpriseProvider&&this._siteKey===e._siteKey}}class CustomProvider{constructor(e){this._customProviderOptions=e}async getToken(){const e=await this._customProviderOptions.getToken(),t=issuedAtTime(e.token),r=null!==t&&t<Date.now()&&t>0?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:r})}initialize(e){this._app=e}isEqual(e){return e instanceof CustomProvider&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function setBackoff(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};{const r=t?t.backoffCount:0,n=function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),o=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+o)}(r,1e3,2);return{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e}}}function throwIfThrottled(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw E.create("throttled",{time:getDurationString(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function initializeAppCheck(t=e(),r){t=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(t);const n=_getProvider(t,"app-check");if(getDebugState().initialized||initializeDebugMode(),isDebugMode()&&getDebugToken().then((e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`))),n.isInitialized()){const e=n.getImmediate(),o=n.getOptions();if(o.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&o.provider.isEqual(r.provider))return e;throw E.create("already-initialized",{appName:t.name})}const o=n.initialize({options:r});return function _activate(e,t,r){const n=function setInitialState(e,t){return p.set(e,t),p.get(e)}(e,Object.assign({},g));n.activated=!0,n.provider=t,n.cachedTokenPromise=readTokenFromStorage(e).then((t=>(t&&isValid(t)&&(n.token=t,notifyTokenListeners(e,{token:t.token})),t))),n.isTokenAutoRefreshEnabled=void 0===r?e.automaticDataCollectionEnabled:r,n.provider.initialize(e)}(t,r.provider,r.isTokenAutoRefreshEnabled),getStateReference(t).isTokenAutoRefreshEnabled&&addTokenListener(o,"INTERNAL",(()=>{})),o}function setTokenAutoRefreshEnabled(e,t){const r=getStateReference(e.app);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=t}async function getToken(e,t){const r=await getToken$2(e,t);if(r.error)throw r.error;return{token:r.token}}function getLimitedUseToken(e){return getLimitedUseToken$1(e)}function onTokenChanged(e,t,r,n){let nextFn=()=>{},errorFn=()=>{};return nextFn=null!=t.next?t.next.bind(t):t,null!=t.error?errorFn=t.error.bind(t):r&&(errorFn=r),addTokenListener(e,"EXTERNAL",nextFn,errorFn),()=>removeTokenListener(e.app,nextFn)}!function registerAppCheck(){t(new Component("app-check",(e=>function factory(e,t){return new AppCheckService(e,t)}(e.getProvider("app").getImmediate(),e.getProvider("heartbeat"))),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,r)=>{e.getProvider("app-check-internal").initialize()}))),t(new Component("app-check-internal",(e=>function internalFactory(e){return{getToken:t=>getToken$2(e,t),getLimitedUseToken:()=>getLimitedUseToken$1(e),addTokenListener:t=>addTokenListener(e,"INTERNAL",t),removeTokenListener:t=>removeTokenListener(e.app,t)}}(e.getProvider("app-check").getImmediate())),"PUBLIC").setInstantiationMode("EXPLICIT")),r("@firebase/app-check","0.8.6-20240716220314")}();export{CustomProvider,ReCaptchaEnterpriseProvider,ReCaptchaV3Provider,getLimitedUseToken,getToken,initializeAppCheck,onTokenChanged,setTokenAutoRefreshEnabled}; | ||
//# sourceMappingURL=firebase-app-check.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";const r=function(t){const r=[];let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},n={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let h=0;h<r.length;h+=3){var a=r[h],s=h+1<r.length,o=s?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,s||(e=64)),i.push(n[a>>2],n[(3&a)<<4|o>>4],n[e],n[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){var i,a,s=e[r++];s<128?t[n++]=String.fromCharCode(s):191<s&&s<224?(i=e[r++],t[n++]=String.fromCharCode((31&s)<<6|63&i)):239<s&&s<365?(a=((7&s)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t[n++]=String.fromCharCode(55296+(a>>10)),t[n++]=String.fromCharCode(56320+(1023&a))):(i=e[r++],a=e[r++],t[n++]=String.fromCharCode((15&s)<<12|(63&i)<<6|63&a))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_;const n=[];for(let c=0;c<e.length;){var i=r[e.charAt(c++)],a=c<e.length?r[e.charAt(c)]:0;++c;var s=c<e.length?r[e.charAt(c)]:64;++c;var o=c<e.length?r[e.charAt(c)]:64;if(++c,null==i||null==a||null==s||null==o)throw new l;n.push(i<<2|a>>4),64!==s&&(n.push(a<<4&240|s>>2),64!==o&&n.push(s<<6&192|o))}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const i=function(e){return e=e,t=r(e),n.encodeByteArray(t,!0).replace(/\./g,"");var t};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const r=t;return new Date(r.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=c(e[n],t[n]));return e}const e=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,t=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},a=()=>{try{return e()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||t()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},h=()=>{var e;return null===(e=a())||void 0===e?void 0:e.config};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function d(){return"undefined"!=typeof window||u()}function u(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class o extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,p.prototype.create)}}class p{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},i=`${this.service}/${e}`,a=this.errors[e],a=a?(n=r,a.replace(f,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",a=`${this.serviceName}: ${a} (${i}).`;return new o(i,a,r)}}const f=/\{\$([^}]+)}/g;function g(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function b(e,t){if(e===t)return 1;const r=Object.keys(e),n=Object.keys(t);for(const s of r){if(!n.includes(s))return;var i=e[s],a=t[s];if(m(i)&&m(a)){if(!b(i,a))return}else if(i!==a)return}for(const o of n)if(!r.includes(o))return;return 1}function m(e){return null!==e&&"object"==typeof e}function v(e,t){const r=new _(e,t);return r.subscribe.bind(r)}class _{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");n=function(e,t){if("object"!=typeof e||null===e)return!1;for(const r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=y),void 0===n.error&&(n.error=y),void 0===n.complete&&(n.complete=y);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function y(){}class E{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}const w="[DEFAULT]";class C{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const n=new s;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(r=null==e?void 0:e.optional)&&void 0!==r&&r;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:w})}catch(e){}for(var[t,r]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var n=this.getOrInitializeService({instanceIdentifier:t});r.resolve(n)}catch(e){}}}}clearInstance(e=w){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=w){return this.instances.has(e)}getOptions(e=w){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var n,i,a=this.getOrInitializeService({instanceIdentifier:r,options:t});for([n,i]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(n)&&i.resolve(a);return a}onInit(e,t){var r=this.normalizeInstanceIdentifier(t);const n=null!==(i=this.onInitCallbacks.get(r))&&void 0!==i?i:new Set;n.add(e),this.onInitCallbacks.set(r,n);var i=this.instances.get(r);return i&&e(i,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){var r=this.onInitCallbacks.get(t);if(r)for(const n of r)try{n(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===w?void 0:n,options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch(e){}var n;return r||null}normalizeInstanceIdentifier(e=w){return!this.component||this.component.multipleInstances?e:w}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class D{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new C(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const I=[];var S,O,A;(O=S=S||{})[O.DEBUG=0]="DEBUG",O[O.VERBOSE=1]="VERBOSE",O[O.INFO=2]="INFO",O[O.WARN=3]="WARN",O[O.ERROR=4]="ERROR",O[O.SILENT=5]="SILENT";const L={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},N=S.INFO,B={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},T=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=B[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class R{constructor(e){this.name=e,this._logLevel=N,this._logHandler=T,this._userLogHandler=null,I.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in S))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?L[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,S.DEBUG,...e),this._logHandler(this,S.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,S.VERBOSE,...e),this._logHandler(this,S.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,S.INFO,...e),this._logHandler(this,S.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,S.WARN,...e),this._logHandler(this,S.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,S.ERROR,...e),this._logHandler(this,S.ERROR,...e)}}const P=(t,e)=>e.some(e=>t instanceof e);let k,M;const F=new WeakMap,j=new WeakMap,z=new WeakMap,$=new WeakMap,H=new WeakMap;let x={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return j.get(e);if("objectStoreNames"===t)return e.objectStoreNames||z.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return U(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function V(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(M=M||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(G(this),e),U(F.get(this))}:function(...e){return U(n.apply(G(this),e))}:function(e,...t){var r=n.call(G(this),e,...t);return z.set(r,e.sort?e.sort():[e]),U(r)}}function W(e){return"function"==typeof e?V(e):(e instanceof IDBTransaction&&(a=e,j.has(a)||(t=new Promise((e,t)=>{const r=()=>{a.removeEventListener("complete",n),a.removeEventListener("error",i),a.removeEventListener("abort",i)},n=()=>{e(),r()},i=()=>{t(a.error||new DOMException("AbortError","AbortError")),r()};a.addEventListener("complete",n),a.addEventListener("error",i),a.addEventListener("abort",i)}),j.set(a,t))),P(e,k=k||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,x):e);var a,t}function U(e){if(e instanceof IDBRequest)return function(a){const e=new Promise((e,t)=>{const r=()=>{a.removeEventListener("success",n),a.removeEventListener("error",i)},n=()=>{e(U(a.result)),r()},i=()=>{t(a.error),r()};a.addEventListener("success",n),a.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&F.set(e,a)}).catch(()=>{}),H.set(e,a),e}(e);if($.has(e))return $.get(e);var t=W(e);return t!==e&&($.set(e,t),H.set(t,e)),t}const G=e=>H.get(e);const J=["get","getKey","getAll","getAllKeys","count"],K=["put","add","delete","clear"],Y=new Map;function X(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Y.get(t))return Y.get(t);const i=t.replace(/FromIndex$/,""),a=t!==i,s=K.includes(i);if(i in(a?IDBIndex:IDBObjectStore).prototype&&(s||J.includes(i))){var r=async function(e,...t){var r=this.transaction(e,s?"readwrite":"readonly");let n=r.store;return a&&(n=n.index(t.shift())),(await Promise.all([n[i](...t),s&&r.done]))[0]};return Y.set(t,r),r}}}x={...A=x,get:(e,t,r)=>X(e,t)||A.get(e,t,r),has:(e,t)=>!!X(e,t)||A.has(e,t)};class q{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Z="@firebase/app",Q="0.10.6",ee=new R("@firebase/app");var te;const re="[DEFAULT]",ne={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},ie=new Map,ae=new Map,se=new Map;function oe(t,r){try{t.container.addComponent(r)}catch(e){ee.debug(`Component ${r.name} failed to register with FirebaseApp ${t.name}`,e)}}function ce(e,t){e.container.addOrOverwriteComponent(t)}function le(e){var t=e.name;if(se.has(t))return ee.debug(`There were multiple attempts to register component ${t}.`),!1;se.set(t,e);for(const r of ie.values())oe(r,e);for(const n of ae.values())oe(n,e);return!0}function he(e,t){const r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function de(e){return void 0!==e.options}const ue=new p("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class pe{constructor(e,t,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new E("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw ue.create("app-deleted",{appName:this._name})}}class fe extends pe{constructor(e,t,r,n){var i=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,a={name:r,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,a,n):super(e.options,a,n),this._serverConfig=Object.assign({automaticDataCollectionEnabled:i},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,ve(Z,Q,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){me(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw ue.create("server-app-deleted")}}const ge="10.12.3";function be(e,t={}){let r=e;if("object"!=typeof t){const i=t;t={name:i}}var n=Object.assign({name:re,automaticDataCollectionEnabled:!1},t);const i=n.name;if("string"!=typeof i||!i)throw ue.create("bad-app-name",{appName:String(i)});if(r=r||h(),!r)throw ue.create("no-options");var a=ie.get(i);if(a){if(b(r,a.options)&&b(n,a.config))return a;throw ue.create("duplicate-app",{appName:i})}const s=new D(i);for(const o of se.values())s.addComponent(o);n=new pe(r,n,s);return ie.set(i,n),n}async function me(e){let t=!1;var r=e.name;if(ie.has(r))t=!0,ie.delete(r);else if(ae.has(r)){const n=e;n.decRefCount()<=0&&(ae.delete(r),t=!0)}t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function ve(e,t,r){let n=null!==(a=ne[e])&&void 0!==a?a:e;r&&(n+=`-${r}`);var i=n.match(/\s|\//),a=t.match(/\s|\//);if(i||a){const s=[`Unable to register library "${n}" with version "${t}":`];return i&&s.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&a&&s.push("and"),a&&s.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ee.warn(s.join(" "))}le(new E(`${n}-version`,()=>({library:n,version:t}),"VERSION"))}function _e(e,t){if(null!==e&&"function"!=typeof e)throw ue.create("invalid-log-argument");!function(a,e){for(const t of I){let i=null;e&&e.level&&(i=L[e.level]),t.userLogHandler=null===a?null:(e,t,...r)=>{var n=r.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(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&a({level:S[t].toLowerCase(),message:n,args:r,type:e.name})}}}(e,t)}function ye(e){var t;t=e,I.forEach(e=>{e.setLogLevel(t)})}const Ee="firebase-heartbeat-database",we=1,Ce="firebase-heartbeat-store";let De=null;function Ie(){return De=De||function(e,t,{blocked:r,upgrade:n,blocking:i,terminated:a}){const s=indexedDB.open(e,t),o=U(s);return n&&s.addEventListener("upgradeneeded",e=>{n(U(s.result),e.oldVersion,e.newVersion,U(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),o.then(e=>{a&&e.addEventListener("close",()=>a()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}(Ee,we,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Ce)}catch(e){console.warn(e)}}}).catch(e=>{throw ue.create("idb-open",{originalErrorMessage:e.message})}),De}async function Se(e,t){try{const n=await Ie(),i=n.transaction(Ce,"readwrite"),a=i.objectStore(Ce);await a.put(t,Oe(e)),await i.done}catch(e){var r;e instanceof o?ee.warn(e.message):(r=ue.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),ee.warn(r.message))}}function Oe(e){return`${e.name}!${e.options.appId}`}class Ae{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Ne(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){var e;const t=this.container.getProvider("platform-logger").getImmediate();var r=t.getPlatformInfoString();const n=Le();if((null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)))&&this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:r}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(r=this._heartbeatsCache)||void 0===r?void 0:r.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";var e=Le(),{heartbeatsToSend:t,unsentEntries:r}=function(e,t=1024){const r=[];let n=e.slice();for(const i of e){const a=r.find(e=>e.agent===i.agent);if(a){if(a.dates.push(i.date),Be(r)>t){a.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Be(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}(this._heartbeatsCache.heartbeats),t=i(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function Le(){const e=new Date;return e.toISOString().substring(0,10)}class Ne{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function(){try{return"object"==typeof indexedDB}catch(e){return}}()&&new Promise((t,r)=>{try{let e=!0;const n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(n),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;r((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){r(e)}}).then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){var e=await async function(e){try{const r=await Ie(),n=r.transaction(Ce);var t=await n.objectStore(Ce).get(Oe(e));return await n.done,t}catch(e){e instanceof o?ee.warn(e.message):(t=ue.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),ee.warn(t.message))}}(this.app);return null!=e&&e.heartbeats?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var r=await this.read();return Se(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var r=await this.read();return Se(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}}}function Be(e){return i(JSON.stringify({version:2,heartbeats:e})).length}te="",le(new E("platform-logger",e=>new q(e),"PRIVATE")),le(new E("heartbeat",e=>new Ae(e),"PRIVATE")),ve(Z,Q,te),ve(Z,Q,"esm2017"),ve("fire-js","");var Te=Object.freeze({__proto__:null,SDK_VERSION:ge,_DEFAULT_ENTRY_NAME:re,_addComponent:oe,_addOrOverwriteComponent:ce,_apps:ie,_clearComponents:function(){se.clear()},_components:se,_getProvider:he,_isFirebaseApp:de,_isFirebaseServerApp:function(e){return void 0!==e.settings},_registerComponent:le,_removeServiceInstance:function(e,t,r=re){he(e,t).clearInstance(r)},_serverApps:ae,deleteApp:me,getApp:function(e=re){var t=ie.get(e);if(!t&&e===re&&h())return be();if(!t)throw ue.create("no-app",{appName:e});return t},getApps:function(){return Array.from(ie.values())},initializeApp:be,initializeServerApp:function(e,t){if(d()&&!u())throw ue.create("invalid-server-app-environment");void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1);let r;r=de(e)?e.options:e;const n=Object.assign(Object.assign({},t),r);if(void 0!==n.releaseOnDeref&&delete n.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw ue.create("finalization-registry-not-supported",{});var i=""+[...JSON.stringify(n)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0);const a=ae.get(i);if(a)return a.incRefCount(t.releaseOnDeref),a;const s=new D(i);for(const c of se.values())s.addComponent(c);var o=new fe(r,t,i,s);return ae.set(i,o),o},onLog:_e,registerVersion:ve,setLogLevel:ye,FirebaseError:o});class Re{constructor(e,t){this._delegate=e,this.firebase=t,oe(e,new E("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),me(this._delegate)))}_getService(e,t=re){var r;this._delegate.checkDestroyed();const n=this._delegate.container.getProvider(e);return n.isInitialized()||"EXPLICIT"!==(null===(r=n.getComponent())||void 0===r?void 0:r.instantiationMode)||n.initialize(),n.getImmediate({identifier:t})}_removeServiceInstance(e,t=re){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){oe(this._delegate,e)}_addOrOverwriteComponent(e){ce(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Pe=new p("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function ke(i){const a={},s={__esModule:!0,initializeApp:function(e,t={}){var r=be(e,t);if(g(a,r.name))return a[r.name];var n=new i(r,s);return a[r.name]=n},app:o,registerVersion:ve,setLogLevel:ye,onLog:_e,apps:null,SDK_VERSION:ge,INTERNAL:{registerComponent:function(r){const n=r.name,t=n.replace("-compat","");{var e;le(r)&&"PUBLIC"===r.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw Pe.create("invalid-app-argument",{appName:n});return e[t]()},void 0!==r.serviceProps&&c(e,r.serviceProps),s[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,n);return t.apply(this,r.multipleInstances?e:[])})}return"PUBLIC"===r.type?s[t]:null},removeApp:function(e){delete a[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var r=t;return r},modularAPIs:Te}};function o(e){if(e=e||re,!g(a,e))throw Pe.create("no-app",{appName:e});return a[e]}return s.default=s,Object.defineProperty(s,"apps",{get:function(){return Object.keys(a).map(e=>a[e])}}),o.App=i,s}var Me=function e(){const t=ke(Re);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:v,ErrorFactory:p,deepExtend:c}),t}();const Fe=new R("@firebase/app-compat");if(d()&&void 0!==self.firebase){Fe.warn(` | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";const r=function(t){const r=[];let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},n={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let h=0;h<r.length;h+=3){var a=r[h],s=h+1<r.length,o=s?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,s||(e=64)),i.push(n[a>>2],n[(3&a)<<4|o>>4],n[e],n[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){var i,a,s=e[r++];s<128?t[n++]=String.fromCharCode(s):191<s&&s<224?(i=e[r++],t[n++]=String.fromCharCode((31&s)<<6|63&i)):239<s&&s<365?(a=((7&s)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t[n++]=String.fromCharCode(55296+(a>>10)),t[n++]=String.fromCharCode(56320+(1023&a))):(i=e[r++],a=e[r++],t[n++]=String.fromCharCode((15&s)<<12|(63&i)<<6|63&a))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_;const n=[];for(let c=0;c<e.length;){var i=r[e.charAt(c++)],a=c<e.length?r[e.charAt(c)]:0;++c;var s=c<e.length?r[e.charAt(c)]:64;++c;var o=c<e.length?r[e.charAt(c)]:64;if(++c,null==i||null==a||null==s||null==o)throw new l;n.push(i<<2|a>>4),64!==s&&(n.push(a<<4&240|s>>2),64!==o&&n.push(s<<6&192|o))}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const i=function(e){return e=e,t=r(e),n.encodeByteArray(t,!0).replace(/\./g,"");var t};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const r=t;return new Date(r.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=c(e[n],t[n]));return e}const e=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,t=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return n.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},a=()=>{try{return e()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||t()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},h=()=>{var e;return null===(e=a())||void 0===e?void 0:e.config};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function d(){return"undefined"!=typeof window||u()}function u(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class o extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,p.prototype.create)}}class p{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},i=`${this.service}/${e}`,a=this.errors[e],a=a?(n=r,a.replace(f,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",a=`${this.serviceName}: ${a} (${i}).`;return new o(i,a,r)}}const f=/\{\$([^}]+)}/g;function g(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function b(e,t){if(e===t)return 1;const r=Object.keys(e),n=Object.keys(t);for(const s of r){if(!n.includes(s))return;var i=e[s],a=t[s];if(m(i)&&m(a)){if(!b(i,a))return}else if(i!==a)return}for(const o of n)if(!r.includes(o))return;return 1}function m(e){return null!==e&&"object"==typeof e}function v(e,t){const r=new _(e,t);return r.subscribe.bind(r)}class _{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");n=function(e,t){if("object"!=typeof e||null===e)return!1;for(const r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=y),void 0===n.error&&(n.error=y),void 0===n.complete&&(n.complete=y);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function y(){}class E{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}const w="[DEFAULT]";class C{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const n=new s;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(r=null==e?void 0:e.optional)&&void 0!==r&&r;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:w})}catch(e){}for(var[t,r]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var n=this.getOrInitializeService({instanceIdentifier:t});r.resolve(n)}catch(e){}}}}clearInstance(e=w){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=w){return this.instances.has(e)}getOptions(e=w){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var n,i,a=this.getOrInitializeService({instanceIdentifier:r,options:t});for([n,i]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(n)&&i.resolve(a);return a}onInit(e,t){var r=this.normalizeInstanceIdentifier(t);const n=null!==(i=this.onInitCallbacks.get(r))&&void 0!==i?i:new Set;n.add(e),this.onInitCallbacks.set(r,n);var i=this.instances.get(r);return i&&e(i,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){var r=this.onInitCallbacks.get(t);if(r)for(const n of r)try{n(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===w?void 0:n,options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch(e){}var n;return r||null}normalizeInstanceIdentifier(e=w){return!this.component||this.component.multipleInstances?e:w}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class D{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new C(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const I=[];var S,O,A;(O=S=S||{})[O.DEBUG=0]="DEBUG",O[O.VERBOSE=1]="VERBOSE",O[O.INFO=2]="INFO",O[O.WARN=3]="WARN",O[O.ERROR=4]="ERROR",O[O.SILENT=5]="SILENT";const L={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},N=S.INFO,B={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},T=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=B[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class R{constructor(e){this.name=e,this._logLevel=N,this._logHandler=T,this._userLogHandler=null,I.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in S))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?L[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,S.DEBUG,...e),this._logHandler(this,S.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,S.VERBOSE,...e),this._logHandler(this,S.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,S.INFO,...e),this._logHandler(this,S.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,S.WARN,...e),this._logHandler(this,S.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,S.ERROR,...e),this._logHandler(this,S.ERROR,...e)}}const P=(t,e)=>e.some(e=>t instanceof e);let k,M;const F=new WeakMap,j=new WeakMap,z=new WeakMap,$=new WeakMap,H=new WeakMap;let x={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return j.get(e);if("objectStoreNames"===t)return e.objectStoreNames||z.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return U(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function V(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(M=M||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(G(this),e),U(F.get(this))}:function(...e){return U(n.apply(G(this),e))}:function(e,...t){var r=n.call(G(this),e,...t);return z.set(r,e.sort?e.sort():[e]),U(r)}}function W(e){return"function"==typeof e?V(e):(e instanceof IDBTransaction&&(a=e,j.has(a)||(t=new Promise((e,t)=>{const r=()=>{a.removeEventListener("complete",n),a.removeEventListener("error",i),a.removeEventListener("abort",i)},n=()=>{e(),r()},i=()=>{t(a.error||new DOMException("AbortError","AbortError")),r()};a.addEventListener("complete",n),a.addEventListener("error",i),a.addEventListener("abort",i)}),j.set(a,t))),P(e,k=k||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,x):e);var a,t}function U(e){if(e instanceof IDBRequest)return function(a){const e=new Promise((e,t)=>{const r=()=>{a.removeEventListener("success",n),a.removeEventListener("error",i)},n=()=>{e(U(a.result)),r()},i=()=>{t(a.error),r()};a.addEventListener("success",n),a.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&F.set(e,a)}).catch(()=>{}),H.set(e,a),e}(e);if($.has(e))return $.get(e);var t=W(e);return t!==e&&($.set(e,t),H.set(t,e)),t}const G=e=>H.get(e);const J=["get","getKey","getAll","getAllKeys","count"],K=["put","add","delete","clear"],Y=new Map;function X(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Y.get(t))return Y.get(t);const i=t.replace(/FromIndex$/,""),a=t!==i,s=K.includes(i);if(i in(a?IDBIndex:IDBObjectStore).prototype&&(s||J.includes(i))){var r=async function(e,...t){var r=this.transaction(e,s?"readwrite":"readonly");let n=r.store;return a&&(n=n.index(t.shift())),(await Promise.all([n[i](...t),s&&r.done]))[0]};return Y.set(t,r),r}}}x={...A=x,get:(e,t,r)=>X(e,t)||A.get(e,t,r),has:(e,t)=>!!X(e,t)||A.has(e,t)};class q{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Z="@firebase/app",Q="0.10.6",ee=new R("@firebase/app");var te;const re="[DEFAULT]",ne={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},ie=new Map,ae=new Map,se=new Map;function oe(t,r){try{t.container.addComponent(r)}catch(e){ee.debug(`Component ${r.name} failed to register with FirebaseApp ${t.name}`,e)}}function ce(e,t){e.container.addOrOverwriteComponent(t)}function le(e){var t=e.name;if(se.has(t))return ee.debug(`There were multiple attempts to register component ${t}.`),!1;se.set(t,e);for(const r of ie.values())oe(r,e);for(const n of ae.values())oe(n,e);return!0}function he(e,t){const r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function de(e){return void 0!==e.options}const ue=new p("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class pe{constructor(e,t,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new E("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw ue.create("app-deleted",{appName:this._name})}}class fe extends pe{constructor(e,t,r,n){var i=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,a={name:r,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,a,n):super(e.options,a,n),this._serverConfig=Object.assign({automaticDataCollectionEnabled:i},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,ve(Z,Q,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){me(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw ue.create("server-app-deleted")}}const ge="10.12.4-20240716220314";function be(e,t={}){let r=e;if("object"!=typeof t){const i=t;t={name:i}}var n=Object.assign({name:re,automaticDataCollectionEnabled:!1},t);const i=n.name;if("string"!=typeof i||!i)throw ue.create("bad-app-name",{appName:String(i)});if(r=r||h(),!r)throw ue.create("no-options");var a=ie.get(i);if(a){if(b(r,a.options)&&b(n,a.config))return a;throw ue.create("duplicate-app",{appName:i})}const s=new D(i);for(const o of se.values())s.addComponent(o);n=new pe(r,n,s);return ie.set(i,n),n}async function me(e){let t=!1;var r=e.name;if(ie.has(r))t=!0,ie.delete(r);else if(ae.has(r)){const n=e;n.decRefCount()<=0&&(ae.delete(r),t=!0)}t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function ve(e,t,r){let n=null!==(a=ne[e])&&void 0!==a?a:e;r&&(n+=`-${r}`);var i=n.match(/\s|\//),a=t.match(/\s|\//);if(i||a){const s=[`Unable to register library "${n}" with version "${t}":`];return i&&s.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&a&&s.push("and"),a&&s.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ee.warn(s.join(" "))}le(new E(`${n}-version`,()=>({library:n,version:t}),"VERSION"))}function _e(e,t){if(null!==e&&"function"!=typeof e)throw ue.create("invalid-log-argument");!function(a,e){for(const t of I){let i=null;e&&e.level&&(i=L[e.level]),t.userLogHandler=null===a?null:(e,t,...r)=>{var n=r.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(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&a({level:S[t].toLowerCase(),message:n,args:r,type:e.name})}}}(e,t)}function ye(e){var t;t=e,I.forEach(e=>{e.setLogLevel(t)})}const Ee="firebase-heartbeat-database",we=1,Ce="firebase-heartbeat-store";let De=null;function Ie(){return De=De||function(e,t,{blocked:r,upgrade:n,blocking:i,terminated:a}){const s=indexedDB.open(e,t),o=U(s);return n&&s.addEventListener("upgradeneeded",e=>{n(U(s.result),e.oldVersion,e.newVersion,U(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),o.then(e=>{a&&e.addEventListener("close",()=>a()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}(Ee,we,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Ce)}catch(e){console.warn(e)}}}).catch(e=>{throw ue.create("idb-open",{originalErrorMessage:e.message})}),De}async function Se(e,t){try{const n=await Ie(),i=n.transaction(Ce,"readwrite"),a=i.objectStore(Ce);await a.put(t,Oe(e)),await i.done}catch(e){var r;e instanceof o?ee.warn(e.message):(r=ue.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),ee.warn(r.message))}}function Oe(e){return`${e.name}!${e.options.appId}`}class Ae{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Ne(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){var e;const t=this.container.getProvider("platform-logger").getImmediate();var r=t.getPlatformInfoString();const n=Le();if((null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)))&&this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:r}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(r=this._heartbeatsCache)||void 0===r?void 0:r.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";var e=Le(),{heartbeatsToSend:t,unsentEntries:r}=function(e,t=1024){const r=[];let n=e.slice();for(const i of e){const a=r.find(e=>e.agent===i.agent);if(a){if(a.dates.push(i.date),Be(r)>t){a.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Be(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}(this._heartbeatsCache.heartbeats),t=i(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function Le(){const e=new Date;return e.toISOString().substring(0,10)}class Ne{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function(){try{return"object"==typeof indexedDB}catch(e){return}}()&&new Promise((t,r)=>{try{let e=!0;const n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(n),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;r((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){r(e)}}).then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){var e=await async function(e){try{const r=await Ie(),n=r.transaction(Ce);var t=await n.objectStore(Ce).get(Oe(e));return await n.done,t}catch(e){e instanceof o?ee.warn(e.message):(t=ue.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),ee.warn(t.message))}}(this.app);return null!=e&&e.heartbeats?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var r=await this.read();return Se(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var r=await this.read();return Se(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}}}function Be(e){return i(JSON.stringify({version:2,heartbeats:e})).length}te="",le(new E("platform-logger",e=>new q(e),"PRIVATE")),le(new E("heartbeat",e=>new Ae(e),"PRIVATE")),ve(Z,Q,te),ve(Z,Q,"esm2017"),ve("fire-js","");var Te=Object.freeze({__proto__:null,SDK_VERSION:ge,_DEFAULT_ENTRY_NAME:re,_addComponent:oe,_addOrOverwriteComponent:ce,_apps:ie,_clearComponents:function(){se.clear()},_components:se,_getProvider:he,_isFirebaseApp:de,_isFirebaseServerApp:function(e){return void 0!==e.settings},_registerComponent:le,_removeServiceInstance:function(e,t,r=re){he(e,t).clearInstance(r)},_serverApps:ae,deleteApp:me,getApp:function(e=re){var t=ie.get(e);if(!t&&e===re&&h())return be();if(!t)throw ue.create("no-app",{appName:e});return t},getApps:function(){return Array.from(ie.values())},initializeApp:be,initializeServerApp:function(e,t){if(d()&&!u())throw ue.create("invalid-server-app-environment");void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1);let r;r=de(e)?e.options:e;const n=Object.assign(Object.assign({},t),r);if(void 0!==n.releaseOnDeref&&delete n.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw ue.create("finalization-registry-not-supported",{});var i=""+[...JSON.stringify(n)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0);const a=ae.get(i);if(a)return a.incRefCount(t.releaseOnDeref),a;const s=new D(i);for(const c of se.values())s.addComponent(c);var o=new fe(r,t,i,s);return ae.set(i,o),o},onLog:_e,registerVersion:ve,setLogLevel:ye,FirebaseError:o});class Re{constructor(e,t){this._delegate=e,this.firebase=t,oe(e,new E("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),me(this._delegate)))}_getService(e,t=re){var r;this._delegate.checkDestroyed();const n=this._delegate.container.getProvider(e);return n.isInitialized()||"EXPLICIT"!==(null===(r=n.getComponent())||void 0===r?void 0:r.instantiationMode)||n.initialize(),n.getImmediate({identifier:t})}_removeServiceInstance(e,t=re){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){oe(this._delegate,e)}_addOrOverwriteComponent(e){ce(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Pe=new p("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function ke(i){const a={},s={__esModule:!0,initializeApp:function(e,t={}){var r=be(e,t);if(g(a,r.name))return a[r.name];var n=new i(r,s);return a[r.name]=n},app:o,registerVersion:ve,setLogLevel:ye,onLog:_e,apps:null,SDK_VERSION:ge,INTERNAL:{registerComponent:function(r){const n=r.name,t=n.replace("-compat","");{var e;le(r)&&"PUBLIC"===r.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw Pe.create("invalid-app-argument",{appName:n});return e[t]()},void 0!==r.serviceProps&&c(e,r.serviceProps),s[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,n);return t.apply(this,r.multipleInstances?e:[])})}return"PUBLIC"===r.type?s[t]:null},removeApp:function(e){delete a[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var r=t;return r},modularAPIs:Te}};function o(e){if(e=e||re,!g(a,e))throw Pe.create("no-app",{appName:e});return a[e]}return s.default=s,Object.defineProperty(s,"apps",{get:function(){return Object.keys(a).map(e=>a[e])}}),o.App=i,s}var Me=function e(){const t=ke(Re);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:v,ErrorFactory:p,deepExtend:c}),t}();const Fe=new R("@firebase/app-compat");if(d()&&void 0!==self.firebase){Fe.warn(` | ||
Warning: Firebase is already defined in the global scope. Please make sure | ||
@@ -7,3 +7,3 @@ Firebase library is only loaded once. | ||
You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code. | ||
`)}const je=Me;ve("@firebase/app-compat","0.2.36",void 0);return je.registerVersion("firebase","10.12.3","app-compat-cdn"),je}); | ||
`)}const je=Me;ve("@firebase/app-compat","0.2.36",void 0);return je.registerVersion("firebase","10.12.4-20240716220314","app-compat-cdn"),je}); | ||
//# sourceMappingURL=firebase-app-compat.js.map |
@@ -1,3 +0,3 @@ | ||
import{_registerComponent as e,registerVersion as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=o>>2,l=(3&o)<<4|i>>4;let h=(15&i)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++r)),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const o=e[n++];if(o<128)t[r++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[n++];t[r++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],i=e[n++];t[r++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const o=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const i=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const c=o<<2|s>>4;if(r.push(c),64!==i){const e=s<<4&240|i>>2;if(r.push(e),64!==a){const e=i<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,n;return null===(n=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]})(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,s=this.errors[e],i=s?function replaceTemplate(e,t){return e.replace(o,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(s,n):"Error",a=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,a,n)}}const o=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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}}function mapValues(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function encode(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>encode(e)));if("function"==typeof e||"object"==typeof e)return mapValues(e,(e=>encode(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function decode(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>decode(e))):"function"==typeof e||"object"==typeof e?mapValues(e,(e=>decode(e))):e}const s={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FunctionsError extends FirebaseError{constructor(e,t,n){super(`functions/${e}`,t||""),this.details=n}}class ContextProvider{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then((e=>this.auth=e),(()=>{})),this.messaging||t.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||n.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}class FunctionsService{constructor(e,t,n,r,o="us-central1",s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ContextProvider(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(o);this.customDomain=e.origin,this.region="us-central1"}catch(e){this.customDomain=null,this.region=o}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function httpsCallable$1(e,t,n){return r=>function call(e,t,n,r){const o=e._url(t);return callAtURL(e,o,n,r)}(e,t,r,n||{})}async function postJSON(e,t,n,r){let o;n["Content-Type"]="application/json";try{o=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await o.json()}catch(e){}return{status:o.status,json:s}}async function callAtURL(e,t,n,r){const o={data:n=encode(n)},i={},a=await e.contextProvider.getContext(r.limitedUseAppCheckTokens);a.authToken&&(i.Authorization="Bearer "+a.authToken),a.messagingToken&&(i["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(i["X-Firebase-AppCheck"]=a.appCheckToken);const c=function failAfter(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new FunctionsError("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),u=await Promise.race([postJSON(t,o,i,e.fetchImpl),c.promise,e.cancelAllRequests]);if(c.cancel(),!u)throw new FunctionsError("cancelled","Firebase Functions instance was deleted.");const l=function _errorForResponse(e,t){let n,r=function codeForHTTPStatus(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),o=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!s[t])return new FunctionsError("internal","internal");r=s[t],o=t}const i=e.message;"string"==typeof i&&(o=i),n=e.details,void 0!==n&&(n=decode(n))}}catch(e){}return"ok"===r?null:new FunctionsError(r,o,n)}(u.status,u.json);if(l)throw l;if(!u.json)throw new FunctionsError("internal","Response is not valid JSON object.");let h=u.json.data;if(void 0===h&&(h=u.json.result),void 0===h)throw new FunctionsError("internal","Response is missing data field.");return{data:decode(h)}}const i="@firebase/functions";function getFunctions(e=n(),t="us-central1"){const r=_getProvider(getModularInstance(e),"functions").getImmediate({identifier:t}),o=getDefaultEmulatorHostnameAndPort("functions");return o&&connectFunctionsEmulator(r,...o),r}function connectFunctionsEmulator(e,t,n){!function connectFunctionsEmulator$1(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(getModularInstance(e),t,n)}function httpsCallable(e,t,n){return httpsCallable$1(getModularInstance(e),t,n)}function httpsCallableFromURL(e,t,n){return function httpsCallableFromURL$1(e,t,n){return r=>callAtURL(e,t,r,n||{})}(getModularInstance(e),t,n)}!function registerFunctions(n,r){e(new Component("functions",((e,{instanceIdentifier:t})=>{const r=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),s=e.getProvider("messaging-internal"),i=e.getProvider("app-check-internal");return new FunctionsService(r,o,s,i,t,n)}),"PUBLIC").setMultipleInstances(!0)),t(i,"0.11.6",r),t(i,"0.11.6","esm2017")}(fetch.bind(self));export{connectFunctionsEmulator,getFunctions,httpsCallable,httpsCallableFromURL}; | ||
import{_registerComponent as e,registerVersion as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=o>>2,l=(3&o)<<4|i>>4;let h=(15&i)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++r)),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const o=e[n++];if(o<128)t[r++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[n++];t[r++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],i=e[n++];t[r++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const o=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const i=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const c=o<<2|s>>4;if(r.push(c),64!==i){const e=s<<4&240|i>>2;if(r.push(e),64!==a){const e=i<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,n;return null===(n=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]})(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]};class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,s=this.errors[e],i=s?function replaceTemplate(e,t){return e.replace(o,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(s,n):"Error",a=`${this.serviceName}: ${i} (${r}).`;return new FirebaseError(r,a,n)}}const o=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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}}function mapValues(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function encode(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>encode(e)));if("function"==typeof e||"object"==typeof e)return mapValues(e,(e=>encode(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function decode(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>decode(e))):"function"==typeof e||"object"==typeof e?mapValues(e,(e=>decode(e))):e}const s={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FunctionsError extends FirebaseError{constructor(e,t,n){super(`functions/${e}`,t||""),this.details=n}}class ContextProvider{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then((e=>this.auth=e),(()=>{})),this.messaging||t.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||n.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}class FunctionsService{constructor(e,t,n,r,o="us-central1",s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ContextProvider(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(o);this.customDomain=e.origin,this.region="us-central1"}catch(e){this.customDomain=null,this.region=o}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function httpsCallable$1(e,t,n){return r=>function call(e,t,n,r){const o=e._url(t);return callAtURL(e,o,n,r)}(e,t,r,n||{})}async function postJSON(e,t,n,r){let o;n["Content-Type"]="application/json";try{o=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await o.json()}catch(e){}return{status:o.status,json:s}}async function callAtURL(e,t,n,r){const o={data:n=encode(n)},i={},a=await e.contextProvider.getContext(r.limitedUseAppCheckTokens);a.authToken&&(i.Authorization="Bearer "+a.authToken),a.messagingToken&&(i["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(i["X-Firebase-AppCheck"]=a.appCheckToken);const c=function failAfter(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new FunctionsError("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),u=await Promise.race([postJSON(t,o,i,e.fetchImpl),c.promise,e.cancelAllRequests]);if(c.cancel(),!u)throw new FunctionsError("cancelled","Firebase Functions instance was deleted.");const l=function _errorForResponse(e,t){let n,r=function codeForHTTPStatus(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),o=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!s[t])return new FunctionsError("internal","internal");r=s[t],o=t}const i=e.message;"string"==typeof i&&(o=i),n=e.details,void 0!==n&&(n=decode(n))}}catch(e){}return"ok"===r?null:new FunctionsError(r,o,n)}(u.status,u.json);if(l)throw l;if(!u.json)throw new FunctionsError("internal","Response is not valid JSON object.");let h=u.json.data;if(void 0===h&&(h=u.json.result),void 0===h)throw new FunctionsError("internal","Response is missing data field.");return{data:decode(h)}}const i="@firebase/functions";function getFunctions(e=n(),t="us-central1"){const r=_getProvider(getModularInstance(e),"functions").getImmediate({identifier:t}),o=getDefaultEmulatorHostnameAndPort("functions");return o&&connectFunctionsEmulator(r,...o),r}function connectFunctionsEmulator(e,t,n){!function connectFunctionsEmulator$1(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(getModularInstance(e),t,n)}function httpsCallable(e,t,n){return httpsCallable$1(getModularInstance(e),t,n)}function httpsCallableFromURL(e,t,n){return function httpsCallableFromURL$1(e,t,n){return r=>callAtURL(e,t,r,n||{})}(getModularInstance(e),t,n)}!function registerFunctions(n,r){e(new Component("functions",((e,{instanceIdentifier:t})=>{const r=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),s=e.getProvider("messaging-internal"),i=e.getProvider("app-check-internal");return new FunctionsService(r,o,s,i,t,n)}),"PUBLIC").setMultipleInstances(!0)),t(i,"0.11.6",r),t(i,"0.11.6","esm2017")}(fetch.bind(self));export{connectFunctionsEmulator,getFunctions,httpsCallable,httpsCallableFromURL}; | ||
//# sourceMappingURL=firebase-functions.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_getProvider,getApp as t,_registerComponent as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},a=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${i} (${a}).`;return new FirebaseError(a,s,n)}}const r=/\{\$([^}]+)}/g;class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 a,o;const i=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,l=new WeakMap;let d={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(i.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return a||(a=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,d):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&i.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),l.set(t,e)),t}const unwrap=e=>l.get(e);const p=["get","getKey","getAll","getAllKeys","count"],f=["put","add","delete","clear"],g=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(g.get(t))return g.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=f.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!p.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,a?"readwrite":"readonly");let i=o.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),a&&o.done]))[0]};return g.set(t,method),method}!function replaceTraps(e){d=e(d)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.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 n=getHeaders(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const I=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=getBroadcastChannel();n&&n.postMessage({key:e,fid:t});closeBroadcastChannel()}(n,t)}function callFidChangeCallbacks(e,t){const n=I.get(e);if(n)for(const e of n)e(t)}let y=null;function getBroadcastChannel(){return!y&&"BroadcastChannel"in self&&(y=new BroadcastChannel("[Firebase] FID Change"),y.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)}),y}function closeBroadcastChannel(){0===I.size&&y&&(y.close(),y=null)}const v="firebase-installations-store";let b=null;function getDbPromise(){return b||(b=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),s=wrap(i);return r&&i.addEventListener("upgradeneeded",(e=>{r(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),n&&i.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),b}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n);return await a.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n),i=t(o);return void 0===i?await a.delete(n):await a.put(i,n),await r.done,!i||o&&o.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}async function deleteInstallationRequest(e,t){const n=function getDeleteEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}`}(e,t),r={method:"DELETE",headers:getHeadersWithAuth(e,t)},a=await retryIfServerError((()=>fetch(n,r)));if(!a.ok)throw await getErrorFromResponse("Delete Installation",a)}async function deleteInstallations(e){const{appConfig:t}=e,n=await update(t,(e=>{if(!e||0!==e.registrationStatus)return e}));if(n){if(1===n.registrationStatus)throw w.create("delete-pending-registration");if(2===n.registrationStatus){if(!navigator.onLine)throw w.create("app-offline");await deleteInstallationRequest(t,n),await remove(t)}}}function onIdChange(e,t){const{appConfig:n}=e;return function addCallback(e,t){getBroadcastChannel();const n=getKey(e);let r=I.get(n);r||(r=new Set,I.set(n,r)),r.add(t)}(n,t),()=>{!function removeCallback(e,t){const n=getKey(e),r=I.get(n);r&&(r.delete(t),0===r.size&&I.delete(n),closeBroadcastChannel())}(n,t)}}function getInstallations(e=t()){return _getProvider(e,"installations").getImmediate()}function getMissingValueError(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>getId(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){n(new Component("installations",publicFactory,"PUBLIC")),n(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");export{deleteInstallations,getId,getInstallations,getToken,onIdChange}; | ||
import{registerVersion as e,_getProvider,getApp as t,_registerComponent as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},a=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${i} (${a}).`;return new FirebaseError(a,s,n)}}const r=/\{\$([^}]+)}/g;class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 a,o;const i=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,l=new WeakMap;let d={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(i.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return a||(a=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,d):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&i.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),l.set(t,e)),t}const unwrap=e=>l.get(e);const p=["get","getKey","getAll","getAllKeys","count"],f=["put","add","delete","clear"],g=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(g.get(t))return g.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=f.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!p.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,a?"readwrite":"readonly");let i=o.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),a&&o.done]))[0]};return g.set(t,method),method}!function replaceTraps(e){d=e(d)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.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 n=getHeaders(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const I=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=getBroadcastChannel();n&&n.postMessage({key:e,fid:t});closeBroadcastChannel()}(n,t)}function callFidChangeCallbacks(e,t){const n=I.get(e);if(n)for(const e of n)e(t)}let y=null;function getBroadcastChannel(){return!y&&"BroadcastChannel"in self&&(y=new BroadcastChannel("[Firebase] FID Change"),y.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)}),y}function closeBroadcastChannel(){0===I.size&&y&&(y.close(),y=null)}const v="firebase-installations-store";let b=null;function getDbPromise(){return b||(b=function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),s=wrap(i);return r&&i.addEventListener("upgradeneeded",(e=>{r(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),n&&i.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),b}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n);return await a.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n),i=t(o);return void 0===i?await a.delete(n):await a.put(i,n),await r.done,!i||o&&o.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}async function deleteInstallationRequest(e,t){const n=function getDeleteEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}`}(e,t),r={method:"DELETE",headers:getHeadersWithAuth(e,t)},a=await retryIfServerError((()=>fetch(n,r)));if(!a.ok)throw await getErrorFromResponse("Delete Installation",a)}async function deleteInstallations(e){const{appConfig:t}=e,n=await update(t,(e=>{if(!e||0!==e.registrationStatus)return e}));if(n){if(1===n.registrationStatus)throw w.create("delete-pending-registration");if(2===n.registrationStatus){if(!navigator.onLine)throw w.create("app-offline");await deleteInstallationRequest(t,n),await remove(t)}}}function onIdChange(e,t){const{appConfig:n}=e;return function addCallback(e,t){getBroadcastChannel();const n=getKey(e);let r=I.get(n);r||(r=new Set,I.set(n,r)),r.add(t)}(n,t),()=>{!function removeCallback(e,t){const n=getKey(e),r=I.get(n);r&&(r.delete(t),0===r.size&&I.delete(n),closeBroadcastChannel())}(n,t)}}function getInstallations(e=t()){return _getProvider(e,"installations").getImmediate()}function getMissingValueError(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>getId(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){n(new Component("installations",publicFactory,"PUBLIC")),n(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");export{deleteInstallations,getId,getInstallations,getToken,onIdChange}; | ||
//# sourceMappingURL=firebase-installations.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},o=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",s=`${this.serviceName}: ${a} (${o}).`;return new FirebaseError(o,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 o,i;const a=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap;let l={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(a.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return o||(o=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,l):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&a.set(t,e)})).catch((()=>{})),d.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),d.set(t,e)),t}const unwrap=e=>d.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=wrap(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(wrap(a.result),e.oldVersion,e.newVersion,wrap(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),o&&e.addEventListener("versionchange",(e=>o(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const p=["get","getKey","getAll","getAllKeys","count"],f=["put","add","delete","clear"],g=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(g.get(t))return g.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=f.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!p.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return g.set(t,method),method}!function replaceTraps(e){l=e(l)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep$1(e){return new Promise((t=>{setTimeout(t,e)}))}const m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const y=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!b&&"BroadcastChannel"in self&&(b=new BroadcastChannel("[Firebase] FID Change"),b.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return b}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===y.size&&b&&(b.close(),b=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=y.get(e);if(n)for(const e of n)e(t)}let b=null;const v="firebase-installations-store";let k=null;function getDbPromise$1(){return k||(k=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),k}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),o=r.objectStore(v),i=await o.get(n);return await o.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),o=r.objectStore(v),i=await o.get(n),a=t(i);return void 0===a?await o.delete(n):await o.put(a,n),await r.done,!a||i&&i.fid===a.fid||fidChanged(e,a.fid),a}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),o=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),o=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&o.append("x-firebase-client",e)}const a={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:o,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=o.registrationPromise,o.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep$1(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),o=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&o.append("x-firebase-client",e)}const a={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:o,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const o=r.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+36e5}(e)}(o))return r;if(1===o.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep$1(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError$1(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");const I="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4";var T,S;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(T||(T={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(S||(S={}));const E="firebase-messaging-store";let C=null;function getDbPromise(){return C||(C=openDB("firebase-messaging-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(E)}})),C}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(E).objectStore(E).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes("fcm_token_details_db"))return null}let t=null;return(await openDB("fcm_token_details_db",5,{upgrade:async(n,r,o,i)=>{var a;if(r<2)return;if(!n.objectStoreNames.contains("fcm_token_object_Store"))return;const s=i.objectStore("fcm_token_object_Store"),c=await s.index("fcmSenderId").get(e);if(await s.clear(),c)if(2===r){const e=c;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:null!==(a=e.createTime)&&void 0!==a?a:Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB("fcm_token_details_db"),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(E,"readwrite");return await r.objectStore(E).put(t,n),await r.done,t}function getKey({appConfig:e}){return e.appId}const D=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),o=await r.json();if(o.error){const e=o.error.message;throw D.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw D.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const o={web:{endpoint:n,auth:t,p256dh:e}};return r!==I&&(o.web.applicationPubKey=r),o}async function getTokenInternal(e){const t=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,o=t.auth===e.auth,i=t.p256dh===e.p256dh;return n&&r&&o&&i}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions),o={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,o);i=await n.json()}catch(e){throw D.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){const e=i.error.message;throw D.create("token-update-failed",{errorInfo:e})}if(!i.token)throw D.create("token-update-no-token");return i.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function deleteTokenInternal(e){const t=await dbGet(e.firebaseDependencies);t&&(await requestDeleteToken(e.firebaseDependencies,t.token),await async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(E,"readwrite");await n.objectStore(E).delete(t),await n.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t),o={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const t=await fetch(getEndpoint(e.appConfig),o);i=await t.json()}catch(e){throw D.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){const e=i.error.message;throw D.create("token-subscribe-failed",{errorInfo:e})}if(!i.token)throw D.create("token-subscribe-no-token");return i.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}async function stageLog(e,t){const n=function createFcmEvent(e,t){var n,r;const o={};e.from&&(o.project_number=e.from);e.fcmMessageId&&(o.message_id=e.fcmMessageId);o.instance_id=t,e.notification?o.message_type=T.DISPLAY_NOTIFICATION.toString():o.message_type=T.DATA_MESSAGE.toString();o.sdk_platform=3..toString(),o.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),!e.collapse_key||(o.collapse_key=e.collapse_key);o.event=1..toString(),!(null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label)||(o.analytics_label=null===(r=e.fcmOptions)||void 0===r?void 0:r.analytics_label);return o}(t,await e.firebaseDependencies.installations.getId());!function createAndEnqueueLogEvent(e,t,n){const r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify(t),!n||(r.compliance_data=function buildComplianceData(e){return{privacy_context:{prequest:{origin_associated_product_id:e}}}}(n));e.logEvents.push(r)}(e,n,t.productId)}function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function onPush(e,t){const n=function getMessagePayloadInternal({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(!n)return;t.deliveryMetricsExportedToBigQueryEnabled&&await stageLog(t,n);const r=await getClientList();if(function hasVisibleClients(e){return e.some((e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))}(r))return function sendMessagePayloadInternalToWindows(e,t){t.isFirebaseMessaging=!0,t.messageType=S.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(r,n);if(n.notification&&await function showNotification(e){var t;const{actions:n}=e,{maxActions:r}=Notification;n&&r&&n.length>r&&console.warn(`This browser only supports ${r} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(t=e.title)&&void 0!==t?t:"",e)}(function wrapInternalPayload(e){const t=Object.assign({},e.notification);return t.data={FCM_MSG:e},t}(n)),t&&t.onBackgroundMessageHandler){const e=function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const o=t.notification.image;o&&(e.notification.image=o);const i=t.notification.icon;i&&(e.notification.icon=i)}(t,e),function propagateDataPayload(e,t){t.data&&(e.data=t.data)}(t,e),function propagateFcmOptions(e,t){var n,r,o,i,a;if(!t.fcmOptions&&!(null===(n=t.notification)||void 0===n?void 0:n.click_action))return;e.fcmOptions={};const s=null!==(o=null===(r=t.fcmOptions)||void 0===r?void 0:r.link)&&void 0!==o?o:null===(i=t.notification)||void 0===i?void 0:i.click_action;s&&(e.fcmOptions.link=s);const c=null===(a=t.fcmOptions)||void 0===a?void 0:a.analytics_label;c&&(e.fcmOptions.analyticsLabel=c)}(t,e),t}(n);"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(e):t.onBackgroundMessageHandler.next(e)}}async function onNotificationClick(e){var t,n;const r=null===(n=null===(t=e.notification)||void 0===t?void 0:t.data)||void 0===n?void 0:n.FCM_MSG;if(!r)return;if(e.action)return;e.stopImmediatePropagation(),e.notification.close();const o=function getLink(e){var t,n,r;const o=null!==(n=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==n?n:null===(r=e.notification)||void 0===r?void 0:r.click_action;if(o)return o;return function isConsoleMessage(e){return"object"==typeof e&&!!e&&"google.c.a.c_id"in e}(e.data)?self.location.origin:null}(r);if(!o)return;const i=new URL(o,self.location.href),a=new URL(self.location.origin);if(i.host!==a.host)return;let s=await async function getWindowClient(e){const t=await getClientList();for(const n of t){const t=new URL(n.url,self.location.href);if(e.host===t.host)return n}return null}(i);return s?s=await s.focus():(s=await self.clients.openWindow(o),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(3e3)),s?(r.messageType=S.NOTIFICATION_CLICKED,r.isFirebaseMessaging=!0,s.postMessage(r)):void 0}function getClientList(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function getMissingValueError(e){return D.create("missing-app-config-values",{valueName:e})}_mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),_mergeStrings("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const SwMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",(e=>{e.waitUntil(onPush(e,t))})),self.addEventListener("pushsubscriptionchange",(e=>{e.waitUntil(async function onSubChange(e,t){var n,r;const{newSubscription:o}=e;if(!o)return void await deleteTokenInternal(t);const i=await dbGet(t.firebaseDependencies);await deleteTokenInternal(t),t.vapidKey=null!==(r=null===(n=null==i?void 0:i.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==r?r:I,await getTokenInternal(t)}(e,t))})),self.addEventListener("notificationclick",(e=>{e.waitUntil(onNotificationClick(e))})),t};async function isSwSupported(){return function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",o=self.indexedDB.open(r);o.onsuccess=()=>{o.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},o.onupgradeneeded=()=>{n=!1},o.onerror=()=>{var e;t((null===(e=o.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function getMessagingInSw(e=n()){return isSwSupported().then((e=>{if(!e)throw D.create("unsupported-browser")}),(e=>{throw D.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging-sw").getImmediate()}function onBackgroundMessage(e,t){return function onBackgroundMessage$1(e,t){if(void 0!==self.document)throw D.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=getModularInstance(e),t)}function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(e,t){return function _setDeliveryMetricsExportedToBigQueryEnabled(e,t){e.deliveryMetricsExportedToBigQueryEnabled=t}(e=getModularInstance(e),t)}!function registerMessagingInSw(){t(new Component("messaging-sw",SwMessagingFactory,"PUBLIC"))}();export{experimentalSetDeliveryMetricsExportedToBigQueryEnabled,getMessagingInSw as getMessaging,isSwSupported as isSupported,onBackgroundMessage}; | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},o=`${this.service}/${e}`,i=this.errors[e],a=i?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",s=`${this.serviceName}: ${a} (${o}).`;return new FirebaseError(o,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 o,i;const a=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap;let l={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(a.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return o||(o=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,l):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&a.set(t,e)})).catch((()=>{})),d.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),d.set(t,e)),t}const unwrap=e=>d.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=wrap(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(wrap(a.result),e.oldVersion,e.newVersion,wrap(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{i&&e.addEventListener("close",(()=>i())),o&&e.addEventListener("versionchange",(e=>o(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const p=["get","getKey","getAll","getAllKeys","count"],f=["put","add","delete","clear"],g=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(g.get(t))return g.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=f.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!p.includes(n))return;const method=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return g.set(t,method),method}!function replaceTraps(e){l=e(l)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep$1(e){return new Promise((t=>{setTimeout(t,e)}))}const m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const y=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!b&&"BroadcastChannel"in self&&(b=new BroadcastChannel("[Firebase] FID Change"),b.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return b}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===y.size&&b&&(b.close(),b=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=y.get(e);if(n)for(const e of n)e(t)}let b=null;const v="firebase-installations-store";let k=null;function getDbPromise$1(){return k||(k=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),k}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),o=r.objectStore(v),i=await o.get(n);return await o.put(t,n),await r.done,i&&i.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),o=r.objectStore(v),i=await o.get(n),a=t(i);return void 0===a?await o.delete(n):await o.put(a,n),await r.done,!a||i&&i.fid===a.fid||fidChanged(e,a.fid),a}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),o=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),o=getHeaders$1(e),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&o.append("x-firebase-client",e)}const a={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:o,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=o.registrationPromise,o.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep$1(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),o=getHeadersWithAuth(e,n),i=t.getImmediate({optional:!0});if(i){const e=await i.getHeartbeatsHeader();e&&o.append("x-firebase-client",e)}const a={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:o,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const o=r.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+36e5}(e)}(o))return r;if(1===o.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep$1(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError$1(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");const I="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4";var T,S;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(T||(T={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(S||(S={}));const E="firebase-messaging-store";let C=null;function getDbPromise(){return C||(C=openDB("firebase-messaging-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(E)}})),C}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(E).objectStore(E).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes("fcm_token_details_db"))return null}let t=null;return(await openDB("fcm_token_details_db",5,{upgrade:async(n,r,o,i)=>{var a;if(r<2)return;if(!n.objectStoreNames.contains("fcm_token_object_Store"))return;const s=i.objectStore("fcm_token_object_Store"),c=await s.index("fcmSenderId").get(e);if(await s.clear(),c)if(2===r){const e=c;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:null!==(a=e.createTime)&&void 0!==a?a:Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB("fcm_token_details_db"),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(E,"readwrite");return await r.objectStore(E).put(t,n),await r.done,t}function getKey({appConfig:e}){return e.appId}const D=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),o=await r.json();if(o.error){const e=o.error.message;throw D.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw D.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const o={web:{endpoint:n,auth:t,p256dh:e}};return r!==I&&(o.web.applicationPubKey=r),o}async function getTokenInternal(e){const t=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,o=t.auth===e.auth,i=t.p256dh===e.p256dh;return n&&r&&o&&i}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions),o={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,o);i=await n.json()}catch(e){throw D.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){const e=i.error.message;throw D.create("token-update-failed",{errorInfo:e})}if(!i.token)throw D.create("token-update-no-token");return i.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function deleteTokenInternal(e){const t=await dbGet(e.firebaseDependencies);t&&(await requestDeleteToken(e.firebaseDependencies,t.token),await async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(E,"readwrite");await n.objectStore(E).delete(t),await n.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t),o={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const t=await fetch(getEndpoint(e.appConfig),o);i=await t.json()}catch(e){throw D.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){const e=i.error.message;throw D.create("token-subscribe-failed",{errorInfo:e})}if(!i.token)throw D.create("token-subscribe-no-token");return i.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}async function stageLog(e,t){const n=function createFcmEvent(e,t){var n,r;const o={};e.from&&(o.project_number=e.from);e.fcmMessageId&&(o.message_id=e.fcmMessageId);o.instance_id=t,e.notification?o.message_type=T.DISPLAY_NOTIFICATION.toString():o.message_type=T.DATA_MESSAGE.toString();o.sdk_platform=3..toString(),o.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),!e.collapse_key||(o.collapse_key=e.collapse_key);o.event=1..toString(),!(null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label)||(o.analytics_label=null===(r=e.fcmOptions)||void 0===r?void 0:r.analytics_label);return o}(t,await e.firebaseDependencies.installations.getId());!function createAndEnqueueLogEvent(e,t,n){const r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify(t),!n||(r.compliance_data=function buildComplianceData(e){return{privacy_context:{prequest:{origin_associated_product_id:e}}}}(n));e.logEvents.push(r)}(e,n,t.productId)}function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function onPush(e,t){const n=function getMessagePayloadInternal({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(!n)return;t.deliveryMetricsExportedToBigQueryEnabled&&await stageLog(t,n);const r=await getClientList();if(function hasVisibleClients(e){return e.some((e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))}(r))return function sendMessagePayloadInternalToWindows(e,t){t.isFirebaseMessaging=!0,t.messageType=S.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(r,n);if(n.notification&&await function showNotification(e){var t;const{actions:n}=e,{maxActions:r}=Notification;n&&r&&n.length>r&&console.warn(`This browser only supports ${r} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(t=e.title)&&void 0!==t?t:"",e)}(function wrapInternalPayload(e){const t=Object.assign({},e.notification);return t.data={FCM_MSG:e},t}(n)),t&&t.onBackgroundMessageHandler){const e=function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const o=t.notification.image;o&&(e.notification.image=o);const i=t.notification.icon;i&&(e.notification.icon=i)}(t,e),function propagateDataPayload(e,t){t.data&&(e.data=t.data)}(t,e),function propagateFcmOptions(e,t){var n,r,o,i,a;if(!t.fcmOptions&&!(null===(n=t.notification)||void 0===n?void 0:n.click_action))return;e.fcmOptions={};const s=null!==(o=null===(r=t.fcmOptions)||void 0===r?void 0:r.link)&&void 0!==o?o:null===(i=t.notification)||void 0===i?void 0:i.click_action;s&&(e.fcmOptions.link=s);const c=null===(a=t.fcmOptions)||void 0===a?void 0:a.analytics_label;c&&(e.fcmOptions.analyticsLabel=c)}(t,e),t}(n);"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(e):t.onBackgroundMessageHandler.next(e)}}async function onNotificationClick(e){var t,n;const r=null===(n=null===(t=e.notification)||void 0===t?void 0:t.data)||void 0===n?void 0:n.FCM_MSG;if(!r)return;if(e.action)return;e.stopImmediatePropagation(),e.notification.close();const o=function getLink(e){var t,n,r;const o=null!==(n=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==n?n:null===(r=e.notification)||void 0===r?void 0:r.click_action;if(o)return o;return function isConsoleMessage(e){return"object"==typeof e&&!!e&&"google.c.a.c_id"in e}(e.data)?self.location.origin:null}(r);if(!o)return;const i=new URL(o,self.location.href),a=new URL(self.location.origin);if(i.host!==a.host)return;let s=await async function getWindowClient(e){const t=await getClientList();for(const n of t){const t=new URL(n.url,self.location.href);if(e.host===t.host)return n}return null}(i);return s?s=await s.focus():(s=await self.clients.openWindow(o),await function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}(3e3)),s?(r.messageType=S.NOTIFICATION_CLICKED,r.isFirebaseMessaging=!0,s.postMessage(r)):void 0}function getClientList(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function getMissingValueError(e){return D.create("missing-app-config-values",{valueName:e})}_mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),_mergeStrings("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const SwMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",(e=>{e.waitUntil(onPush(e,t))})),self.addEventListener("pushsubscriptionchange",(e=>{e.waitUntil(async function onSubChange(e,t){var n,r;const{newSubscription:o}=e;if(!o)return void await deleteTokenInternal(t);const i=await dbGet(t.firebaseDependencies);await deleteTokenInternal(t),t.vapidKey=null!==(r=null===(n=null==i?void 0:i.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==r?r:I,await getTokenInternal(t)}(e,t))})),self.addEventListener("notificationclick",(e=>{e.waitUntil(onNotificationClick(e))})),t};async function isSwSupported(){return function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",o=self.indexedDB.open(r);o.onsuccess=()=>{o.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},o.onupgradeneeded=()=>{n=!1},o.onerror=()=>{var e;t((null===(e=o.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function getMessagingInSw(e=n()){return isSwSupported().then((e=>{if(!e)throw D.create("unsupported-browser")}),(e=>{throw D.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging-sw").getImmediate()}function onBackgroundMessage(e,t){return function onBackgroundMessage$1(e,t){if(void 0!==self.document)throw D.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=getModularInstance(e),t)}function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(e,t){return function _setDeliveryMetricsExportedToBigQueryEnabled(e,t){e.deliveryMetricsExportedToBigQueryEnabled=t}(e=getModularInstance(e),t)}!function registerMessagingInSw(){t(new Component("messaging-sw",SwMessagingFactory,"PUBLIC"))}();export{experimentalSetDeliveryMetricsExportedToBigQueryEnabled,getMessagingInSw as getMessaging,isSwSupported as isSupported,onBackgroundMessage}; | ||
//# sourceMappingURL=firebase-messaging-sw.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},a=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${i} (${a}).`;return new FirebaseError(a,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 a,o;const i=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap;let p={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(i.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return a||(a=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,p):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&i.set(t,e)})).catch((()=>{})),d.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),d.set(t,e)),t}const unwrap=e=>d.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),s=wrap(i);return r&&i.addEventListener("upgradeneeded",(e=>{r(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),n&&i.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const l=["get","getKey","getAll","getAllKeys","count"],g=["put","add","delete","clear"],f=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(f.get(t))return f.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=g.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!l.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,a?"readwrite":"readonly");let i=o.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),a&&o.done]))[0]};return f.set(t,method),method}!function replaceTraps(e){p=e(p)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const y=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!b&&"BroadcastChannel"in self&&(b=new BroadcastChannel("[Firebase] FID Change"),b.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return b}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===y.size&&b&&(b.close(),b=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=y.get(e);if(n)for(const e of n)e(t)}let b=null;const v="firebase-installations-store";let k=null;function getDbPromise$1(){return k||(k=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),k}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n);return await a.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n),i=t(o);return void 0===i?await a.delete(n):await a.put(i,n),await r.done,!i||o&&o.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken$2(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError$1(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken$2(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");const I="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4";var T,S;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(T||(T={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(S||(S={}));const E="firebase-messaging-store";let D=null;function getDbPromise(){return D||(D=openDB("firebase-messaging-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(E)}})),D}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(E).objectStore(E).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes("fcm_token_details_db"))return null}let t=null;return(await openDB("fcm_token_details_db",5,{upgrade:async(n,r,a,o)=>{var i;if(r<2)return;if(!n.objectStoreNames.contains("fcm_token_object_Store"))return;const s=o.objectStore("fcm_token_object_Store"),c=await s.index("fcmSenderId").get(e);if(await s.clear(),c)if(2===r){const e=c;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:null!==(i=e.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB("fcm_token_details_db"),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(E,"readwrite");return await r.objectStore(E).put(t,n),await r.done,t}function getKey({appConfig:e}){return e.appId}const C=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),a=await r.json();if(a.error){const e=a.error.message;throw C.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw C.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const a={web:{endpoint:n,auth:t,p256dh:e}};return r!==I&&(a.web.applicationPubKey=r),a}async function getTokenInternal(e){const t=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,a=t.auth===e.auth,o=t.p256dh===e.p256dh;return n&&r&&a&&o}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions),a={method:"PATCH",headers:n,body:JSON.stringify(r)};let o;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,a);o=await n.json()}catch(e){throw C.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(o.error){const e=o.error.message;throw C.create("token-update-failed",{errorInfo:e})}if(!o.token)throw C.create("token-update-no-token");return o.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function deleteTokenInternal(e){const t=await dbGet(e.firebaseDependencies);t&&(await requestDeleteToken(e.firebaseDependencies,t.token),await async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(E,"readwrite");await n.objectStore(E).delete(t),await n.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t),a={method:"POST",headers:n,body:JSON.stringify(r)};let o;try{const t=await fetch(getEndpoint(e.appConfig),a);o=await t.json()}catch(e){throw C.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(o.error){const e=o.error.message;throw C.create("token-subscribe-failed",{errorInfo:e})}if(!o.token)throw C.create("token-subscribe-no-token");return o.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const a=t.notification.image;a&&(e.notification.image=a);const o=t.notification.icon;o&&(e.notification.icon=o)}(t,e),function propagateDataPayload(e,t){if(!t.data)return;e.data=t.data}(t,e),function propagateFcmOptions(e,t){var n,r,a,o,i;if(!t.fcmOptions&&!(null===(n=t.notification)||void 0===n?void 0:n.click_action))return;e.fcmOptions={};const s=null!==(a=null===(r=t.fcmOptions)||void 0===r?void 0:r.link)&&void 0!==a?a:null===(o=t.notification)||void 0===o?void 0:o.click_action;s&&(e.fcmOptions.link=s);const c=null===(i=t.fcmOptions)||void 0===i?void 0:i.analytics_label;c&&(e.fcmOptions.analyticsLabel=c)}(t,e),t}function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function getMissingValueError(e){return C.create("missing-app-config-values",{valueName:e})}_mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),_mergeStrings("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function registerDefaultSw(e){try{e.swRegistration=await navigator.serviceWorker.register("/firebase-messaging-sw.js",{scope:"/firebase-cloud-messaging-push-scope"}),e.swRegistration.update().catch((()=>{}))}catch(e){throw C.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function getToken$1(e,t){if(!navigator)throw C.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw C.create("permission-blocked");return await async function updateVapidKey(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=I)}(e,null==t?void 0:t.vapidKey),await async function updateSwReg(e,t){if(t||e.swRegistration||await registerDefaultSw(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw C.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),getTokenInternal(e)}async function logToScion(e,t,n){const r=function getEventType(e){switch(e){case S.NOTIFICATION_CLICKED:return"notification_open";case S.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(r,{message_id:n["google.c.a.c_id"],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}const M="@firebase/messaging",WindowMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",(e=>async function messageEventListener(e,t){const n=t.data;if(!n.isFirebaseMessaging)return;e.onMessageHandler&&n.messageType===S.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(externalizePayload(n)):e.onMessageHandler.next(externalizePayload(n)));const r=n.data;(function isConsoleMessage(e){return"object"==typeof e&&!!e&&"google.c.a.c_id"in e})(r)&&"1"===r["google.c.a.e"]&&await logToScion(e,n.messageType,r)}(t,e))),t},WindowMessagingInternalFactory=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>getToken$1(t,e)}};async function isWindowSupported(){try{await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()}catch(e){return!1}return"undefined"!=typeof window&&function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function getMessagingInWindow(e=n()){return isWindowSupported().then((e=>{if(!e)throw C.create("unsupported-browser")}),(e=>{throw C.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging").getImmediate()}async function getToken(e,t){return getToken$1(e=getModularInstance(e),t)}function deleteToken(e){return async function deleteToken$1(e){if(!navigator)throw C.create("only-available-in-window");return e.swRegistration||await registerDefaultSw(e),deleteTokenInternal(e)}(e=getModularInstance(e))}function onMessage(e,t){return function onMessage$1(e,t){if(!navigator)throw C.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=getModularInstance(e),t)}!function registerMessagingInWindow(){t(new Component("messaging",WindowMessagingFactory,"PUBLIC")),t(new Component("messaging-internal",WindowMessagingInternalFactory,"PRIVATE")),e(M,"0.12.10"),e(M,"0.12.10","esm2017")}();export{deleteToken,getMessagingInWindow as getMessaging,getToken,isWindowSupported as isSupported,onMessage}; | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},a=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${i} (${a}).`;return new FirebaseError(a,s,n)}}const r=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 a,o;const i=new WeakMap,s=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap;let p={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return s.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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 o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(i.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return c.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(s.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));s.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return a||(a=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,p):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&i.set(t,e)})).catch((()=>{})),d.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=transformCachableValue(e);return t!==e&&(u.set(e,t),d.set(t,e)),t}const unwrap=e=>d.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),s=wrap(i);return r&&i.addEventListener("upgradeneeded",(e=>{r(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),n&&i.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),wrap(n).then((()=>{}))}const l=["get","getKey","getAll","getAllKeys","count"],g=["put","add","delete","clear"],f=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(f.get(t))return f.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=g.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!l.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,a?"readwrite":"readonly");let i=o.store;return r&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),a&&o.done]))[0]};return f.set(t,method),method}!function replaceTraps(e){p=e(p)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const h="@firebase/installations",w=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 n=(await t.json()).error;return w.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function getHeaders$1({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const n=getHeaders$1(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 m=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return m.test(t)?t:""}catch(e){return""}}function getKey$1(e){return`${e.appName}!${e.appId}`}const y=new Map;function fidChanged(e,t){const n=getKey$1(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!b&&"BroadcastChannel"in self&&(b=new BroadcastChannel("[Firebase] FID Change"),b.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return b}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===y.size&&b&&(b.close(),b=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=y.get(e);if(n)for(const e of n)e(t)}let b=null;const v="firebase-installations-store";let k=null;function getDbPromise$1(){return k||(k=openDB("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(v)}})),k}async function set(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n);return await a.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey$1(e),n=(await getDbPromise$1()).transaction(v,"readwrite");await n.objectStore(v).delete(t),await n.done}async function update(e,t){const n=getKey$1(e),r=(await getDbPromise$1()).transaction(v,"readwrite"),a=r.objectStore(v),o=await a.get(n),i=t(o);return void 0===i?await a.delete(n):await a.put(i,n),await r.done,!i||o&&o.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(w.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),a=getHeaders$1(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=a.registrationPromise,a.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw w.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),a=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw w.create("not-registered");const a=r.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+36e5}(e)}(a))return r;if(1===a.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw w.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw w.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken$2(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError$1(e){return w.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=function extractAppConfig$1(e){if(!e||!e.options)throw getMissingValueError$1("App Configuration");if(!e.name)throw getMissingValueError$1("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw getMissingValueError$1(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken$2(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(h,"0.6.8"),e(h,"0.6.8","esm2017");const I="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4";var T,S;function arrayToBase64(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function base64ToArray(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;++e)r[e]=n.charCodeAt(e);return r}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(T||(T={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(S||(S={}));const E="firebase-messaging-store";let D=null;function getDbPromise(){return D||(D=openDB("firebase-messaging-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(E)}})),D}async function dbGet(e){const t=getKey(e),n=await getDbPromise(),r=await n.transaction(E).objectStore(E).get(t);if(r)return r;{const t=await async function migrateOldDatabase(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes("fcm_token_details_db"))return null}let t=null;return(await openDB("fcm_token_details_db",5,{upgrade:async(n,r,a,o)=>{var i;if(r<2)return;if(!n.objectStoreNames.contains("fcm_token_object_Store"))return;const s=o.objectStore("fcm_token_object_Store"),c=await s.index("fcmSenderId").get(e);if(await s.clear(),c)if(2===r){const e=c;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:null!==(i=e.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:arrayToBase64(e.vapidKey)}}}else if(3===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}else if(4===r){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:arrayToBase64(e.auth),p256dh:arrayToBase64(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:arrayToBase64(e.vapidKey)}}}}})).close(),await deleteDB("fcm_token_details_db"),await deleteDB("fcm_vapid_details_db"),await deleteDB("undefined"),function checkTokenDetails(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await dbSet(e,t),t}}async function dbSet(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(E,"readwrite");return await r.objectStore(E).put(t,n),await r.done,t}function getKey({appConfig:e}){return e.appId}const C=new ErrorFactory("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function requestDeleteToken(e,t){const n={method:"DELETE",headers:await getHeaders(e)};try{const r=await fetch(`${getEndpoint(e.appConfig)}/${t}`,n),a=await r.json();if(a.error){const e=a.error.message;throw C.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw C.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function getEndpoint({projectId:e}){return`https://fcmregistrations.googleapis.com/v1/projects/${e}/registrations`}async function getHeaders({appConfig:e,installations:t}){const n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function getBody({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const a={web:{endpoint:n,auth:t,p256dh:e}};return r!==I&&(a.web.applicationPubKey=r),a}async function getTokenInternal(e){const t=await async function getPushSubscription(e,t){const n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:base64ToArray(t)})}(e.swRegistration,e.vapidKey),n={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:arrayToBase64(t.getKey("auth")),p256dh:arrayToBase64(t.getKey("p256dh"))},r=await dbGet(e.firebaseDependencies);if(r){if(function isTokenValid(e,t){const n=t.vapidKey===e.vapidKey,r=t.endpoint===e.endpoint,a=t.auth===e.auth,o=t.p256dh===e.p256dh;return n&&r&&a&&o}(r.subscriptionOptions,n))return Date.now()>=r.createTime+6048e5?async function updateToken(e,t){try{const n=await async function requestUpdateToken(e,t){const n=await getHeaders(e),r=getBody(t.subscriptionOptions),a={method:"PATCH",headers:n,body:JSON.stringify(r)};let o;try{const n=await fetch(`${getEndpoint(e.appConfig)}/${t.token}`,a);o=await n.json()}catch(e){throw C.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(o.error){const e=o.error.message;throw C.create("token-update-failed",{errorInfo:e})}if(!o.token)throw C.create("token-update-no-token");return o.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await dbSet(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:r.token,createTime:Date.now(),subscriptionOptions:n}):r.token;try{await requestDeleteToken(e.firebaseDependencies,r.token)}catch(e){console.warn(e)}return getNewToken(e.firebaseDependencies,n)}return getNewToken(e.firebaseDependencies,n)}async function deleteTokenInternal(e){const t=await dbGet(e.firebaseDependencies);t&&(await requestDeleteToken(e.firebaseDependencies,t.token),await async function dbRemove(e){const t=getKey(e),n=(await getDbPromise()).transaction(E,"readwrite");await n.objectStore(E).delete(t),await n.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function getNewToken(e,t){const n=await async function requestGetToken(e,t){const n=await getHeaders(e),r=getBody(t),a={method:"POST",headers:n,body:JSON.stringify(r)};let o;try{const t=await fetch(getEndpoint(e.appConfig),a);o=await t.json()}catch(e){throw C.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(o.error){const e=o.error.message;throw C.create("token-subscribe-failed",{errorInfo:e})}if(!o.token)throw C.create("token-subscribe-no-token");return o.token}(e,t),r={token:n,createTime:Date.now(),subscriptionOptions:t};return await dbSet(e,r),r.token}function externalizePayload(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function propagateNotificationPayload(e,t){if(!t.notification)return;e.notification={};const n=t.notification.title;n&&(e.notification.title=n);const r=t.notification.body;r&&(e.notification.body=r);const a=t.notification.image;a&&(e.notification.image=a);const o=t.notification.icon;o&&(e.notification.icon=o)}(t,e),function propagateDataPayload(e,t){if(!t.data)return;e.data=t.data}(t,e),function propagateFcmOptions(e,t){var n,r,a,o,i;if(!t.fcmOptions&&!(null===(n=t.notification)||void 0===n?void 0:n.click_action))return;e.fcmOptions={};const s=null!==(a=null===(r=t.fcmOptions)||void 0===r?void 0:r.link)&&void 0!==a?a:null===(o=t.notification)||void 0===o?void 0:o.click_action;s&&(e.fcmOptions.link=s);const c=null===(i=t.fcmOptions)||void 0===i?void 0:i.analytics_label;c&&(e.fcmOptions.analyticsLabel=c)}(t,e),t}function _mergeStrings(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function getMissingValueError(e){return C.create("missing-app-config-values",{valueName:e})}_mergeStrings("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),_mergeStrings("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class MessagingService{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;const r=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration Object");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:n}=e;for(const e of t)if(!n[e])throw getMissingValueError(e);return{appName:e.name,projectId:n.projectId,apiKey:n.apiKey,appId:n.appId,senderId:n.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function registerDefaultSw(e){try{e.swRegistration=await navigator.serviceWorker.register("/firebase-messaging-sw.js",{scope:"/firebase-cloud-messaging-push-scope"}),e.swRegistration.update().catch((()=>{}))}catch(e){throw C.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function getToken$1(e,t){if(!navigator)throw C.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw C.create("permission-blocked");return await async function updateVapidKey(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=I)}(e,null==t?void 0:t.vapidKey),await async function updateSwReg(e,t){if(t||e.swRegistration||await registerDefaultSw(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw C.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),getTokenInternal(e)}async function logToScion(e,t,n){const r=function getEventType(e){switch(e){case S.NOTIFICATION_CLICKED:return"notification_open";case S.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(r,{message_id:n["google.c.a.c_id"],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}const M="@firebase/messaging",WindowMessagingFactory=e=>{const t=new MessagingService(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",(e=>async function messageEventListener(e,t){const n=t.data;if(!n.isFirebaseMessaging)return;e.onMessageHandler&&n.messageType===S.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(externalizePayload(n)):e.onMessageHandler.next(externalizePayload(n)));const r=n.data;(function isConsoleMessage(e){return"object"==typeof e&&!!e&&"google.c.a.c_id"in e})(r)&&"1"===r["google.c.a.e"]&&await logToScion(e,n.messageType,r)}(t,e))),t},WindowMessagingInternalFactory=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>getToken$1(t,e)}};async function isWindowSupported(){try{await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(r);a.onsuccess=()=>{a.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},a.onupgradeneeded=()=>{n=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()}catch(e){return!1}return"undefined"!=typeof window&&function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&function areCookiesEnabled(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function getMessagingInWindow(e=n()){return isWindowSupported().then((e=>{if(!e)throw C.create("unsupported-browser")}),(e=>{throw C.create("indexed-db-unsupported")})),_getProvider(getModularInstance(e),"messaging").getImmediate()}async function getToken(e,t){return getToken$1(e=getModularInstance(e),t)}function deleteToken(e){return async function deleteToken$1(e){if(!navigator)throw C.create("only-available-in-window");return e.swRegistration||await registerDefaultSw(e),deleteTokenInternal(e)}(e=getModularInstance(e))}function onMessage(e,t){return function onMessage$1(e,t){if(!navigator)throw C.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=getModularInstance(e),t)}!function registerMessagingInWindow(){t(new Component("messaging",WindowMessagingFactory,"PUBLIC")),t(new Component("messaging-internal",WindowMessagingInternalFactory,"PRIVATE")),e(M,"0.12.10"),e(M,"0.12.10","esm2017")}();export{deleteToken,getMessagingInWindow as getMessaging,getToken,isWindowSupported as isSupported,onMessage}; | ||
//# sourceMappingURL=firebase-messaging.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,o=this.errors[e],a=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${a} (${i}).`;return new FirebaseError(i,s,n)}}const r=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],o=t[i];if(isObject(n)&&isObject(o)){if(!deepEqual(n,o))return!1}else if(n!==o)return!1}for(const e of r)if(!n.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 i;!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"}(i||(i={}));const o={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},a=i.INFO,s={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=s[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 c,u;const l=new WeakMap,p=new WeakMap,g=new WeakMap,d=new WeakMap,f=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return p.get(e);if("objectStoreNames"===t)return e.objectStoreNames||g.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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(l.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return g.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(p.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));p.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return c||(c=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,h):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&l.set(t,e)})).catch((()=>{})),f.set(t,e),t}(e);if(d.has(e))return d.get(e);const t=transformCachableValue(e);return t!==e&&(d.set(e,t),f.set(t,e)),t}const unwrap=e=>f.get(e);const m=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],b=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(b.get(t))return b.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!m.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let a=o.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),i&&o.done]))[0]};return b.set(t,method),method}!function replaceTraps(e){h=e(h)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const w="@firebase/installations",T=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 n=(await t.json()).error;return T.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.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 n=getHeaders(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 E=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return E.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const I=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!y&&"BroadcastChannel"in self&&(y=new BroadcastChannel("[Firebase] FID Change"),y.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return y}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===I.size&&y&&(y.close(),y=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=I.get(e);if(n)for(const e of n)e(t)}let y=null;const S="firebase-installations-store";let _=null;function getDbPromise(){return _||(_=function openDB(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const a=indexedDB.open(e,t),s=wrap(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(wrap(a.result),e.oldVersion,e.newVersion,wrap(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(S)}})),_}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),i=r.objectStore(S),o=await i.get(n);return await i.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(S,"readwrite");await n.objectStore(S).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),i=r.objectStore(S),o=await i.get(n),a=t(o);return void 0===a?await i.delete(n):await i.put(a,n),await r.done,!a||o&&o.fid===a.fid||fidChanged(e,a.fid),a}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),i=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(T.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),i=getHeaders(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw T.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),i=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw T.create("not-registered");const i=r.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+36e5}(e)}(i))return r;if(1===i.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw T.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw T.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return T.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(w,"0.6.8"),e(w,"0.6.8","esm2017");const A="@firebase/performance",k=new ErrorFactory("performance","Performance",{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"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."}),R=new class Logger{constructor(e){this.name=e,this._logLevel=a,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?o[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("Performance");let C,N,O,P;R.logLevel=i.INFO;class Api{constructor(e){if(this.window=e,!e)throw k.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)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}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}}()||(R.info("IndexedDB is not supported by current browser"),!1):(R.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 n of e.getEntries())t(n)})).observe({entryTypes:[e]})}static getInstance(){return void 0===C&&(C=new Api(N)),C}}function getIid(){return O}function mergeStrings(e,t){const n=e.length-t.length;if(n<0||n>1)throw k.create("invalid String merger input");const r=[];for(let n=0;n<e.length;n++)r.push(e.charAt(n)),t.length>n&&r.push(t.charAt(n));return r.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}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===P&&(P=new SettingsService),P}}var M;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VISIBLE=1]="VISIBLE",e[e.HIDDEN=2]="HIDDEN"}(M||(M={}));const D=["firebase_","google_","ga_"],L=new RegExp("^[a-zA-Z]\\w*$");function getServiceWorkerStatus(){const e=Api.getInstance().navigator;return(null==e?void 0:e.serviceWorker)?e.serviceWorker.controller?2:3:1}function getVisibilityState(){switch(Api.getInstance().document.visibilityState){case"visible":return M.VISIBLE;case"hidden":return M.HIDDEN;default:return M.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){var t;const n=null===(t=e.options)||void 0===t?void 0:t.appId;if(!n)throw k.create("no app id");return n}const F={loggingEnabled:!0};function getConfig(e,t){const n=function getStoredConfig(){const e=Api.getInstance().localStorage;if(!e)return;const t=e.getItem("@firebase/performance/configexpire");if(!t||!function configValid(e){return Number(e)>Date.now()}(t))return;const n=e.getItem("@firebase/performance/config");if(!n)return;try{return JSON.parse(n)}catch(e){return}}();return n?(processConfig(n),Promise.resolve()):function getRemoteConfig(e,t){return function getAuthTokenPromise(e){const t=e.getToken();return t.then((e=>{})),t}(e.installations).then((n=>{const r=function getProjectId(e){var t;const n=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!n)throw k.create("no project id");return n}(e.app),i=function getApiKey(e){var t;const n=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!n)throw k.create("no api key");return n}(e.app),o=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${r}/namespaces/fireperf:fetch?key=${i}`,{method:"POST",headers:{Authorization:`FIREBASE_INSTALLATIONS_AUTH ${n}`},body:JSON.stringify({app_instance_id:t,app_instance_id_token:n,app_id:getAppId(e.app),app_version:"0.6.8",sdk_version:"0.0.1"})});return fetch(o).then((e=>{if(e.ok)return e.json();throw k.create("RC response not ok")}))})).catch((()=>{R.info("Could not fetch config, will use default configs")}))}(e,t).then(processConfig).then((e=>function storeConfig(e){const t=Api.getInstance().localStorage;if(!e||!t)return;t.setItem("@firebase/performance/config",JSON.stringify(e)),t.setItem("@firebase/performance/configexpire",String(Date.now()+60*SettingsService.getInstance().configTimeToLive*60*1e3))}(e)),(()=>{}))}function processConfig(e){if(!e)return e;const t=SettingsService.getInstance(),n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=F.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):F.logSource&&(t.logSource=F.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:F.logEndPointUrl&&(t.logEndPointUrl=F.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:F.transportKey&&(t.transportKey=F.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==F.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=F.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==F.tracesSamplingRate&&(t.tracesSamplingRate=F.tracesSamplingRate),t.logTraceAfterSampling=shouldLogAfterSampling(t.tracesSamplingRate),t.logNetworkAfterSampling=shouldLogAfterSampling(t.networkRequestsSamplingRate),e}function shouldLogAfterSampling(e){return Math.random()<=e}let B,q=1;function getInitializationPromise(e){return q=2,B=B||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=>{O=e})),t}(e.installations))).then((t=>getConfig(e,t))).then((()=>changeInitializationStatus()),(()=>changeInitializationStatus()))}(e),B}function changeInitializationStatus(){q=3}let j,U=3,$=[],H=!1;function processQueue(e){setTimeout((()=>{if(0!==U)return $.length?void function dispatchQueueEvents(){const e=$.splice(0,1e3),t=e.map((e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})));(function sendEventsToFl(e,t){return function postToFlEndpoint(e){const t=SettingsService.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then((e=>(e.ok||R.info("Call to Firebase backend failed."),e.json()))).then((e=>{const n=Number(e.nextRequestWaitMillis);let r=1e4;isNaN(n)||(r=Math.max(n,r));const i=e.logResponseDetails;Array.isArray(i)&&i.length>0&&"RETRY_REQUEST_LATER"===i[0].responseAction&&($=[...t,...$],R.info("Retry transport request later.")),U=3,processQueue(r)}))})({request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:SettingsService.getInstance().logSource,log_event:t},e).catch((()=>{$=[...e,...$],U--,R.info(`Tries left: ${U}.`),processQueue(1e4)}))}():processQueue(1e4)}),e)}function transportHandler(e){return(...t)=>{!function addToQueue(e){if(!e.eventTime||!e.message)throw k.create("invalid cc log");$=[...$,e]}({message:e(...t),eventTime:Date.now()})}}function sendLog(e,t){j||(j=transportHandler(serializer)),j(e,t)}function logTrace(e){const t=SettingsService.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&Api.getInstance().requiredApisAvailable()&&(e.isAuto&&getVisibilityState()!==M.VISIBLE||(!function isPerfInitialized(){return 3===q}()?getInitializationPromise(e.performanceController).then((()=>sendTraceLog(e)),(()=>sendTraceLog(e))):sendTraceLog(e)))}function sendTraceLog(e){if(!getIid())return;const t=SettingsService.getInstance();t.loggingEnabled&&t.logTraceAfterSampling&&setTimeout((()=>sendLog(e,1)),0)}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},n={application_info:getApplicationInfo(e.performanceController.app),network_request_metric:t};return JSON.stringify(n)}(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 n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);const r={application_info:getApplicationInfo(e.performanceController.app),trace_metric:t};return JSON.stringify(r)}(e)}function getApplicationInfo(e){return{google_app_id:getAppId(e),app_instance_id:getIid(),web_app_info:{sdk_version:"0.6.8",page_url:Api.getInstance().getUrl(),service_worker_status:getServiceWorkerStatus(),visibility_state:getVisibilityState(),effective_connection_type:getEffectiveConnectionType()},application_process_state:0}}const V=["_fp","_fcp","_fid"];class Trace{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,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=r||`FB-PERF-TRACE-MEASURE-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw k.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw k.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,n){if(e<=0)throw k.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw k.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const e of Object.keys(n.metrics))isNaN(Number(n.metrics[e]))||(this.counters[e]=Math.floor(Number(n.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("_wt_")&&V.indexOf(e)>-1||!e.startsWith("_"))}(e,this.name))throw k.create("invalid custom metric name",{customMetricName:e});this.counters[e]=function convertMetricValueToInteger(e){const t=Math.floor(e);return t<e&&R.info(`Metric value should be an Integer, setting the value as : ${t}.`),t}(null!=t?t:0)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){const n=function isValidCustomAttributeName(e){return!(0===e.length||e.length>40)&&(!D.some((t=>e.startsWith(t)))&&!!e.match(L))}(e),r=function isValidCustomAttributeValue(e){return 0!==e.length&&e.length<=100}(t);if(n&&r)this.customAttributes[e]=t;else{if(!n)throw k.create("invalid attribute name",{attributeName:e});if(!r)throw k.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 Object.assign({},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,n,r){const i=Api.getInstance().getUrl();if(!i)return;const o=new Trace(e,"_wt_"+i,!0),a=Math.floor(1e3*Api.getInstance().getTimeOrigin());o.setStartTime(a),t&&t[0]&&(o.setDuration(Math.floor(1e3*t[0].duration)),o.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),o.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),o.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));if(n){const e=n.find((e=>"first-paint"===e.name));e&&e.startTime&&o.putMetric("_fp",Math.floor(1e3*e.startTime));const t=n.find((e=>"first-contentful-paint"===e.name));t&&t.startTime&&o.putMetric("_fcp",Math.floor(1e3*t.startTime)),r&&o.putMetric("_fid",Math.floor(1e3*r))}logTrace(o)}static createUserTimingTrace(e,t){logTrace(new Trace(e,t,!1,t))}}function createNetworkRequestEntry(e,t){const n=t;if(!n||void 0===n.responseStart)return;const r=Api.getInstance().getTimeOrigin(),i=Math.floor(1e3*(n.startTime+r)),o=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,a=Math.floor(1e3*(n.responseEnd-n.startTime));!function logNetworkRequest(e){const t=SettingsService.getInstance();if(!t.instrumentationEnabled)return;const n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0];n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout((()=>sendLog(e,0)),0)}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:i,timeToResponseInitiatedUs:o,timeToResponseCompletedUs:a})}function setupOobResources(e){getIid()&&(setTimeout((()=>function setupOobTraces(e){const t=Api.getInstance(),n=t.getEntriesByType("navigation"),r=t.getEntriesByType("paint");if(t.onFirstInputDelay){let i=setTimeout((()=>{Trace.createOobTrace(e,n,r),i=void 0}),5e3);t.onFirstInputDelay((t=>{i&&(clearTimeout(i),Trace.createOobTrace(e,n,r,t))}))}else Trace.createOobTrace(e,n,r)}(e)),0),setTimeout((()=>function setupNetworkRequests(e){const t=Api.getInstance(),n=t.getEntriesByType("resource");for(const t of n)createNetworkRequestEntry(e,t);t.setupObserver("resource",(t=>createNetworkRequestEntry(e,t)))}(e)),0),setTimeout((()=>function setupUserTimingTraces(e){const t=Api.getInstance(),n=t.getEntriesByType("measure");for(const t of n)createUserTimingTrace(e,t);t.setupObserver("measure",(t=>createUserTimingTrace(e,t)))}(e)),0))}function createUserTimingTrace(e,t){const n=t.name;"FB-PERF-TRACE-MEASURE"!==n.substring(0,"FB-PERF-TRACE-MEASURE".length)&&Trace.createUserTimingTrace(e,n)}class PerformanceController{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),Api.getInstance().requiredApisAvailable()?function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}().then((e=>{e&&(!function setupTransportService(){H||(processQueue(5500),H=!0)}(),getInitializationPromise(this).then((()=>setupOobResources(this)),(()=>setupOobResources(this))),this.initialized=!0)})).catch((e=>{R.info(`Environment doesn't support IndexedDB: ${e}`)})):R.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=n()){e=getModularInstance(e);return _getProvider(e,"performance").getImmediate()}function initializePerformance(e,t){e=getModularInstance(e);const n=_getProvider(e,"performance");if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(n.getOptions(),null!=t?t:{}))return e;throw k.create("already initialized")}return n.initialize({options:t})}function trace(e,t){return e=getModularInstance(e),new Trace(e,t)}const factory=(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("[DEFAULT]"!==n.name)throw k.create("FB not default");if("undefined"==typeof window)throw k.create("no window");!function setupApi(e){N=e}(window);const i=new PerformanceController(n,r);return i._init(t),i};!function registerPerformance(){t(new Component("performance",factory,"PUBLIC")),e(A,"0.6.8"),e(A,"0.6.8","esm2017")}();export{getPerformance,initializePerformance,trace}; | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,o=this.errors[e],a=o?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(o,n):"Error",s=`${this.serviceName}: ${a} (${i}).`;return new FirebaseError(i,s,n)}}const r=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],o=t[i];if(isObject(n)&&isObject(o)){if(!deepEqual(n,o))return!1}else if(n!==o)return!1}for(const e of r)if(!n.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 i;!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"}(i||(i={}));const o={debug:i.DEBUG,verbose:i.VERBOSE,info:i.INFO,warn:i.WARN,error:i.ERROR,silent:i.SILENT},a=i.INFO,s={[i.DEBUG]:"log",[i.VERBOSE]:"log",[i.INFO]:"info",[i.WARN]:"warn",[i.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=s[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,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 c,u;const l=new WeakMap,p=new WeakMap,g=new WeakMap,d=new WeakMap,f=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return p.get(e);if("objectStoreNames"===t)return e.objectStoreNames||g.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return wrap(e[t])},set:(e,t,n)=>(e[t]=n,!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(l.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const r=e.call(unwrap(this),t,...n);return g.set(r,t.sort?t.sort():[t]),wrap(r)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(p.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));p.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return c||(c=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,h):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&l.set(t,e)})).catch((()=>{})),f.set(t,e),t}(e);if(d.has(e))return d.get(e);const t=transformCachableValue(e);return t!==e&&(d.set(e,t),f.set(t,e)),t}const unwrap=e=>f.get(e);const m=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],b=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(b.get(t))return b.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!m.includes(n))return;const method=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let a=o.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),i&&o.done]))[0]};return b.set(t,method),method}!function replaceTraps(e){h=e(h)}((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const w="@firebase/installations",T=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 n=(await t.json()).error;return T.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.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 n=getHeaders(e);return n.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),n}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 E=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return E.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const I=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!y&&"BroadcastChannel"in self&&(y=new BroadcastChannel("[Firebase] FID Change"),y.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return y}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===I.size&&y&&(y.close(),y=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=I.get(e);if(n)for(const e of n)e(t)}let y=null;const S="firebase-installations-store";let _=null;function getDbPromise(){return _||(_=function openDB(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const a=indexedDB.open(e,t),s=wrap(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(wrap(a.result),e.oldVersion,e.newVersion,wrap(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{o&&e.addEventListener("close",(()=>o())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(S)}})),_}async function set(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),i=r.objectStore(S),o=await i.get(n);return await i.put(t,n),await r.done,o&&o.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(S,"readwrite");await n.objectStore(S).delete(t),await n.done}async function update(e,t){const n=getKey(e),r=(await getDbPromise()).transaction(S,"readwrite"),i=r.objectStore(S),o=await i.get(n),a=t(o);return void 0===a?await i.delete(n):await i.put(a,n),await r.done,!a||o&&o.fid===a.fid||fidChanged(e,a.fid),a}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const r=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(n),i=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(T.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=getInstallationsEndpoint(e),i=getHeaders(e),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={fid:n,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){const e=await c.json();return{fid:e.fid||n,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,n)}catch(n){throw isServerError(n)&&409===n.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,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:n}=await getInstallationEntry(e);return n||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw T.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const r=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),i=getHeadersWithAuth(e,n),o=t.getImmediate({optional:!0});if(o){const e=await o.getHeartbeatsHeader();e&&i.append("x-firebase-client",e)}const a={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},s={method:"POST",headers:i,body:JSON.stringify(a)},c=await retryIfServerError((()=>fetch(r,s)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const r=await update(e.appConfig,(r=>{if(!isEntryRegistered(r))throw T.create("not-registered");const i=r.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+36e5}(e)}(i))return r;if(1===i.requestStatus)return n=async function waitUntilAuthTokenRequest(e,t){let n=await updateAuthTokenRequest(e.appConfig);for(;1===n.authToken.requestStatus;)await sleep(100),n=await updateAuthTokenRequest(e.appConfig);const r=n.authToken;return 0===r.requestStatus?refreshAuthToken(e,t):r}(e,t),r;{if(!navigator.onLine)throw T.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(r);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),r=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,r),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:r.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw T.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const n=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(n);return(await refreshAuthToken(n,t)).token}function getMissingValueError(e){return T.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),n=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 n of t)if(!e.options[n])throw getMissingValueError(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),n=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:r}=await getInstallationEntry(t);return r?r.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(w,"0.6.8"),e(w,"0.6.8","esm2017");const A="@firebase/performance",k=new ErrorFactory("performance","Performance",{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"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."}),R=new class Logger{constructor(e){this.name=e,this._logLevel=a,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in i))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?o[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,i.DEBUG,...e),this._logHandler(this,i.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,i.VERBOSE,...e),this._logHandler(this,i.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,i.INFO,...e),this._logHandler(this,i.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,i.WARN,...e),this._logHandler(this,i.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,i.ERROR,...e),this._logHandler(this,i.ERROR,...e)}}("Performance");let C,N,O,P;R.logLevel=i.INFO;class Api{constructor(e){if(this.window=e,!e)throw k.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)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}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}}()||(R.info("IndexedDB is not supported by current browser"),!1):(R.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 n of e.getEntries())t(n)})).observe({entryTypes:[e]})}static getInstance(){return void 0===C&&(C=new Api(N)),C}}function getIid(){return O}function mergeStrings(e,t){const n=e.length-t.length;if(n<0||n>1)throw k.create("invalid String merger input");const r=[];for(let n=0;n<e.length;n++)r.push(e.charAt(n)),t.length>n&&r.push(t.charAt(n));return r.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}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===P&&(P=new SettingsService),P}}var M;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VISIBLE=1]="VISIBLE",e[e.HIDDEN=2]="HIDDEN"}(M||(M={}));const D=["firebase_","google_","ga_"],L=new RegExp("^[a-zA-Z]\\w*$");function getServiceWorkerStatus(){const e=Api.getInstance().navigator;return(null==e?void 0:e.serviceWorker)?e.serviceWorker.controller?2:3:1}function getVisibilityState(){switch(Api.getInstance().document.visibilityState){case"visible":return M.VISIBLE;case"hidden":return M.HIDDEN;default:return M.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){var t;const n=null===(t=e.options)||void 0===t?void 0:t.appId;if(!n)throw k.create("no app id");return n}const F={loggingEnabled:!0};function getConfig(e,t){const n=function getStoredConfig(){const e=Api.getInstance().localStorage;if(!e)return;const t=e.getItem("@firebase/performance/configexpire");if(!t||!function configValid(e){return Number(e)>Date.now()}(t))return;const n=e.getItem("@firebase/performance/config");if(!n)return;try{return JSON.parse(n)}catch(e){return}}();return n?(processConfig(n),Promise.resolve()):function getRemoteConfig(e,t){return function getAuthTokenPromise(e){const t=e.getToken();return t.then((e=>{})),t}(e.installations).then((n=>{const r=function getProjectId(e){var t;const n=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!n)throw k.create("no project id");return n}(e.app),i=function getApiKey(e){var t;const n=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!n)throw k.create("no api key");return n}(e.app),o=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${r}/namespaces/fireperf:fetch?key=${i}`,{method:"POST",headers:{Authorization:`FIREBASE_INSTALLATIONS_AUTH ${n}`},body:JSON.stringify({app_instance_id:t,app_instance_id_token:n,app_id:getAppId(e.app),app_version:"0.6.8",sdk_version:"0.0.1"})});return fetch(o).then((e=>{if(e.ok)return e.json();throw k.create("RC response not ok")}))})).catch((()=>{R.info("Could not fetch config, will use default configs")}))}(e,t).then(processConfig).then((e=>function storeConfig(e){const t=Api.getInstance().localStorage;if(!e||!t)return;t.setItem("@firebase/performance/config",JSON.stringify(e)),t.setItem("@firebase/performance/configexpire",String(Date.now()+60*SettingsService.getInstance().configTimeToLive*60*1e3))}(e)),(()=>{}))}function processConfig(e){if(!e)return e;const t=SettingsService.getInstance(),n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=F.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):F.logSource&&(t.logSource=F.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:F.logEndPointUrl&&(t.logEndPointUrl=F.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:F.transportKey&&(t.transportKey=F.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==F.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=F.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==F.tracesSamplingRate&&(t.tracesSamplingRate=F.tracesSamplingRate),t.logTraceAfterSampling=shouldLogAfterSampling(t.tracesSamplingRate),t.logNetworkAfterSampling=shouldLogAfterSampling(t.networkRequestsSamplingRate),e}function shouldLogAfterSampling(e){return Math.random()<=e}let B,q=1;function getInitializationPromise(e){return q=2,B=B||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=>{O=e})),t}(e.installations))).then((t=>getConfig(e,t))).then((()=>changeInitializationStatus()),(()=>changeInitializationStatus()))}(e),B}function changeInitializationStatus(){q=3}let j,U=3,$=[],H=!1;function processQueue(e){setTimeout((()=>{if(0!==U)return $.length?void function dispatchQueueEvents(){const e=$.splice(0,1e3),t=e.map((e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})));(function sendEventsToFl(e,t){return function postToFlEndpoint(e){const t=SettingsService.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then((e=>(e.ok||R.info("Call to Firebase backend failed."),e.json()))).then((e=>{const n=Number(e.nextRequestWaitMillis);let r=1e4;isNaN(n)||(r=Math.max(n,r));const i=e.logResponseDetails;Array.isArray(i)&&i.length>0&&"RETRY_REQUEST_LATER"===i[0].responseAction&&($=[...t,...$],R.info("Retry transport request later.")),U=3,processQueue(r)}))})({request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:SettingsService.getInstance().logSource,log_event:t},e).catch((()=>{$=[...e,...$],U--,R.info(`Tries left: ${U}.`),processQueue(1e4)}))}():processQueue(1e4)}),e)}function transportHandler(e){return(...t)=>{!function addToQueue(e){if(!e.eventTime||!e.message)throw k.create("invalid cc log");$=[...$,e]}({message:e(...t),eventTime:Date.now()})}}function sendLog(e,t){j||(j=transportHandler(serializer)),j(e,t)}function logTrace(e){const t=SettingsService.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&Api.getInstance().requiredApisAvailable()&&(e.isAuto&&getVisibilityState()!==M.VISIBLE||(!function isPerfInitialized(){return 3===q}()?getInitializationPromise(e.performanceController).then((()=>sendTraceLog(e)),(()=>sendTraceLog(e))):sendTraceLog(e)))}function sendTraceLog(e){if(!getIid())return;const t=SettingsService.getInstance();t.loggingEnabled&&t.logTraceAfterSampling&&setTimeout((()=>sendLog(e,1)),0)}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},n={application_info:getApplicationInfo(e.performanceController.app),network_request_metric:t};return JSON.stringify(n)}(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 n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);const r={application_info:getApplicationInfo(e.performanceController.app),trace_metric:t};return JSON.stringify(r)}(e)}function getApplicationInfo(e){return{google_app_id:getAppId(e),app_instance_id:getIid(),web_app_info:{sdk_version:"0.6.8",page_url:Api.getInstance().getUrl(),service_worker_status:getServiceWorkerStatus(),visibility_state:getVisibilityState(),effective_connection_type:getEffectiveConnectionType()},application_process_state:0}}const V=["_fp","_fcp","_fid"];class Trace{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,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=r||`FB-PERF-TRACE-MEASURE-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw k.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw k.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,n){if(e<=0)throw k.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw k.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const e of Object.keys(n.metrics))isNaN(Number(n.metrics[e]))||(this.counters[e]=Math.floor(Number(n.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("_wt_")&&V.indexOf(e)>-1||!e.startsWith("_"))}(e,this.name))throw k.create("invalid custom metric name",{customMetricName:e});this.counters[e]=function convertMetricValueToInteger(e){const t=Math.floor(e);return t<e&&R.info(`Metric value should be an Integer, setting the value as : ${t}.`),t}(null!=t?t:0)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){const n=function isValidCustomAttributeName(e){return!(0===e.length||e.length>40)&&(!D.some((t=>e.startsWith(t)))&&!!e.match(L))}(e),r=function isValidCustomAttributeValue(e){return 0!==e.length&&e.length<=100}(t);if(n&&r)this.customAttributes[e]=t;else{if(!n)throw k.create("invalid attribute name",{attributeName:e});if(!r)throw k.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 Object.assign({},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,n,r){const i=Api.getInstance().getUrl();if(!i)return;const o=new Trace(e,"_wt_"+i,!0),a=Math.floor(1e3*Api.getInstance().getTimeOrigin());o.setStartTime(a),t&&t[0]&&(o.setDuration(Math.floor(1e3*t[0].duration)),o.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),o.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),o.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));if(n){const e=n.find((e=>"first-paint"===e.name));e&&e.startTime&&o.putMetric("_fp",Math.floor(1e3*e.startTime));const t=n.find((e=>"first-contentful-paint"===e.name));t&&t.startTime&&o.putMetric("_fcp",Math.floor(1e3*t.startTime)),r&&o.putMetric("_fid",Math.floor(1e3*r))}logTrace(o)}static createUserTimingTrace(e,t){logTrace(new Trace(e,t,!1,t))}}function createNetworkRequestEntry(e,t){const n=t;if(!n||void 0===n.responseStart)return;const r=Api.getInstance().getTimeOrigin(),i=Math.floor(1e3*(n.startTime+r)),o=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,a=Math.floor(1e3*(n.responseEnd-n.startTime));!function logNetworkRequest(e){const t=SettingsService.getInstance();if(!t.instrumentationEnabled)return;const n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0];n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout((()=>sendLog(e,0)),0)}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:i,timeToResponseInitiatedUs:o,timeToResponseCompletedUs:a})}function setupOobResources(e){getIid()&&(setTimeout((()=>function setupOobTraces(e){const t=Api.getInstance(),n=t.getEntriesByType("navigation"),r=t.getEntriesByType("paint");if(t.onFirstInputDelay){let i=setTimeout((()=>{Trace.createOobTrace(e,n,r),i=void 0}),5e3);t.onFirstInputDelay((t=>{i&&(clearTimeout(i),Trace.createOobTrace(e,n,r,t))}))}else Trace.createOobTrace(e,n,r)}(e)),0),setTimeout((()=>function setupNetworkRequests(e){const t=Api.getInstance(),n=t.getEntriesByType("resource");for(const t of n)createNetworkRequestEntry(e,t);t.setupObserver("resource",(t=>createNetworkRequestEntry(e,t)))}(e)),0),setTimeout((()=>function setupUserTimingTraces(e){const t=Api.getInstance(),n=t.getEntriesByType("measure");for(const t of n)createUserTimingTrace(e,t);t.setupObserver("measure",(t=>createUserTimingTrace(e,t)))}(e)),0))}function createUserTimingTrace(e,t){const n=t.name;"FB-PERF-TRACE-MEASURE"!==n.substring(0,"FB-PERF-TRACE-MEASURE".length)&&Trace.createUserTimingTrace(e,n)}class PerformanceController{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),Api.getInstance().requiredApisAvailable()?function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}().then((e=>{e&&(!function setupTransportService(){H||(processQueue(5500),H=!0)}(),getInitializationPromise(this).then((()=>setupOobResources(this)),(()=>setupOobResources(this))),this.initialized=!0)})).catch((e=>{R.info(`Environment doesn't support IndexedDB: ${e}`)})):R.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=n()){e=getModularInstance(e);return _getProvider(e,"performance").getImmediate()}function initializePerformance(e,t){e=getModularInstance(e);const n=_getProvider(e,"performance");if(n.isInitialized()){const e=n.getImmediate();if(deepEqual(n.getOptions(),null!=t?t:{}))return e;throw k.create("already initialized")}return n.initialize({options:t})}function trace(e,t){return e=getModularInstance(e),new Trace(e,t)}const factory=(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("[DEFAULT]"!==n.name)throw k.create("FB not default");if("undefined"==typeof window)throw k.create("no window");!function setupApi(e){N=e}(window);const i=new PerformanceController(n,r);return i._init(t),i};!function registerPerformance(){t(new Component("performance",factory,"PUBLIC")),e(A,"0.6.8"),e(A,"0.6.8","esm2017")}();export{getPerformance,initializePerformance,trace}; | ||
//# sourceMappingURL=firebase-performance.js.map |
@@ -1,3 +0,3 @@ | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,s=this.errors[e],i=s?function replaceTemplate(e,t){return e.replace(a,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(s,r):"Error",o=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,o,r)}}const a=/\{\$([^}]+)}/g;function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),a=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+a)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 s;!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"}(s||(s={}));const i={debug:s.DEBUG,verbose:s.VERBOSE,info:s.INFO,warn:s.WARN,error:s.ERROR,silent:s.SILENT},o=s.INFO,c={[s.DEBUG]:"log",[s.VERBOSE]:"log",[s.INFO]:"info",[s.WARN]:"warn",[s.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),a=c[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${n}] ${e.name}:`,...r)};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 s))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[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,s.DEBUG,...e),this._logHandler(this,s.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,s.VERBOSE,...e),this._logHandler(this,s.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,s.INFO,...e),this._logHandler(this,s.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,s.WARN,...e),this._logHandler(this,s.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,s.ERROR,...e),this._logHandler(this,s.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,r){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||d.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!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,...r){const n=e.call(unwrap(this),t,...r);return d.set(n,t.sort?t.sort():[t]),wrap(n)}}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,r)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{r(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,r)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{r(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"],E=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(E.get(t))return E.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=v.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!w.includes(r))return;const method=async function(e,...t){const s=this.transaction(e,a?"readwrite":"readonly");let i=s.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[r](...t),a&&s.done]))[0]};return E.set(t,method),method}!function replaceTraps(e){m=e(m)}((e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)})));const y="@firebase/installations",I=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 r=(await t.json()).error;return I.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.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 r=getHeaders(e);return r.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),r}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 b=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return b.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const C=new Map;function fidChanged(e,t){const r=getKey(e);callFidChangeCallbacks(r,t),function broadcastFidChange(e,t){const r=function getBroadcastChannel(){!S&&"BroadcastChannel"in self&&(S=new BroadcastChannel("[Firebase] FID Change"),S.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return S}();r&&r.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===C.size&&S&&(S.close(),S=null)}()}(r,t)}function callFidChangeCallbacks(e,t){const r=C.get(e);if(r)for(const e of r)e(t)}let S=null;const T="firebase-installations-store";let _=null;function getDbPromise(){return _||(_=function openDB(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),o=wrap(i);return n&&i.addEventListener("upgradeneeded",(e=>{n(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),r&&i.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),o.then((e=>{s&&e.addEventListener("close",(()=>s())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(T)}})),_}async function set(e,t){const r=getKey(e),n=(await getDbPromise()).transaction(T,"readwrite"),a=n.objectStore(T),s=await a.get(r);return await a.put(t,r),await n.done,s&&s.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),r=(await getDbPromise()).transaction(T,"readwrite");await r.objectStore(T).delete(t),await r.done}async function update(e,t){const r=getKey(e),n=(await getDbPromise()).transaction(T,"readwrite"),a=n.objectStore(T),s=await a.get(r),i=t(s);return void 0===i?await a.delete(r):await a.put(i,r),await n.done,!i||s&&s.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const r=await update(e.appConfig,(r=>{const n=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(r),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(I.create("app-offline"))}}const r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function registerInstallation(e,t){try{const r=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:r}){const n=getInstallationsEndpoint(e),a=getHeaders(e),s=t.getImmediate({optional:!0});if(s){const e=await s.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:r,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},o={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(n,o)));if(c.ok){const e=await c.json();return{fid:e.fid||r,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,r)}catch(r){throw isServerError(r)&&409===r.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),r}}(e,r);return{installationEntry:r,registrationPromise:n}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,n);return t=a.registrationPromise,a.installationEntry}));return""===r.fid?{installationEntry:await t}:{installationEntry:r,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:r}=await getInstallationEntry(e);return r||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw I.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},r){const n=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,r),a=getHeadersWithAuth(e,r),s=t.getImmediate({optional:!0});if(s){const e=await s.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},o={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(n,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let r;const n=await update(e.appConfig,(n=>{if(!isEntryRegistered(n))throw I.create("not-registered");const a=n.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+36e5}(e)}(a))return n;if(1===a.requestStatus)return r=async function waitUntilAuthTokenRequest(e,t){let r=await updateAuthTokenRequest(e.appConfig);for(;1===r.authToken.requestStatus;)await sleep(100),r=await updateAuthTokenRequest(e.appConfig);const n=r.authToken;return 0===n.requestStatus?refreshAuthToken(e,t):n}(e,t),n;{if(!navigator.onLine)throw I.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(n);return r=async function fetchAuthTokenFromServer(e,t){try{const r=await generateAuthTokenRequest(e,t),n=Object.assign(Object.assign({},t),{authToken:r});return await set(e.appConfig,n),r}catch(r){if(!isServerError(r)||401!==r.customData.serverCode&&404!==r.customData.serverCode){const r=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,r)}else await remove(e.appConfig);throw r}}(e,t),t}}));return r?await r:n.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw I.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const r=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(r);return(await refreshAuthToken(r,t)).token}function getMissingValueError(e){return I.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),r=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 r of t)if(!e.options[r])throw getMissingValueError(r);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:r,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),r=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:r,registrationPromise:n}=await getInstallationEntry(t);return n?n.catch(console.error):refreshAuthToken(t).catch(console.error),r.fid}(r),getToken:e=>getToken(r,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(y,"0.6.8"),e(y,"0.6.8","esm2017");const F="@firebase/remote-config";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const M=new ErrorFactory("remoteconfig","Remote Config",{"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"});const k=["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&&k.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}}function getRemoteConfig(e=r()){e=getModularInstance(e);return _getProvider(e,"remote-config").getImmediate()}async function activate(e){const t=getModularInstance(e),[r,n]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(r&&r.config&&r.eTag&&r.eTag!==n)&&(await Promise.all([t._storageCache.setActiveConfig(r.config),t._storage.setActiveConfigEtag(r.eTag)]),!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),r=new RemoteConfigAbortSignal;setTimeout((async()=>{r.abort()}),t.settings.fetchTimeoutMillis);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:r}),await t._storageCache.setLastFetchStatus("success")}catch(e){const r=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(r),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys(Object.assign(Object.assign({},e),t))}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,r)=>(t[r]=getValue(e,r),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 r=getModularInstance(e);r._isInitializationComplete||r._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 n=r._storageCache.getActiveConfig();return n&&void 0!==n[t]?new Value("remote",n[t]):r.defaultConfig&&void 0!==r.defaultConfig[t]?new Value("default",String(r.defaultConfig[t])):(r._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 r=getModularInstance(e);switch(t){case"debug":r._logger.logLevel=s.DEBUG;break;case"silent":r._logger.logLevel=s.SILENT;break;default:r._logger.logLevel=s.ERROR}}class CachingClient{constructor(e,t,r,n){this.client=e,this.storage=t,this.storageCache=r,this.logger=n}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const r=Date.now()-t,n=r<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${r}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${n}.`),n}async fetch(e){const[t,r]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(r&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return r;e.eTag=r&&r.eTag;const n=await this.client.fetch(e),a=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&a.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(a),n}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,r,n,a,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=r,this.projectId=n,this.apiKey=a,this.appId=s}async fetch(e){const[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),n=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,a={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},s={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:getUserLanguage()},i={method:"POST",headers:a,body:JSON.stringify(s)},o=fetch(n,i),c=new Promise(((t,r)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",r(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),M.create(t,{originalErrorMessage:null==e?void 0:e.message})}let u=l.status;const g=l.headers.get("ETag")||void 0;let h,d;if(200===l.status){let e;try{e=await l.json()}catch(e){throw M.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}h=e.entries,d=e.state}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={}),304!==u&&200!==u)throw M.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h}}}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:r}){await function setAbortableTimeout(e,t){return new Promise(((r,n)=>{const a=Math.max(t-Date.now(),0),s=setTimeout(r,a);e.addEventListener((()=>{clearTimeout(s),n(M.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 n={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(r),backoffCount:r+1};return await this.storage.setThrottleMetadata(n),this.attemptFetch(e,n)}}}class RemoteConfig{constructor(e,t,r,n,a){this.app=e,this._client=t,this._storageCache=r,this._storage=n,this._logger=a,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function toFirebaseError(e,t){const r=e.target.error||void 0;return M.create(t,{originalErrorMessage:r&&(null==r?void 0:r.message)})}class Storage{constructor(e,t,r,n=function openDatabase(){return new Promise(((e,t)=>{try{const r=indexedDB.open("firebase_remote_config",1);r.onerror=e=>{t(toFirebaseError(e,"storage-open"))},r.onsuccess=t=>{e(t.target.result)},r.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore("app_namespace_store",{keyPath:"compositeKey"})}}catch(e){t(M.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}))}()){this.appId=e,this.appName=t,this.namespace=r,this.openDbPromise=n}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)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(e){const t=await this.openDbPromise;return new Promise(((r,n)=>{const a=t.transaction(["app_namespace_store"],"readonly").objectStore("app_namespace_store"),s=this.createCompositeKey(e);try{const e=a.get(s);e.onerror=e=>{n(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;r(t?t.value:void 0)}}catch(e){n(M.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}}))}async set(e,t){const r=await this.openDbPromise;return new Promise(((n,a)=>{const s=r.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),i=this.createCompositeKey(e);try{const e=s.put({compositeKey:i,value:t});e.onerror=e=>{a(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{n()}}catch(e){a(M.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}}))}async delete(e){const t=await this.openDbPromise;return new Promise(((r,n)=>{const a=t.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),s=this.createCompositeKey(e);try{const e=a.delete(s);e.onerror=e=>{n(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{r()}}catch(e){n(M.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),r=this.storage.getActiveConfig(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const s=await r;s&&(this.activeConfig=s)}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 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 r=!0;const n="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(n);a.onsuccess=()=>{a.result.close(),r||self.indexedDB.deleteDatabase(n),e(!0)},a.onupgradeneeded=()=>{r=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component("remote-config",(function remoteConfigFactory(e,{instanceIdentifier:t}){const r=e.getProvider("app").getImmediate(),a=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw M.create("registration-window");if(!isIndexedDBAvailable())throw M.create("indexed-db-unavailable");const{projectId:i,apiKey:o,appId:c}=r.options;if(!i)throw M.create("registration-project-id");if(!o)throw M.create("registration-api-key");if(!c)throw M.create("registration-app-id");t=t||"firebase";const l=new Storage(c,r.name,t),u=new StorageCache(l),g=new Logger(F);g.logLevel=s.ERROR;const h=new RestClient(a,n,t,i,o,c),d=new RetryingClient(h,l),f=new CachingClient(d,l,u,g),p=new RemoteConfig(r,f,u,l,g);return ensureInitialized(p),p}),"PUBLIC").setMultipleInstances(!0)),e(F,"0.4.8"),e(F,"0.4.8","esm2017")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,setLogLevel}; | ||
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,s=this.errors[e],i=s?function replaceTemplate(e,t){return e.replace(a,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(s,r):"Error",o=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,o,r)}}const a=/\{\$([^}]+)}/g;function calculateBackoffMillis(e,t=1e3,r=2){const n=t*Math.pow(r,e),a=Math.round(.5*n*(Math.random()-.5)*2);return Math.min(144e5,n+a)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 s;!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"}(s||(s={}));const i={debug:s.DEBUG,verbose:s.VERBOSE,info:s.INFO,warn:s.WARN,error:s.ERROR,silent:s.SILENT},o=s.INFO,c={[s.DEBUG]:"log",[s.VERBOSE]:"log",[s.INFO]:"info",[s.WARN]:"warn",[s.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),a=c[t];if(!a)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[a](`[${n}] ${e.name}:`,...r)};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 s))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[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,s.DEBUG,...e),this._logHandler(this,s.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,s.VERBOSE,...e),this._logHandler(this,s.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,s.INFO,...e),this._logHandler(this,s.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,s.WARN,...e),this._logHandler(this,s.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,s.ERROR,...e),this._logHandler(this,s.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,r){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||d.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!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,...r){const n=e.call(unwrap(this),t,...r);return d.set(n,t.sort?t.sort():[t]),wrap(n)}}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,r)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{r(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,r)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{r(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"],E=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(E.get(t))return E.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=v.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!w.includes(r))return;const method=async function(e,...t){const s=this.transaction(e,a?"readwrite":"readonly");let i=s.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[r](...t),a&&s.done]))[0]};return E.set(t,method),method}!function replaceTraps(e){m=e(m)}((e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)})));const y="@firebase/installations",I=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 r=(await t.json()).error;return I.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.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 r=getHeaders(e);return r.append("Authorization",function getAuthorizationHeader(e){return`FIS_v2 ${e}`}(t)),r}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 b=/^[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){return function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22)}(e);return b.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const C=new Map;function fidChanged(e,t){const r=getKey(e);callFidChangeCallbacks(r,t),function broadcastFidChange(e,t){const r=function getBroadcastChannel(){!S&&"BroadcastChannel"in self&&(S=new BroadcastChannel("[Firebase] FID Change"),S.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return S}();r&&r.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===C.size&&S&&(S.close(),S=null)}()}(r,t)}function callFidChangeCallbacks(e,t){const r=C.get(e);if(r)for(const e of r)e(t)}let S=null;const T="firebase-installations-store";let _=null;function getDbPromise(){return _||(_=function openDB(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),o=wrap(i);return n&&i.addEventListener("upgradeneeded",(e=>{n(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),r&&i.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),o.then((e=>{s&&e.addEventListener("close",(()=>s())),a&&e.addEventListener("versionchange",(e=>a(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(T)}})),_}async function set(e,t){const r=getKey(e),n=(await getDbPromise()).transaction(T,"readwrite"),a=n.objectStore(T),s=await a.get(r);return await a.put(t,r),await n.done,s&&s.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),r=(await getDbPromise()).transaction(T,"readwrite");await r.objectStore(T).delete(t),await r.done}async function update(e,t){const r=getKey(e),n=(await getDbPromise()).transaction(T,"readwrite"),a=n.objectStore(T),s=await a.get(r),i=t(s);return void 0===i?await a.delete(r):await a.put(i,r),await n.done,!i||s&&s.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const r=await update(e.appConfig,(r=>{const n=function updateOrCreateInstallationEntry(e){return clearTimedOutRequest(e||{fid:generateFid(),registrationStatus:0})}(r),a=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(I.create("app-offline"))}}const r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function registerInstallation(e,t){try{const r=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:r}){const n=getInstallationsEndpoint(e),a=getHeaders(e),s=t.getImmediate({optional:!0});if(s){const e=await s.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={fid:r,authVersion:"FIS_v2",appId:e.appId,sdkVersion:"w:0.6.8"},o={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(n,o)));if(c.ok){const e=await c.json();return{fid:e.fid||r,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,r)}catch(r){throw isServerError(r)&&409===r.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),r}}(e,r);return{installationEntry:r,registrationPromise:n}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,n);return t=a.registrationPromise,a.installationEntry}));return""===r.fid?{installationEntry:await t}:{installationEntry:r,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:r}=await getInstallationEntry(e);return r||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw I.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+1e4<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},r){const n=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,r),a=getHeadersWithAuth(e,r),s=t.getImmediate({optional:!0});if(s){const e=await s.getHeartbeatsHeader();e&&a.append("x-firebase-client",e)}const i={installation:{sdkVersion:"w:0.6.8",appId:e.appId}},o={method:"POST",headers:a,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(n,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let r;const n=await update(e.appConfig,(n=>{if(!isEntryRegistered(n))throw I.create("not-registered");const a=n.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+36e5}(e)}(a))return n;if(1===a.requestStatus)return r=async function waitUntilAuthTokenRequest(e,t){let r=await updateAuthTokenRequest(e.appConfig);for(;1===r.authToken.requestStatus;)await sleep(100),r=await updateAuthTokenRequest(e.appConfig);const n=r.authToken;return 0===n.requestStatus?refreshAuthToken(e,t):n}(e,t),n;{if(!navigator.onLine)throw I.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(n);return r=async function fetchAuthTokenFromServer(e,t){try{const r=await generateAuthTokenRequest(e,t),n=Object.assign(Object.assign({},t),{authToken:r});return await set(e.appConfig,n),r}catch(r){if(!isServerError(r)||401!==r.customData.serverCode&&404!==r.customData.serverCode){const r=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await set(e.appConfig,r)}else await remove(e.appConfig);throw r}}(e,t),t}}));return r?await r:n.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw I.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+1e4<Date.now()}(e.authToken)?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const r=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(r);return(await refreshAuthToken(r,t)).token}function getMissingValueError(e){return I.create("missing-app-config-values",{valueName:e})}const publicFactory=e=>{const t=e.getProvider("app").getImmediate(),r=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 r of t)if(!e.options[r])throw getMissingValueError(r);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:r,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),r=_getProvider(t,"installations").getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:r,registrationPromise:n}=await getInstallationEntry(t);return n?n.catch(console.error):refreshAuthToken(t).catch(console.error),r.fid}(r),getToken:e=>getToken(r,e)}};!function registerInstallations(){t(new Component("installations",publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(y,"0.6.8"),e(y,"0.6.8","esm2017");const F="@firebase/remote-config";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const M=new ErrorFactory("remoteconfig","Remote Config",{"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"});const k=["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&&k.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}}function getRemoteConfig(e=r()){e=getModularInstance(e);return _getProvider(e,"remote-config").getImmediate()}async function activate(e){const t=getModularInstance(e),[r,n]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(r&&r.config&&r.eTag&&r.eTag!==n)&&(await Promise.all([t._storageCache.setActiveConfig(r.config),t._storage.setActiveConfigEtag(r.eTag)]),!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),r=new RemoteConfigAbortSignal;setTimeout((async()=>{r.abort()}),t.settings.fetchTimeoutMillis);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:r}),await t._storageCache.setLastFetchStatus("success")}catch(e){const r=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(r),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys(Object.assign(Object.assign({},e),t))}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,r)=>(t[r]=getValue(e,r),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 r=getModularInstance(e);r._isInitializationComplete||r._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 n=r._storageCache.getActiveConfig();return n&&void 0!==n[t]?new Value("remote",n[t]):r.defaultConfig&&void 0!==r.defaultConfig[t]?new Value("default",String(r.defaultConfig[t])):(r._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 r=getModularInstance(e);switch(t){case"debug":r._logger.logLevel=s.DEBUG;break;case"silent":r._logger.logLevel=s.SILENT;break;default:r._logger.logLevel=s.ERROR}}class CachingClient{constructor(e,t,r,n){this.client=e,this.storage=t,this.storageCache=r,this.logger=n}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const r=Date.now()-t,n=r<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${r}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${n}.`),n}async fetch(e){const[t,r]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(r&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return r;e.eTag=r&&r.eTag;const n=await this.client.fetch(e),a=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&a.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(a),n}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,r,n,a,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=r,this.projectId=n,this.apiKey=a,this.appId=s}async fetch(e){const[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),n=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,a={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},s={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:getUserLanguage()},i={method:"POST",headers:a,body:JSON.stringify(s)},o=fetch(n,i),c=new Promise(((t,r)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",r(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),M.create(t,{originalErrorMessage:null==e?void 0:e.message})}let u=l.status;const g=l.headers.get("ETag")||void 0;let h,d;if(200===l.status){let e;try{e=await l.json()}catch(e){throw M.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}h=e.entries,d=e.state}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={}),304!==u&&200!==u)throw M.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h}}}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:r}){await function setAbortableTimeout(e,t){return new Promise(((r,n)=>{const a=Math.max(t-Date.now(),0),s=setTimeout(r,a);e.addEventListener((()=>{clearTimeout(s),n(M.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 n={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(r),backoffCount:r+1};return await this.storage.setThrottleMetadata(n),this.attemptFetch(e,n)}}}class RemoteConfig{constructor(e,t,r,n,a){this.app=e,this._client=t,this._storageCache=r,this._storage=n,this._logger=a,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function toFirebaseError(e,t){const r=e.target.error||void 0;return M.create(t,{originalErrorMessage:r&&(null==r?void 0:r.message)})}class Storage{constructor(e,t,r,n=function openDatabase(){return new Promise(((e,t)=>{try{const r=indexedDB.open("firebase_remote_config",1);r.onerror=e=>{t(toFirebaseError(e,"storage-open"))},r.onsuccess=t=>{e(t.target.result)},r.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore("app_namespace_store",{keyPath:"compositeKey"})}}catch(e){t(M.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}))}()){this.appId=e,this.appName=t,this.namespace=r,this.openDbPromise=n}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)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(e){const t=await this.openDbPromise;return new Promise(((r,n)=>{const a=t.transaction(["app_namespace_store"],"readonly").objectStore("app_namespace_store"),s=this.createCompositeKey(e);try{const e=a.get(s);e.onerror=e=>{n(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;r(t?t.value:void 0)}}catch(e){n(M.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}}))}async set(e,t){const r=await this.openDbPromise;return new Promise(((n,a)=>{const s=r.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),i=this.createCompositeKey(e);try{const e=s.put({compositeKey:i,value:t});e.onerror=e=>{a(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{n()}}catch(e){a(M.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}}))}async delete(e){const t=await this.openDbPromise;return new Promise(((r,n)=>{const a=t.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),s=this.createCompositeKey(e);try{const e=a.delete(s);e.onerror=e=>{n(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{r()}}catch(e){n(M.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),r=this.storage.getActiveConfig(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const s=await r;s&&(this.activeConfig=s)}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 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 r=!0;const n="validate-browser-context-for-indexeddb-analytics-module",a=self.indexedDB.open(n);a.onsuccess=()=>{a.result.close(),r||self.indexedDB.deleteDatabase(n),e(!0)},a.onupgradeneeded=()=>{r=!1},a.onerror=()=>{var e;t((null===(e=a.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component("remote-config",(function remoteConfigFactory(e,{instanceIdentifier:t}){const r=e.getProvider("app").getImmediate(),a=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw M.create("registration-window");if(!isIndexedDBAvailable())throw M.create("indexed-db-unavailable");const{projectId:i,apiKey:o,appId:c}=r.options;if(!i)throw M.create("registration-project-id");if(!o)throw M.create("registration-api-key");if(!c)throw M.create("registration-app-id");t=t||"firebase";const l=new Storage(c,r.name,t),u=new StorageCache(l),g=new Logger(F);g.logLevel=s.ERROR;const h=new RestClient(a,n,t,i,o,c),d=new RetryingClient(h,l),f=new CachingClient(d,l,u,g),p=new RemoteConfig(r,f,u,l,g);return ensureInitialized(p),p}),"PUBLIC").setMultipleInstances(!0)),e(F,"0.4.8"),e(F,"0.4.8","esm2017")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,setLogLevel}; | ||
//# sourceMappingURL=firebase-remote-config.js.map |
@@ -1,3 +0,3 @@ | ||
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t},o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=o>>2,u=(3&o)<<4|i>>4;let h=(15&i)<<2|l>>6,d=63&l;a||(d=64,s||(h=64)),n.push(r[c],r[u],r[h],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],i=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const i=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const l=o<<2|s>>4;if(n.push(l),64!==i){const e=s<<4&240|i>>2;if(n.push(e),64!==a){const e=i<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return o.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,r;return null===(r=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===r?void 0:r[e]})(e);if(!t)return;const r=t.lastIndexOf(":");if(r<=0||r+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const n=parseInt(t.substring(r+1),10);return"["===t[0]?[t.substring(1,r-1),n]:[t.substring(0,r),n]};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(s,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(o,r):"Error",a=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,a,r)}}const s=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}class StorageError extends FirebaseError{constructor(e,t,r=0){super(prependCode(e),`Firebase Storage: ${t} (${prependCode(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var i,a;function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(i.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(i.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(i.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(i.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(i.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(i.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new StorageError(i.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new StorageError(i.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new StorageError(i.INTERNAL_ERROR,"Internal error: "+e)}!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(i||(i={}));class Location{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Location.makeFromUrl(e,t)}catch(t){return new Location(e,"")}if(""===r.path)return r;throw function invalidDefaultBucket(e){return new StorageError(i.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}(e)}static makeFromUrl(e,t){let r=null;const n="([A-Za-z0-9.\\-_]+)";const o=new RegExp("^gs://"+n+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}const s=t.replace(/[.]/g,"\\."),a=[{regex:o,indices:{bucket:1,path:3},postModify:function gsModify(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${s}/v[A-Za-z0-9_]+/b/${n}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:httpModify},{regex:new RegExp(`^https?://${"firebasestorage.googleapis.com"===t?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${n}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:httpModify}];for(let t=0;t<a.length;t++){const n=a[t],o=n.regex.exec(e);if(o){const e=o[n.indices.bucket];let t=o[n.indices.path];t||(t=""),r=new Location(e,t),n.postModify(r);break}}if(null==r)throw function invalidUrl(e){return new StorageError(i.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return r}}class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,t,r,n){if(n<t)throw invalidArgument(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n>r)throw invalidArgument(`Invalid value for '${e}'. Expected ${r} or less.`)}function makeUrl(e,t,r){let n=t;return null==r&&(n=`https://${t}`),`${r}://${n}/v0${e}`}function makeQueryString(e){const t=encodeURIComponent;let r="?";for(const n in e)if(e.hasOwnProperty(n)){r=r+(t(n)+"="+t(e[n]))+"&"}return r=r.slice(0,-1),r}function isRetryStatusCode(e,t){const r=e>=500&&e<600,n=-1!==[408,429].indexOf(e),o=-1!==t.indexOf(e);return r||n||o}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(a||(a={}));class NetworkRequest{constructor(e,t,r,n,o,s,i,a,l,c,u,h=!0){this.url_=e,this.method_=t,this.headers_=r,this.body_=n,this.successCodes_=o,this.additionalRetryCodes_=s,this.callback_=i,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const doTheRequest=(e,t)=>{if(t)return void e(!1,new RequestEndStatus(!1,null,!0));const r=this.connectionFactory_();this.pendingConnection_=r;const progressListener=e=>{const t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)};null!==this.progressCallback_&&r.addUploadProgressListener(progressListener),r.send(this.url_,this.method_,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(progressListener),this.pendingConnection_=null;const t=r.getErrorCode()===a.NO_ERROR,n=r.getStatus();if(!t||isRetryStatusCode(n,this.additionalRetryCodes_)&&this.retry){const t=r.getErrorCode()===a.ABORT;return void e(!1,new RequestEndStatus(!1,null,t))}const o=-1!==this.successCodes_.indexOf(n);e(!0,new RequestEndStatus(o,r))}))},backoffDone=(e,t)=>{const r=this.resolve_,n=this.reject_,o=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(o,o.getResponse());!function isJustDef(e){return void 0!==e}(e)?r():r(e)}catch(e){n(e)}else if(null!==o){const e=unknown();e.serverResponse=o.getErrorText(),this.errorCallback_?n(this.errorCallback_(o,e)):n(e)}else if(t.canceled){n(this.appDelete_?appDeleted():canceled())}else{n(retryLimitExceeded())}};this.canceled_?backoffDone(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=function start(e,t,r){let n=1,o=null,s=null,i=!1,a=0;function canceled(){return 2===a}let l=!1;function triggerCallback(...e){l||(l=!0,t.apply(null,e))}function callWithDelay(t){o=setTimeout((()=>{o=null,e(responseHandler,canceled())}),t)}function clearGlobalTimeout(){s&&clearTimeout(s)}function responseHandler(e,...t){if(l)return void clearGlobalTimeout();if(e)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);if(canceled()||i)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);let r;n<64&&(n*=2),1===a?(a=2,r=0):r=1e3*(n+Math.random()),callWithDelay(r)}let c=!1;function stop(e){c||(c=!0,clearGlobalTimeout(),l||(null!==o?(e||(a=2),clearTimeout(o),callWithDelay(0)):e||(a=1)))}return callWithDelay(0),s=setTimeout((()=>{i=!0,stop(!0)}),r),stop}(doTheRequest,backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function stop(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class RequestEndStatus{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob$1(...e){const t=getBlobBuilder();if(void 0!==t){const r=new t;for(let t=0;t<e.length;t++)r.append(e[t]);return r.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(i.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function decodeBase64(e){if("undefined"==typeof atob)throw function missingPolyFill(e){return new StorageError(i.UNSUPPORTED_ENVIRONMENT,`${e} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}("base-64");return atob(e)}const l={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class StringData{constructor(e,t){this.data=e,this.contentType=t||null}}function dataFromString(e,t){switch(e){case l.RAW:return new StringData(utf8Bytes_(t));case l.BASE64:case l.BASE64URL:return new StringData(base64Bytes_(e,t));case l.DATA_URL:return new StringData(function dataURLBytes_(e){const t=new DataURLParts(e);return t.base64?base64Bytes_(l.BASE64,t.rest):function percentEncodedBytes_(e){let t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(l.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}(t.rest)}(t),function dataURLContentType_(e){return new DataURLParts(e).contentType}(t))}throw unknown()}function utf8Bytes_(e){const t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<=127)t.push(n);else if(n<=2047)t.push(192|n>>6,128|63&n);else if(55296==(64512&n)){if(r<e.length-1&&56320==(64512&e.charCodeAt(r+1))){n=65536|(1023&n)<<10|1023&e.charCodeAt(++r),t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}else t.push(239,191,189)}else 56320==(64512&n)?t.push(239,191,189):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function base64Bytes_(e,t){switch(e){case l.BASE64:{const r=-1!==t.indexOf("-"),n=-1!==t.indexOf("_");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?")}break}case l.BASE64URL:{const r=-1!==t.indexOf("+"),n=-1!==t.indexOf("/");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let r;try{r=decodeBase64(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw invalidFormat(e,"Invalid character found")}const n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(l.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;null!=r&&(this.base64=function endsWith(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-";base64".length):r),this.rest=e.substring(e.indexOf(",")+1)}}class FbsBlob{constructor(e,t){let r=0,n="";isNativeBlob(e)?(this.data_=e,r=e.size,n=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=n}size(){return this.size_}type(){return this.type_}slice(e,t){if(isNativeBlob(this.data_)){const r=function sliceBlob(e,t,r){return e.webkitSlice?e.webkitSlice(t,r):e.mozSlice?e.mozSlice(t,r):e.slice?e.slice(t,r):null}(this.data_,e,t);return null===r?null:new FbsBlob(r)}{const r=new Uint8Array(this.data_.buffer,e,t-e);return new FbsBlob(r,!0)}}static getBlob(...e){if(isNativeBlobDefined()){const t=e.map((e=>e instanceof FbsBlob?e.data_:e));return new FbsBlob(getBlob$1.apply(null,t))}{const t=e.map((e=>isString(e)?dataFromString(l.RAW,e).data:e.data_));let r=0;t.forEach((e=>{r+=e.byteLength}));const n=new Uint8Array(r);let o=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)n[o++]=e[t]})),new FbsBlob(n,!0)}}uploadData(){return this.data_}}function jsonObjectOrNull(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function isNonArrayObject(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}function lastComponent(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function noXform_(e,t){return t}class Mapping{constructor(e,t,r,n){this.server=e,this.local=t||e,this.writable=!!r,this.xform=n||noXform_}}let c=null;function getMappings(){if(c)return c;const e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));const t=new Mapping("name");t.xform=function mappingsXformPath(e,t){return function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e)}(t)},e.push(t);const r=new Mapping("size");return r.xform=function xformSize(e,t){return void 0!==t?Number(t):t},e.push(r),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),c=e,c}function fromResource(e,t,r){const n={type:"file"},o=r.length;for(let e=0;e<o;e++){const o=r[e];n[o.local]=o.xform(n,t[o.server])}return function addRef(e,t){Object.defineProperty(e,"ref",{get:function generateRef(){const r=e.bucket,n=e.fullPath,o=new Location(r,n);return t._makeStorageReference(o)}})}(n,e),n}function fromResourceString(e,t,r){const n=jsonObjectOrNull(t);if(null===n)return null;return fromResource(e,n,r)}function toResourceString(e,t){const r={},n=t.length;for(let o=0;o<n;o++){const n=t[o];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}function fromResponseString(e,t,r){const n=jsonObjectOrNull(r);if(null===n)return null;return function fromBackendResponse(e,t,r){const n={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r.prefixes)for(const o of r.prefixes){const r=o.replace(/\/$/,""),s=e._makeStorageReference(new Location(t,r));n.prefixes.push(s)}if(r.items)for(const o of r.items){const r=e._makeStorageReference(new Location(t,o.name));n.items.push(r)}return n}(e,t,n)}class RequestInfo{constructor(e,t,r,n){this.url=e,this.method=t,this.handler=r,this.timeout=n,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),o}}function downloadUrlHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),function downloadUrlFromResourceString(e,t,r,n){const o=jsonObjectOrNull(t);if(null===o)return null;if(!isString(o.downloadTokens))return null;const s=o.downloadTokens;if(0===s.length)return null;const i=encodeURIComponent;return s.split(",").map((t=>{const o=e.bucket,s=e.fullPath;return makeUrl("/b/"+i(o)+"/o/"+i(s),r,n)+makeQueryString({alt:"media",token:t})}))[0]}(o,n,e.host,e._protocol)}}function sharedErrorHandler(e){return function errorHandler(t,r){let n;return n=401===t.getStatus()?t.getErrorText().includes("Firebase App Check token is invalid")?function unauthorizedApp(){return new StorageError(i.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}():function unauthenticated(){return new StorageError(i.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}():402===t.getStatus()?function quotaExceeded(e){return new StorageError(i.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}(e.bucket):403===t.getStatus()?function unauthorized(e){return new StorageError(i.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}(e.path):r,n.status=t.getStatus(),n.serverResponse=r.serverResponse,n}}function objectErrorHandler(e){const t=sharedErrorHandler(e);return function errorHandler(r,n){let o=t(r,n);return 404===r.getStatus()&&(o=function objectNotFound(e){return new StorageError(i.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}(e.path)),o.serverResponse=n.serverResponse,o}}function getMetadata$2(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",metadataHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}function list$2(e,t,r,n,o){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",r&&r.length>0&&(s.delimiter=r),n&&(s.pageToken=n),o&&(s.maxResults=o);const i=makeUrl(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,l=new RequestInfo(i,"GET",function listHandler(e,t){return function handler(r,n){const o=fromResponseString(e,t,n);return handlerCheck(null!==o),o}}(e,t.bucket),a);return l.urlParams=s,l.errorHandler=sharedErrorHandler(t),l}function getBytes$1(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol)+"?alt=media",o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",((e,t)=>t),o);return s.errorHandler=objectErrorHandler(t),void 0!==r&&(s.headers.Range=`bytes=0-${r}`,s.successCodes=[200,206]),s}function metadataForUpload_(e,t,r){const n=Object.assign({},r);return n.fullPath=e.path,n.size=t.size(),n.contentType||(n.contentType=function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),n}function multipartUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};const a=function genBoundary(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();i["Content-Type"]="multipart/related; boundary="+a;const l=metadataForUpload_(t,n,o),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(l,r)+"\r\n--"+a+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",u="\r\n--"+a+"--",h=FbsBlob.getBlob(c,n,u);if(null===h)throw cannotSliceBlob();const d={name:l.fullPath},p=makeUrl(s,e.host,e._protocol),_=e.maxUploadRetryTime,f=new RequestInfo(p,"POST",metadataHandler(e,r),_);return f.urlParams=d,f.headers=i,f.body=h.uploadData(),f.errorHandler=sharedErrorHandler(t),f}class ResumableUploadStatus{constructor(e,t,r,n){this.current=e,this.total=t,this.finalized=!!r,this.metadata=n||null}}function checkResumeHeader_(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!r&&-1!==(t||["active"]).indexOf(r)),r}function continueResumableUpload(e,t,r,n,o,s,a,l){const c=new ResumableUploadStatus(0,0);if(a?(c.current=a.current,c.total=a.total):(c.current=0,c.total=n.size()),n.size()!==c.total)throw function serverFileWrongSize(){return new StorageError(i.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}();const u=c.total-c.current;let h=u;o>0&&(h=Math.min(h,o));const d=c.current,p=d+h;let _="";_=0===h?"finalize":u===h?"upload, finalize":"upload";const f={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${c.current}`},g=n.slice(d,p);if(null===g)throw cannotSliceBlob();const m=t.maxUploadRetryTime,b=new RequestInfo(r,"POST",(function handler(e,r){const o=checkResumeHeader_(e,["active","final"]),i=c.current+h,a=n.size();let l;return l="final"===o?metadataHandler(t,s)(e,r):null,new ResumableUploadStatus(i,a,"final"===o,l)}),m);return b.headers=f,b.body=g.uploadData(),b.progressCallback=l||null,b.errorHandler=sharedErrorHandler(e),b}const u={STATE_CHANGED:"state_changed"},h={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return h.RUNNING;case"paused":return h.PAUSED;case"success":return h.SUCCESS;case"canceled":return h.CANCELED;default:return h.ERROR}}class Observer{constructor(e,t,r){if(function isFunction(e){return"function"==typeof e}(e)||null!=t||null!=r)this.next=e,this.error=null!=t?t:void 0,this.complete=null!=r?r:void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}function async(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=a.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=a.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=a.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,r,n){if(this.sent_)throw internalError("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(const e in n)n.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,n[e].toString());return void 0!==r?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}}function newTextConnection(){return new XhrTextConnection}class XhrBytesConnection extends XhrConnection{initXhr(){this.xhr_.responseType="arraybuffer"}}function newBytesConnection(){return new XhrBytesConnection}class XhrBlobConnection extends XhrConnection{initXhr(){this.xhr_.responseType="blob"}}function newBlobConnection(){return new XhrBlobConnection}class UploadTask{constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(i.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=retryLimitExceeded()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(i.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,r])=>{switch(this._state){case"running":e(t,r);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const r=function createResumableUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i=metadataForUpload_(t,n,o),a={name:i.fullPath},l=makeUrl(s,e.host,e._protocol),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},u=toResourceString(i,r),h=e.maxUploadRetryTime,d=new RequestInfo(l,"POST",(function handler(e){let t;checkResumeHeader_(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(t)),t}),h);return d.urlParams=a,d.headers=c,d.body=u,d.errorHandler=sharedErrorHandler(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,r)=>{const n=function getResumableUploadStatus(e,t,r,n){const o=e.maxUploadRetryTime,s=new RequestInfo(r,"POST",(function handler(e){const t=checkResumeHeader_(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}r||handlerCheck(!1);const o=Number(r);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,n.size(),"final"===t)}),o);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=sharedErrorHandler(t),s}(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(n,newTextConnection,t,r);this._request=o,o.getPromise().then((e=>{e=e,this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=262144*this._chunkMultiplier,t=new ResumableUploadStatus(this._transferred,this._blob.size()),r=this._uploadUrl;this._resolveToken(((n,o)=>{let s;try{s=continueResumableUpload(this._ref._location,this._ref.storage,r,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const i=this._ref.storage._makeRequest(s,newTextConnection,n,o,!1);this._request=i,i.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const r=getMetadata$2(this._ref.storage,this._ref._location,this._mappings),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const r=multipartUpload(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,n){const o=new Observer(t||void 0,r||void 0,n||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case h.SUCCESS:async(this._resolve.bind(null,this.snapshot))();break;case h.CANCELED:case h.ERROR:async(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(taskStateFromInternalTaskState(this._state)){case h.RUNNING:case h.PAUSED:e.next&&async(e.next.bind(e,this.snapshot))();break;case h.SUCCESS:e.complete&&async(e.complete.bind(e))();break;default:e.error&&async(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Reference{constructor(e,t){this._service=e,this._location=t instanceof Location?t:Location.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Reference(e,t)}get root(){const e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){const e=function parent(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;const t=new Location(this._location.bucket,e);return new Reference(this._service,t)}_throwIfRoot(e){if(""===this._location.path)throw invalidRootOperation(e)}}function uploadBytes$1(e,t,r){e._throwIfRoot("uploadBytes");const n=multipartUpload(e.storage,e._location,getMappings(),new FbsBlob(t,!0),r);return e.storage.makeRequestWithTokens(n,newTextConnection).then((t=>({metadata:t,ref:e})))}function listAll$1(e){const t={prefixes:[],items:[]};return listAllHelper(e,t).then((()=>t))}async function listAllHelper(e,t,r){const n={pageToken:r},o=await list$1(e,n);t.prefixes.push(...o.prefixes),t.items.push(...o.items),null!=o.nextPageToken&&await listAllHelper(e,t,o.nextPageToken)}function list$1(e,t){null!=t&&"number"==typeof t.maxResults&&validateNumber("options.maxResults",1,1e3,t.maxResults);const r=t||{},n=list$2(e.storage,e._location,"/",r.pageToken,r.maxResults);return e.storage.makeRequestWithTokens(n,newTextConnection)}function updateMetadata$1(e,t){e._throwIfRoot("updateMetadata");const r=function updateMetadata$2(e,t,r,n){const o=makeUrl(t.fullServerUrl(),e.host,e._protocol),s=toResourceString(r,n),i=e.maxOperationRetryTime,a=new RequestInfo(o,"PATCH",metadataHandler(e,n),i);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=objectErrorHandler(t),a}(e.storage,e._location,t,getMappings());return e.storage.makeRequestWithTokens(r,newTextConnection)}function getDownloadURL$1(e){e._throwIfRoot("getDownloadURL");const t=function getDownloadUrl(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",downloadUrlHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection).then((e=>{if(null===e)throw function noDownloadURL(){return new StorageError(i.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}();return e}))}function deleteObject$1(e){e._throwIfRoot("deleteObject");const t=function deleteObject$2(e,t){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime,o=new RequestInfo(r,"DELETE",(function handler(e,t){}),n);return o.successCodes=[200,204],o.errorHandler=objectErrorHandler(t),o}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,newTextConnection)}function _getChild$1(e,t){const r=function child(e,t){const r=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?r:e+"/"+r}(e._location.path,t),n=new Location(e._location.bucket,r);return new Reference(e.storage,n)}function refFromPath(e,t){if(e instanceof FirebaseStorageImpl){const r=e;if(null==r._bucket)throw function noDefaultBucket(){return new StorageError(i.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the 'storageBucket' property when initializing the app?")}();const n=new Reference(r,r._bucket);return null!=t?refFromPath(n,t):n}return void 0!==t?_getChild$1(e,t):e}function ref$1(e,t){if(t&&function isUrl(e){return/^[A-Za-z]+:\/\//.test(e)}(t)){if(e instanceof FirebaseStorageImpl)return function refFromURL(e,t){return new Reference(e,t)}(e,t);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}return refFromPath(e,t)}function extractBucket(e,t){const r=null==t?void 0:t.storageBucket;return null==r?null:Location.makeFromBucketSpec(r,e)}function connectStorageEmulator$1(e,t,r,n={}){e.host=`${t}:${r}`,e._protocol="http";const{mockUserToken:o}=n;o&&(e._overrideAuthToken="string"==typeof o?o:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=t||"demo-project",n=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:n,exp:n+3600,auth_time:n,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(o,e.app.options.projectId))}class FirebaseStorageImpl{constructor(e,t,r,n,o){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=n,this._firebaseVersion=o,this._bucket=null,this._host="firebasestorage.googleapis.com",this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=n?Location.makeFromBucketSpec(n,this._host):extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,t,r,n,o=!0){if(this._deleted)return new FailRequest(appDeleted());{const s=function makeRequest(e,t,r,n,o,s,i=!0){const a=makeQueryString(e.urlParams),l=e.url+a,c=Object.assign({},e.headers);return function addGmpidHeader_(e,t){t&&(e["X-Firebase-GMPID"]=t)}(c,t),function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(c,r),function addVersionHeader_(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(null!=t?t:"AppManager")}(c,s),function addAppCheckHeader_(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(c,n),new NetworkRequest(l,e.method,c,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,o,i)}(e,this._appId,r,n,t,this._firebaseVersion,o);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[r,n]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,n).getPromise()}}const d="@firebase/storage";function getBytes(e,t){return function getBytesInternal(e,t){e._throwIfRoot("getBytes");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBytesConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function uploadBytes(e,t,r){return uploadBytes$1(e=getModularInstance(e),t,r)}function uploadString(e,t,r,n){return function uploadString$1(e,t,r=l.RAW,n){e._throwIfRoot("uploadString");const o=dataFromString(r,t),s=Object.assign({},n);return null==s.contentType&&null!=o.contentType&&(s.contentType=o.contentType),uploadBytes$1(e,o.data,s)}(e=getModularInstance(e),t,r,n)}function uploadBytesResumable(e,t,r){return function uploadBytesResumable$1(e,t,r){return e._throwIfRoot("uploadBytesResumable"),new UploadTask(e,new FbsBlob(t),r)}(e=getModularInstance(e),t,r)}function getMetadata(e){return function getMetadata$1(e){e._throwIfRoot("getMetadata");const t=getMetadata$2(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection)}(e=getModularInstance(e))}function updateMetadata(e,t){return updateMetadata$1(e=getModularInstance(e),t)}function list(e,t){return list$1(e=getModularInstance(e),t)}function listAll(e){return listAll$1(e=getModularInstance(e))}function getDownloadURL(e){return getDownloadURL$1(e=getModularInstance(e))}function deleteObject(e){return deleteObject$1(e=getModularInstance(e))}function ref(e,t){return ref$1(e=getModularInstance(e),t)}function _getChild(e,t){return _getChild$1(e,t)}function getStorage(t=e(),r){t=getModularInstance(t);const n=_getProvider(t,"storage").getImmediate({identifier:r}),o=getDefaultEmulatorHostnameAndPort("storage");return o&&connectStorageEmulator(n,...o),n}function connectStorageEmulator(e,t,r,n={}){connectStorageEmulator$1(e,t,r,n)}function getBlob(e,t){return function getBlobInternal(e,t){e._throwIfRoot("getBlob");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBlobConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function getStream(e,t){throw new Error("getStream() is only supported by NodeJS builds")}function factory(e,{instanceIdentifier:t}){const r=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return new FirebaseStorageImpl(r,o,s,t,n)}!function registerStorage(){t(new Component("storage",factory,"PUBLIC").setMultipleInstances(!0)),r(d,"0.12.6",""),r(d,"0.12.6","esm2017")}();export{StorageError,i as StorageErrorCode,l as StringFormat,FbsBlob as _FbsBlob,Location as _Location,u as _TaskEvent,h as _TaskState,UploadTask as _UploadTask,dataFromString as _dataFromString,_getChild,invalidArgument as _invalidArgument,invalidRootOperation as _invalidRootOperation,connectStorageEmulator,deleteObject,getBlob,getBytes,getDownloadURL,getMetadata,getStorage,getStream,list,listAll,ref,updateMetadata,uploadBytes,uploadBytesResumable,uploadString}; | ||
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++n)),t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t},o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const o=e[t],s=t+1<e.length,i=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=o>>2,u=(3&o)<<4|i>>4;let h=(15&i)<<2|l>>6,d=63&l;a||(d=64,s||(h=64)),n.push(r[c],r[u],r[h],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const o=e[r++];if(o<128)t[n++]=String.fromCharCode(o);else if(o>191&&o<224){const s=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&s)}else if(o>239&&o<365){const s=((7&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],i=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&s)<<6|63&i)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const o=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const i=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==o||null==s||null==i||null==a)throw new DecodeBase64StringError;const l=o<<2|s>>4;if(n.push(l),64!==i){const e=s<<4&240|i>>2;if(n.push(e),64!==a){const e=i<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return o.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,r;return null===(r=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===r?void 0:r[e]})(e);if(!t)return;const r=t.lastIndexOf(":");if(r<=0||r+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const n=parseInt(t.substring(r+1),10);return"["===t[0]?[t.substring(1,r-1),n]:[t.substring(0,r),n]};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,o=this.errors[e],i=o?function replaceTemplate(e,t){return e.replace(s,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(o,r):"Error",a=`${this.serviceName}: ${i} (${n}).`;return new FirebaseError(n,a,r)}}const s=/\{\$([^}]+)}/g;function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}class StorageError extends FirebaseError{constructor(e,t,r=0){super(prependCode(e),`Firebase Storage: ${t} (${prependCode(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var i,a;function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(i.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(i.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(i.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(i.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(i.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(i.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new StorageError(i.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new StorageError(i.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new StorageError(i.INTERNAL_ERROR,"Internal error: "+e)}!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(i||(i={}));class Location{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Location.makeFromUrl(e,t)}catch(t){return new Location(e,"")}if(""===r.path)return r;throw function invalidDefaultBucket(e){return new StorageError(i.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}(e)}static makeFromUrl(e,t){let r=null;const n="([A-Za-z0-9.\\-_]+)";const o=new RegExp("^gs://"+n+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}const s=t.replace(/[.]/g,"\\."),a=[{regex:o,indices:{bucket:1,path:3},postModify:function gsModify(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${s}/v[A-Za-z0-9_]+/b/${n}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:httpModify},{regex:new RegExp(`^https?://${"firebasestorage.googleapis.com"===t?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${n}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:httpModify}];for(let t=0;t<a.length;t++){const n=a[t],o=n.regex.exec(e);if(o){const e=o[n.indices.bucket];let t=o[n.indices.path];t||(t=""),r=new Location(e,t),n.postModify(r);break}}if(null==r)throw function invalidUrl(e){return new StorageError(i.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return r}}class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,t,r,n){if(n<t)throw invalidArgument(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n>r)throw invalidArgument(`Invalid value for '${e}'. Expected ${r} or less.`)}function makeUrl(e,t,r){let n=t;return null==r&&(n=`https://${t}`),`${r}://${n}/v0${e}`}function makeQueryString(e){const t=encodeURIComponent;let r="?";for(const n in e)if(e.hasOwnProperty(n)){r=r+(t(n)+"="+t(e[n]))+"&"}return r=r.slice(0,-1),r}function isRetryStatusCode(e,t){const r=e>=500&&e<600,n=-1!==[408,429].indexOf(e),o=-1!==t.indexOf(e);return r||n||o}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(a||(a={}));class NetworkRequest{constructor(e,t,r,n,o,s,i,a,l,c,u,h=!0){this.url_=e,this.method_=t,this.headers_=r,this.body_=n,this.successCodes_=o,this.additionalRetryCodes_=s,this.callback_=i,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const doTheRequest=(e,t)=>{if(t)return void e(!1,new RequestEndStatus(!1,null,!0));const r=this.connectionFactory_();this.pendingConnection_=r;const progressListener=e=>{const t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)};null!==this.progressCallback_&&r.addUploadProgressListener(progressListener),r.send(this.url_,this.method_,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(progressListener),this.pendingConnection_=null;const t=r.getErrorCode()===a.NO_ERROR,n=r.getStatus();if(!t||isRetryStatusCode(n,this.additionalRetryCodes_)&&this.retry){const t=r.getErrorCode()===a.ABORT;return void e(!1,new RequestEndStatus(!1,null,t))}const o=-1!==this.successCodes_.indexOf(n);e(!0,new RequestEndStatus(o,r))}))},backoffDone=(e,t)=>{const r=this.resolve_,n=this.reject_,o=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(o,o.getResponse());!function isJustDef(e){return void 0!==e}(e)?r():r(e)}catch(e){n(e)}else if(null!==o){const e=unknown();e.serverResponse=o.getErrorText(),this.errorCallback_?n(this.errorCallback_(o,e)):n(e)}else if(t.canceled){n(this.appDelete_?appDeleted():canceled())}else{n(retryLimitExceeded())}};this.canceled_?backoffDone(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=function start(e,t,r){let n=1,o=null,s=null,i=!1,a=0;function canceled(){return 2===a}let l=!1;function triggerCallback(...e){l||(l=!0,t.apply(null,e))}function callWithDelay(t){o=setTimeout((()=>{o=null,e(responseHandler,canceled())}),t)}function clearGlobalTimeout(){s&&clearTimeout(s)}function responseHandler(e,...t){if(l)return void clearGlobalTimeout();if(e)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);if(canceled()||i)return clearGlobalTimeout(),void triggerCallback.call(null,e,...t);let r;n<64&&(n*=2),1===a?(a=2,r=0):r=1e3*(n+Math.random()),callWithDelay(r)}let c=!1;function stop(e){c||(c=!0,clearGlobalTimeout(),l||(null!==o?(e||(a=2),clearTimeout(o),callWithDelay(0)):e||(a=1)))}return callWithDelay(0),s=setTimeout((()=>{i=!0,stop(!0)}),r),stop}(doTheRequest,backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function stop(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class RequestEndStatus{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob$1(...e){const t=getBlobBuilder();if(void 0!==t){const r=new t;for(let t=0;t<e.length;t++)r.append(e[t]);return r.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(i.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function decodeBase64(e){if("undefined"==typeof atob)throw function missingPolyFill(e){return new StorageError(i.UNSUPPORTED_ENVIRONMENT,`${e} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}("base-64");return atob(e)}const l={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class StringData{constructor(e,t){this.data=e,this.contentType=t||null}}function dataFromString(e,t){switch(e){case l.RAW:return new StringData(utf8Bytes_(t));case l.BASE64:case l.BASE64URL:return new StringData(base64Bytes_(e,t));case l.DATA_URL:return new StringData(function dataURLBytes_(e){const t=new DataURLParts(e);return t.base64?base64Bytes_(l.BASE64,t.rest):function percentEncodedBytes_(e){let t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(l.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}(t.rest)}(t),function dataURLContentType_(e){return new DataURLParts(e).contentType}(t))}throw unknown()}function utf8Bytes_(e){const t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<=127)t.push(n);else if(n<=2047)t.push(192|n>>6,128|63&n);else if(55296==(64512&n)){if(r<e.length-1&&56320==(64512&e.charCodeAt(r+1))){n=65536|(1023&n)<<10|1023&e.charCodeAt(++r),t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}else t.push(239,191,189)}else 56320==(64512&n)?t.push(239,191,189):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function base64Bytes_(e,t){switch(e){case l.BASE64:{const r=-1!==t.indexOf("-"),n=-1!==t.indexOf("_");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?")}break}case l.BASE64URL:{const r=-1!==t.indexOf("+"),n=-1!==t.indexOf("/");if(r||n){throw invalidFormat(e,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let r;try{r=decodeBase64(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw invalidFormat(e,"Invalid character found")}const n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(l.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;null!=r&&(this.base64=function endsWith(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-";base64".length):r),this.rest=e.substring(e.indexOf(",")+1)}}class FbsBlob{constructor(e,t){let r=0,n="";isNativeBlob(e)?(this.data_=e,r=e.size,n=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=n}size(){return this.size_}type(){return this.type_}slice(e,t){if(isNativeBlob(this.data_)){const r=function sliceBlob(e,t,r){return e.webkitSlice?e.webkitSlice(t,r):e.mozSlice?e.mozSlice(t,r):e.slice?e.slice(t,r):null}(this.data_,e,t);return null===r?null:new FbsBlob(r)}{const r=new Uint8Array(this.data_.buffer,e,t-e);return new FbsBlob(r,!0)}}static getBlob(...e){if(isNativeBlobDefined()){const t=e.map((e=>e instanceof FbsBlob?e.data_:e));return new FbsBlob(getBlob$1.apply(null,t))}{const t=e.map((e=>isString(e)?dataFromString(l.RAW,e).data:e.data_));let r=0;t.forEach((e=>{r+=e.byteLength}));const n=new Uint8Array(r);let o=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)n[o++]=e[t]})),new FbsBlob(n,!0)}}uploadData(){return this.data_}}function jsonObjectOrNull(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function isNonArrayObject(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}function lastComponent(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function noXform_(e,t){return t}class Mapping{constructor(e,t,r,n){this.server=e,this.local=t||e,this.writable=!!r,this.xform=n||noXform_}}let c=null;function getMappings(){if(c)return c;const e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));const t=new Mapping("name");t.xform=function mappingsXformPath(e,t){return function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e)}(t)},e.push(t);const r=new Mapping("size");return r.xform=function xformSize(e,t){return void 0!==t?Number(t):t},e.push(r),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),c=e,c}function fromResource(e,t,r){const n={type:"file"},o=r.length;for(let e=0;e<o;e++){const o=r[e];n[o.local]=o.xform(n,t[o.server])}return function addRef(e,t){Object.defineProperty(e,"ref",{get:function generateRef(){const r=e.bucket,n=e.fullPath,o=new Location(r,n);return t._makeStorageReference(o)}})}(n,e),n}function fromResourceString(e,t,r){const n=jsonObjectOrNull(t);if(null===n)return null;return fromResource(e,n,r)}function toResourceString(e,t){const r={},n=t.length;for(let o=0;o<n;o++){const n=t[o];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}function fromResponseString(e,t,r){const n=jsonObjectOrNull(r);if(null===n)return null;return function fromBackendResponse(e,t,r){const n={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r.prefixes)for(const o of r.prefixes){const r=o.replace(/\/$/,""),s=e._makeStorageReference(new Location(t,r));n.prefixes.push(s)}if(r.items)for(const o of r.items){const r=e._makeStorageReference(new Location(t,o.name));n.items.push(r)}return n}(e,t,n)}class RequestInfo{constructor(e,t,r,n){this.url=e,this.method=t,this.handler=r,this.timeout=n,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),o}}function downloadUrlHandler(e,t){return function handler(r,n){const o=fromResourceString(e,n,t);return handlerCheck(null!==o),function downloadUrlFromResourceString(e,t,r,n){const o=jsonObjectOrNull(t);if(null===o)return null;if(!isString(o.downloadTokens))return null;const s=o.downloadTokens;if(0===s.length)return null;const i=encodeURIComponent;return s.split(",").map((t=>{const o=e.bucket,s=e.fullPath;return makeUrl("/b/"+i(o)+"/o/"+i(s),r,n)+makeQueryString({alt:"media",token:t})}))[0]}(o,n,e.host,e._protocol)}}function sharedErrorHandler(e){return function errorHandler(t,r){let n;return n=401===t.getStatus()?t.getErrorText().includes("Firebase App Check token is invalid")?function unauthorizedApp(){return new StorageError(i.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}():function unauthenticated(){return new StorageError(i.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}():402===t.getStatus()?function quotaExceeded(e){return new StorageError(i.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}(e.bucket):403===t.getStatus()?function unauthorized(e){return new StorageError(i.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}(e.path):r,n.status=t.getStatus(),n.serverResponse=r.serverResponse,n}}function objectErrorHandler(e){const t=sharedErrorHandler(e);return function errorHandler(r,n){let o=t(r,n);return 404===r.getStatus()&&(o=function objectNotFound(e){return new StorageError(i.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}(e.path)),o.serverResponse=n.serverResponse,o}}function getMetadata$2(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",metadataHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}function list$2(e,t,r,n,o){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",r&&r.length>0&&(s.delimiter=r),n&&(s.pageToken=n),o&&(s.maxResults=o);const i=makeUrl(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,l=new RequestInfo(i,"GET",function listHandler(e,t){return function handler(r,n){const o=fromResponseString(e,t,n);return handlerCheck(null!==o),o}}(e,t.bucket),a);return l.urlParams=s,l.errorHandler=sharedErrorHandler(t),l}function getBytes$1(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol)+"?alt=media",o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",((e,t)=>t),o);return s.errorHandler=objectErrorHandler(t),void 0!==r&&(s.headers.Range=`bytes=0-${r}`,s.successCodes=[200,206]),s}function metadataForUpload_(e,t,r){const n=Object.assign({},r);return n.fullPath=e.path,n.size=t.size(),n.contentType||(n.contentType=function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),n}function multipartUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};const a=function genBoundary(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();i["Content-Type"]="multipart/related; boundary="+a;const l=metadataForUpload_(t,n,o),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(l,r)+"\r\n--"+a+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",u="\r\n--"+a+"--",h=FbsBlob.getBlob(c,n,u);if(null===h)throw cannotSliceBlob();const d={name:l.fullPath},p=makeUrl(s,e.host,e._protocol),_=e.maxUploadRetryTime,f=new RequestInfo(p,"POST",metadataHandler(e,r),_);return f.urlParams=d,f.headers=i,f.body=h.uploadData(),f.errorHandler=sharedErrorHandler(t),f}class ResumableUploadStatus{constructor(e,t,r,n){this.current=e,this.total=t,this.finalized=!!r,this.metadata=n||null}}function checkResumeHeader_(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!r&&-1!==(t||["active"]).indexOf(r)),r}function continueResumableUpload(e,t,r,n,o,s,a,l){const c=new ResumableUploadStatus(0,0);if(a?(c.current=a.current,c.total=a.total):(c.current=0,c.total=n.size()),n.size()!==c.total)throw function serverFileWrongSize(){return new StorageError(i.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}();const u=c.total-c.current;let h=u;o>0&&(h=Math.min(h,o));const d=c.current,p=d+h;let _="";_=0===h?"finalize":u===h?"upload, finalize":"upload";const f={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${c.current}`},g=n.slice(d,p);if(null===g)throw cannotSliceBlob();const m=t.maxUploadRetryTime,b=new RequestInfo(r,"POST",(function handler(e,r){const o=checkResumeHeader_(e,["active","final"]),i=c.current+h,a=n.size();let l;return l="final"===o?metadataHandler(t,s)(e,r):null,new ResumableUploadStatus(i,a,"final"===o,l)}),m);return b.headers=f,b.body=g.uploadData(),b.progressCallback=l||null,b.errorHandler=sharedErrorHandler(e),b}const u={STATE_CHANGED:"state_changed"},h={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return h.RUNNING;case"paused":return h.PAUSED;case"success":return h.SUCCESS;case"canceled":return h.CANCELED;default:return h.ERROR}}class Observer{constructor(e,t,r){if(function isFunction(e){return"function"==typeof e}(e)||null!=t||null!=r)this.next=e,this.error=null!=t?t:void 0,this.complete=null!=r?r:void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}function async(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=a.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=a.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=a.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,r,n){if(this.sent_)throw internalError("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(const e in n)n.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,n[e].toString());return void 0!==r?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}}function newTextConnection(){return new XhrTextConnection}class XhrBytesConnection extends XhrConnection{initXhr(){this.xhr_.responseType="arraybuffer"}}function newBytesConnection(){return new XhrBytesConnection}class XhrBlobConnection extends XhrConnection{initXhr(){this.xhr_.responseType="blob"}}function newBlobConnection(){return new XhrBlobConnection}class UploadTask{constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(i.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=retryLimitExceeded()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(i.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,r])=>{switch(this._state){case"running":e(t,r);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const r=function createResumableUpload(e,t,r,n,o){const s=t.bucketOnlyServerUrl(),i=metadataForUpload_(t,n,o),a={name:i.fullPath},l=makeUrl(s,e.host,e._protocol),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},u=toResourceString(i,r),h=e.maxUploadRetryTime,d=new RequestInfo(l,"POST",(function handler(e){let t;checkResumeHeader_(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(t)),t}),h);return d.urlParams=a,d.headers=c,d.body=u,d.errorHandler=sharedErrorHandler(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,r)=>{const n=function getResumableUploadStatus(e,t,r,n){const o=e.maxUploadRetryTime,s=new RequestInfo(r,"POST",(function handler(e){const t=checkResumeHeader_(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}r||handlerCheck(!1);const o=Number(r);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,n.size(),"final"===t)}),o);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=sharedErrorHandler(t),s}(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(n,newTextConnection,t,r);this._request=o,o.getPromise().then((e=>{e=e,this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=262144*this._chunkMultiplier,t=new ResumableUploadStatus(this._transferred,this._blob.size()),r=this._uploadUrl;this._resolveToken(((n,o)=>{let s;try{s=continueResumableUpload(this._ref._location,this._ref.storage,r,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const i=this._ref.storage._makeRequest(s,newTextConnection,n,o,!1);this._request=i,i.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const r=getMetadata$2(this._ref.storage,this._ref._location,this._mappings),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const r=multipartUpload(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),n=this._ref.storage._makeRequest(r,newTextConnection,e,t);this._request=n,n.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,n){const o=new Observer(t||void 0,r||void 0,n||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case h.SUCCESS:async(this._resolve.bind(null,this.snapshot))();break;case h.CANCELED:case h.ERROR:async(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(taskStateFromInternalTaskState(this._state)){case h.RUNNING:case h.PAUSED:e.next&&async(e.next.bind(e,this.snapshot))();break;case h.SUCCESS:e.complete&&async(e.complete.bind(e))();break;default:e.error&&async(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class Reference{constructor(e,t){this._service=e,this._location=t instanceof Location?t:Location.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Reference(e,t)}get root(){const e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){const e=function parent(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;const t=new Location(this._location.bucket,e);return new Reference(this._service,t)}_throwIfRoot(e){if(""===this._location.path)throw invalidRootOperation(e)}}function uploadBytes$1(e,t,r){e._throwIfRoot("uploadBytes");const n=multipartUpload(e.storage,e._location,getMappings(),new FbsBlob(t,!0),r);return e.storage.makeRequestWithTokens(n,newTextConnection).then((t=>({metadata:t,ref:e})))}function listAll$1(e){const t={prefixes:[],items:[]};return listAllHelper(e,t).then((()=>t))}async function listAllHelper(e,t,r){const n={pageToken:r},o=await list$1(e,n);t.prefixes.push(...o.prefixes),t.items.push(...o.items),null!=o.nextPageToken&&await listAllHelper(e,t,o.nextPageToken)}function list$1(e,t){null!=t&&"number"==typeof t.maxResults&&validateNumber("options.maxResults",1,1e3,t.maxResults);const r=t||{},n=list$2(e.storage,e._location,"/",r.pageToken,r.maxResults);return e.storage.makeRequestWithTokens(n,newTextConnection)}function updateMetadata$1(e,t){e._throwIfRoot("updateMetadata");const r=function updateMetadata$2(e,t,r,n){const o=makeUrl(t.fullServerUrl(),e.host,e._protocol),s=toResourceString(r,n),i=e.maxOperationRetryTime,a=new RequestInfo(o,"PATCH",metadataHandler(e,n),i);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=objectErrorHandler(t),a}(e.storage,e._location,t,getMappings());return e.storage.makeRequestWithTokens(r,newTextConnection)}function getDownloadURL$1(e){e._throwIfRoot("getDownloadURL");const t=function getDownloadUrl(e,t,r){const n=makeUrl(t.fullServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime,s=new RequestInfo(n,"GET",downloadUrlHandler(e,r),o);return s.errorHandler=objectErrorHandler(t),s}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection).then((e=>{if(null===e)throw function noDownloadURL(){return new StorageError(i.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}();return e}))}function deleteObject$1(e){e._throwIfRoot("deleteObject");const t=function deleteObject$2(e,t){const r=makeUrl(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime,o=new RequestInfo(r,"DELETE",(function handler(e,t){}),n);return o.successCodes=[200,204],o.errorHandler=objectErrorHandler(t),o}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,newTextConnection)}function _getChild$1(e,t){const r=function child(e,t){const r=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?r:e+"/"+r}(e._location.path,t),n=new Location(e._location.bucket,r);return new Reference(e.storage,n)}function refFromPath(e,t){if(e instanceof FirebaseStorageImpl){const r=e;if(null==r._bucket)throw function noDefaultBucket(){return new StorageError(i.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the 'storageBucket' property when initializing the app?")}();const n=new Reference(r,r._bucket);return null!=t?refFromPath(n,t):n}return void 0!==t?_getChild$1(e,t):e}function ref$1(e,t){if(t&&function isUrl(e){return/^[A-Za-z]+:\/\//.test(e)}(t)){if(e instanceof FirebaseStorageImpl)return function refFromURL(e,t){return new Reference(e,t)}(e,t);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}return refFromPath(e,t)}function extractBucket(e,t){const r=null==t?void 0:t.storageBucket;return null==r?null:Location.makeFromBucketSpec(r,e)}function connectStorageEmulator$1(e,t,r,n={}){e.host=`${t}:${r}`,e._protocol="http";const{mockUserToken:o}=n;o&&(e._overrideAuthToken="string"==typeof o?o:function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=t||"demo-project",n=e.iat||0,o=e.sub||e.user_id;if(!o)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:n,exp:n+3600,auth_time:n,sub:o,user_id:o,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(o,e.app.options.projectId))}class FirebaseStorageImpl{constructor(e,t,r,n,o){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=n,this._firebaseVersion=o,this._bucket=null,this._host="firebasestorage.googleapis.com",this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=n?Location.makeFromBucketSpec(n,this._host):extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,t,r,n,o=!0){if(this._deleted)return new FailRequest(appDeleted());{const s=function makeRequest(e,t,r,n,o,s,i=!0){const a=makeQueryString(e.urlParams),l=e.url+a,c=Object.assign({},e.headers);return function addGmpidHeader_(e,t){t&&(e["X-Firebase-GMPID"]=t)}(c,t),function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(c,r),function addVersionHeader_(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(null!=t?t:"AppManager")}(c,s),function addAppCheckHeader_(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(c,n),new NetworkRequest(l,e.method,c,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,o,i)}(e,this._appId,r,n,t,this._firebaseVersion,o);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[r,n]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,n).getPromise()}}const d="@firebase/storage";function getBytes(e,t){return function getBytesInternal(e,t){e._throwIfRoot("getBytes");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBytesConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function uploadBytes(e,t,r){return uploadBytes$1(e=getModularInstance(e),t,r)}function uploadString(e,t,r,n){return function uploadString$1(e,t,r=l.RAW,n){e._throwIfRoot("uploadString");const o=dataFromString(r,t),s=Object.assign({},n);return null==s.contentType&&null!=o.contentType&&(s.contentType=o.contentType),uploadBytes$1(e,o.data,s)}(e=getModularInstance(e),t,r,n)}function uploadBytesResumable(e,t,r){return function uploadBytesResumable$1(e,t,r){return e._throwIfRoot("uploadBytesResumable"),new UploadTask(e,new FbsBlob(t),r)}(e=getModularInstance(e),t,r)}function getMetadata(e){return function getMetadata$1(e){e._throwIfRoot("getMetadata");const t=getMetadata$2(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(t,newTextConnection)}(e=getModularInstance(e))}function updateMetadata(e,t){return updateMetadata$1(e=getModularInstance(e),t)}function list(e,t){return list$1(e=getModularInstance(e),t)}function listAll(e){return listAll$1(e=getModularInstance(e))}function getDownloadURL(e){return getDownloadURL$1(e=getModularInstance(e))}function deleteObject(e){return deleteObject$1(e=getModularInstance(e))}function ref(e,t){return ref$1(e=getModularInstance(e),t)}function _getChild(e,t){return _getChild$1(e,t)}function getStorage(t=e(),r){t=getModularInstance(t);const n=_getProvider(t,"storage").getImmediate({identifier:r}),o=getDefaultEmulatorHostnameAndPort("storage");return o&&connectStorageEmulator(n,...o),n}function connectStorageEmulator(e,t,r,n={}){connectStorageEmulator$1(e,t,r,n)}function getBlob(e,t){return function getBlobInternal(e,t){e._throwIfRoot("getBlob");const r=getBytes$1(e.storage,e._location,t);return e.storage.makeRequestWithTokens(r,newBlobConnection).then((e=>void 0!==t?e.slice(0,t):e))}(e=getModularInstance(e),t)}function getStream(e,t){throw new Error("getStream() is only supported by NodeJS builds")}function factory(e,{instanceIdentifier:t}){const r=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),s=e.getProvider("app-check-internal");return new FirebaseStorageImpl(r,o,s,t,n)}!function registerStorage(){t(new Component("storage",factory,"PUBLIC").setMultipleInstances(!0)),r(d,"0.12.6",""),r(d,"0.12.6","esm2017")}();export{StorageError,i as StorageErrorCode,l as StringFormat,FbsBlob as _FbsBlob,Location as _Location,u as _TaskEvent,h as _TaskState,UploadTask as _UploadTask,dataFromString as _dataFromString,_getChild,invalidArgument as _invalidArgument,invalidRootOperation as _invalidRootOperation,connectStorageEmulator,deleteObject,getBlob,getBytes,getDownloadURL,getMetadata,getStorage,getStream,list,listAll,ref,updateMetadata,uploadBytes,uploadBytesResumable,uploadString}; | ||
//# sourceMappingURL=firebase-storage.js.map |
@@ -1,3 +0,3 @@ | ||
import{_getProvider,getApp as t,_registerComponent as e,registerVersion as n}from"https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js";class FirebaseError extends Error{constructor(t,e,n){super(e),this.code=t,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(t,e,n){this.service=t,this.serviceName=e,this.errors=n}create(t,...e){const n=e[0]||{},o=`${this.service}/${t}`,r=this.errors[t],i=r?function replaceTemplate(t,e){return t.replace(s,((t,n)=>{const s=e[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",a=`${this.serviceName}: ${i} (${o}).`;return new FirebaseError(o,a,n)}}const s=/\{\$([^}]+)}/g;class Component{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}function __await(t){return this instanceof __await?(this.v=t,this):new __await(t)}function __asyncGenerator(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,o=n.apply(t,e||[]),r=[];return s={},verb("next"),verb("throw"),verb("return"),s[Symbol.asyncIterator]=function(){return this},s;function verb(t){o[t]&&(s[t]=function(e){return new Promise((function(n,s){r.push([t,e,n,s])>1||resume(t,e)}))})}function resume(t,e){try{!function step(t){t.value instanceof __await?Promise.resolve(t.value.v).then(fulfill,reject):settle(r[0][2],t)}(o[t](e))}catch(t){settle(r[0][3],t)}}function fulfill(t){resume("next",t)}function reject(t){resume("throw",t)}function settle(t,e){t(e),r.shift(),r.length&&resume(r[0][0],r[0][1])}}var o="@firebase/vertexai-preview";class VertexAIService{constructor(t,e,n,s){var o;this.app=t,this.options=s;const r=null==n?void 0:n.getImmediate({optional:!0}),i=null==e?void 0:e.getImmediate({optional:!0});this.auth=i||null,this.appCheck=r||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||"us-central1"}_delete(){return Promise.resolve()}}class VertexAIError extends FirebaseError{constructor(t,e,n){const s=`vertexAI/${t}`,o=`VertexAI: ${e} (${s}).`;super(s,o),this.code=t,this.message=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,VertexAIError),Object.setPrototypeOf(this,VertexAIError.prototype),this.toString=()=>o}}var r;!function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens"}(r||(r={}));class RequestUrl{constructor(t,e,n,s,o){this.model=t,this.task=e,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){var t;let e=`${(null===(t=this.requestOptions)||void 0===t?void 0:t.baseUrl)||"https://firebaseml.googleapis.com"}/v2beta`;return e+=`/projects/${this.apiSettings.project}`,e+=`/locations/${this.apiSettings.location}`,e+=`/${this.model}`,e+=`:${this.task}`,this.stream&&(e+="?alt=sse"),e}get fullModelString(){let t=`projects/${this.apiSettings.project}`;return t+=`/locations/${this.apiSettings.location}`,t+=`/${this.model}`,t}}async function getHeaders(t){const e=new Headers;if(e.append("Content-Type","application/json"),e.append("x-goog-api-client",function getClientHeaders(){const t=[];return t.push("gl-js/0.0.3"),t.push("fire/0.0.3"),t.join(" ")}()),e.append("x-goog-api-key",t.apiSettings.apiKey),t.apiSettings.getAppCheckToken){const n=await t.apiSettings.getAppCheckToken();n&&!n.error&&e.append("X-Firebase-AppCheck",n.token)}if(t.apiSettings.getAuthToken){const n=await t.apiSettings.getAuthToken();n&&e.append("Authorization",`Firebase ${n.accessToken}`)}return e}async function makeRequest(t,e,n,s,o,r){const i=new RequestUrl(t,e,n,s,r);let a;try{const c=await async function constructRequest(t,e,n,s,o,r){const i=new RequestUrl(t,e,n,s,r);return{url:i.toString(),fetchOptions:Object.assign(Object.assign({},buildFetchOptions(r)),{method:"POST",headers:await getHeaders(i),body:o})}}(t,e,n,s,o,r);if(a=await fetch(c.url,c.fetchOptions),!a.ok){let t,e="";try{const n=await a.json();e=n.error.message,n.error.details&&(e+=` ${JSON.stringify(n.error.details)}`,t=n.error.details)}catch(t){}throw new VertexAIError("fetch-error",`Error fetching from ${i}: [${a.status} ${a.statusText}] ${e}`,{status:a.status,statusText:a.statusText,errorDetails:t})}}catch(t){let e=t;throw"fetch-error"!==t.code&&t instanceof Error&&(e=new VertexAIError("error",`Error fetching from ${i.toString()}: ${t.message}`),e.stack=t.stack),e}return a}function buildFetchOptions(t){const e={};if((null==t?void 0:t.timeout)&&(null==t?void 0:t.timeout)>=0){const n=new AbortController,s=n.signal;setTimeout((()=>n.abort()),t.timeout),e.signal=s}return e}const i=["user","model","function","system"];var a,c,l,d,u,h,p,f,E;function addHelpers(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(t.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(t)}. Response body stored in error.response`,{response:t});return function getText(t){var e,n,s,o;const r=[];if(null===(n=null===(e=t.candidates)||void 0===e?void 0:e[0].content)||void 0===n?void 0:n.parts)for(const e of null===(o=null===(s=t.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)e.text&&r.push(e.text);return r.length>0?r.join(""):""}(t)}if(t.promptFeedback)throw new VertexAIError("response-error",`Text not available. ${formatBlockErrorMessage(t)}`,{response:t});return""},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(t.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(t)}. Response body stored in error.response`,{response:t});return function getFunctionCalls(t){var e,n,s,o;const r=[];if(null===(n=null===(e=t.candidates)||void 0===e?void 0:e[0].content)||void 0===n?void 0:n.parts)for(const e of null===(o=null===(s=t.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)e.functionCall&&r.push(e.functionCall);return r.length>0?r:void 0}(t)}if(t.promptFeedback)throw new VertexAIError("response-error",`Function call not available. ${formatBlockErrorMessage(t)}`,{response:t})},t}!function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"}(a||(a={})),function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"}(c||(c={})),function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"}(l||(l={})),function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"}(d||(d={})),function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(u||(u={})),function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"}(h||(h={})),function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.OTHER="OTHER"}(p||(p={})),function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"}(f||(f={})),function(t){t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT"}(E||(E={}));const g=[p.RECITATION,p.SAFETY];function hadBadFinishReason(t){return!!t.finishReason&&g.includes(t.finishReason)}function formatBlockErrorMessage(t){var e,n,s;let o="";if(t.candidates&&0!==t.candidates.length||!t.promptFeedback){if(null===(s=t.candidates)||void 0===s?void 0:s[0]){const e=t.candidates[0];hadBadFinishReason(e)&&(o+=`Candidate was blocked due to ${e.finishReason}`,e.finishMessage&&(o+=`: ${e.finishMessage}`))}}else o+="Response was blocked",(null===(e=t.promptFeedback)||void 0===e?void 0:e.blockReason)&&(o+=` due to ${t.promptFeedback.blockReason}`),(null===(n=t.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);return o}const m=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(t){const e=function getResponseStream(t){const e=t.getReader();return new ReadableStream({start(t){let n="";return pump();function pump(){return e.read().then((({value:e,done:s})=>{if(s)return n.trim()?void t.error(new VertexAIError("parse-failed","Failed to parse stream")):void t.close();n+=e;let o,r=n.match(m);for(;r;){try{o=JSON.parse(r[1])}catch(e){return void t.error(new VertexAIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}t.enqueue(o),n=n.substring(r[0].length),r=n.match(m)}return pump()}))}}})}(t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,s]=e.tee();return{stream:generateResponseSequence(n),response:getResponsePromise(s)}}async function getResponsePromise(t){const e=[],n=t.getReader();for(;;){const{done:t,value:s}=await n.read();if(t)return addHelpers(aggregateResponses(e));e.push(s)}}function generateResponseSequence(t){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const e=t.getReader();for(;;){const{value:t,done:n}=yield __await(e.read());if(n)break;yield yield __await(addHelpers(t))}}))}function aggregateResponses(t){const e=t[t.length-1],n={promptFeedback:null==e?void 0:e.promptFeedback};for(const e of t)if(e.candidates)for(const t of e.candidates){const e=t.index;if(n.candidates||(n.candidates=[]),n.candidates[e]||(n.candidates[e]={index:t.index}),n.candidates[e].citationMetadata=t.citationMetadata,n.candidates[e].finishReason=t.finishReason,n.candidates[e].finishMessage=t.finishMessage,n.candidates[e].safetyRatings=t.safetyRatings,t.content&&t.content.parts){n.candidates[e].content||(n.candidates[e].content={role:t.content.role||"user",parts:[]});const s={};for(const o of t.content.parts)o.text&&(s.text=o.text),o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length&&(s.text=""),n.candidates[e].content.parts.push(s)}}return n}async function generateContentStream(t,e,n,s){return processStream(await makeRequest(e,r.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s))}async function generateContent(t,e,n,s){const o=await makeRequest(e,r.GENERATE_CONTENT,t,!1,JSON.stringify(n),s);return{response:addHelpers(await o.json())}}function formatSystemInstruction(t){if(null!=t)return"string"==typeof t?{role:"system",parts:[{text:t}]}:t.text?{role:"system",parts:[t]}:t.parts?t.role?t:{role:"system",parts:t.parts}:void 0}function formatNewContent(t){let e=[];if("string"==typeof t)e=[{text:t}];else for(const n of t)"string"==typeof n?e.push({text:n}):e.push(n);return function assignRoleToPartsAndValidateSendMessageRequest(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,o=!1;for(const r of t)"functionResponse"in r?(n.parts.push(r),o=!0):(e.parts.push(r),s=!0);if(s&&o)throw new VertexAIError("invalid-content","Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.");if(!s&&!o)throw new VertexAIError("invalid-content","No Content is provided for sending chat message.");if(s)return e;return n}(e)}function formatGenerateContentInput(t){let e;if(t.contents)e=t;else{e={contents:[formatNewContent(t)]}}return t.systemInstruction&&(e.systemInstruction=formatSystemInstruction(t.systemInstruction)),e}const I=["text","inlineData","functionCall","functionResponse"],_={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},v={user:["model"],function:["model"],model:["user","function"],system:[]};class ChatSession{constructor(t,e,n,s){this.model=e,this.params=n,this.requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiSettings=t,(null==n?void 0:n.history)&&(!function validateChatHistory(t){let e=null;for(const n of t){const{role:t,parts:s}=n;if(!e&&"user"!==t)throw new VertexAIError("invalid-content",`First Content should be with role 'user', got ${t}`);if(!i.includes(t))throw new VertexAIError("invalid-content",`Each item should include role field. Got ${t} but valid roles are: ${JSON.stringify(i)}`);if(!Array.isArray(s))throw new VertexAIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new VertexAIError("invalid-content","Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0};for(const t of s)for(const e of I)e in t&&(o[e]+=1);const r=_[t];for(const e of I)if(!r.includes(e)&&o[e]>0)throw new VertexAIError("invalid-content",`Content with role '${t}' can't contain '${e}' part`);if(e&&!v[t].includes(e.role))throw new VertexAIError("invalid-content",`Content with role '${t} can't follow '${e.role}'. Valid previous roles: ${JSON.stringify(v)}`);e=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(t){var e,n,s,o,r;await this._sendPromise;const i=formatNewContent(t),a={safetySettings:null===(e=this.params)||void 0===e?void 0:e.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]};let c={};return this._sendPromise=this._sendPromise.then((()=>generateContent(this._apiSettings,this.model,a,this.requestOptions))).then((t=>{var e,n;if(t.response.candidates&&t.response.candidates.length>0){this._history.push(i);const s={parts:(null===(e=t.response.candidates)||void 0===e?void 0:e[0].content.parts)||[],role:(null===(n=t.response.candidates)||void 0===n?void 0:n[0].content.role)||"model"};this._history.push(s)}else{const e=formatBlockErrorMessage(t.response);e&&console.warn(`sendMessage() was unsuccessful. ${e}. Inspect response object for details.`)}c=t})),await this._sendPromise,c}async sendMessageStream(t){var e,n,s,o,r;await this._sendPromise;const i=formatNewContent(t),a={safetySettings:null===(e=this.params)||void 0===e?void 0:e.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((t=>{throw new Error("SILENT_ERROR")})).then((t=>t.response)).then((t=>{if(t.candidates&&t.candidates.length>0){this._history.push(i);const e=Object.assign({},t.candidates[0].content);e.role||(e.role="model"),this._history.push(e)}else{const e=formatBlockErrorMessage(t);e&&console.warn(`sendMessageStream() was unsuccessful. ${e}. Inspect response object for details.`)}})).catch((t=>{"SILENT_ERROR"!==t.message&&console.error(t)})),c}}class GenerativeModel{constructor(t,e,n){var s,o,r,i;if(!(null===(o=null===(s=t.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw new VertexAIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.');if(!(null===(i=null===(r=t.app)||void 0===r?void 0:r.options)||void 0===i?void 0:i.projectId))throw new VertexAIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.');this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,location:t.location},t.appCheck&&(this._apiSettings.getAppCheckToken=()=>t.appCheck.getToken()),t.auth&&(this._apiSettings.getAuthToken=()=>t.auth.getToken()),e.model.includes("/")?e.model.startsWith("models/")?this.model=`publishers/google/${e.model}`:this.model=e.model:this.model=`publishers/google/models/${e.model}`,this.generationConfig=e.generationConfig||{},this.safetySettings=e.safetySettings||[],this.tools=e.tools,this.toolConfig=e.toolConfig,this.systemInstruction=formatSystemInstruction(e.systemInstruction),this.requestOptions=n||{}}async generateContent(t){const e=formatGenerateContentInput(t);return generateContent(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}async generateContentStream(t){const e=formatGenerateContentInput(t);return generateContentStream(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}startChat(t){return new ChatSession(this._apiSettings,this.model,Object.assign({tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}async countTokens(t){const e=formatGenerateContentInput(t);return async function countTokens(t,e,n,s){return(await makeRequest(e,r.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,e)}}function getVertexAI(e=t(),n){e=function getModularInstance(t){return t&&t._delegate?t._delegate:t}(e);return _getProvider(e,"vertexAI").getImmediate({identifier:(null==n?void 0:n.location)||"us-central1"})}function getGenerativeModel(t,e,n){if(!e.model)throw new VertexAIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(t,e,n)}!function registerVertex(){e(new Component("vertexAI",((t,{instanceIdentifier:e})=>{const n=t.getProvider("app").getImmediate(),s=t.getProvider("auth-internal"),o=t.getProvider("app-check-internal");return new VertexAIService(n,s,o,{location:e})}),"PUBLIC").setMultipleInstances(!0)),n(o,"0.0.3"),n(o,"0.0.3","esm2017")}();export{h as BlockReason,ChatSession,p as FinishReason,f as FunctionCallingMode,E as FunctionDeclarationSchemaType,GenerativeModel,l as HarmBlockMethod,c as HarmBlockThreshold,a as HarmCategory,d as HarmProbability,u as HarmSeverity,i as POSSIBLE_ROLES,VertexAIError,getGenerativeModel,getVertexAI}; | ||
import{_getProvider,getApp as t,_registerComponent as e,registerVersion as n}from"https://www.gstatic.com/firebasejs/10.12.4-20240716220314/firebase-app.js";class FirebaseError extends Error{constructor(t,e,n){super(e),this.code=t,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(t,e,n){this.service=t,this.serviceName=e,this.errors=n}create(t,...e){const n=e[0]||{},o=`${this.service}/${t}`,r=this.errors[t],i=r?function replaceTemplate(t,e){return t.replace(s,((t,n)=>{const s=e[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",a=`${this.serviceName}: ${i} (${o}).`;return new FirebaseError(o,a,n)}}const s=/\{\$([^}]+)}/g;class Component{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}function __await(t){return this instanceof __await?(this.v=t,this):new __await(t)}function __asyncGenerator(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,o=n.apply(t,e||[]),r=[];return s={},verb("next"),verb("throw"),verb("return"),s[Symbol.asyncIterator]=function(){return this},s;function verb(t){o[t]&&(s[t]=function(e){return new Promise((function(n,s){r.push([t,e,n,s])>1||resume(t,e)}))})}function resume(t,e){try{!function step(t){t.value instanceof __await?Promise.resolve(t.value.v).then(fulfill,reject):settle(r[0][2],t)}(o[t](e))}catch(t){settle(r[0][3],t)}}function fulfill(t){resume("next",t)}function reject(t){resume("throw",t)}function settle(t,e){t(e),r.shift(),r.length&&resume(r[0][0],r[0][1])}}var o="@firebase/vertexai-preview";class VertexAIService{constructor(t,e,n,s){var o;this.app=t,this.options=s;const r=null==n?void 0:n.getImmediate({optional:!0}),i=null==e?void 0:e.getImmediate({optional:!0});this.auth=i||null,this.appCheck=r||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||"us-central1"}_delete(){return Promise.resolve()}}class VertexAIError extends FirebaseError{constructor(t,e,n){const s=`vertexAI/${t}`,o=`VertexAI: ${e} (${s}).`;super(s,o),this.code=t,this.message=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,VertexAIError),Object.setPrototypeOf(this,VertexAIError.prototype),this.toString=()=>o}}var r;!function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens"}(r||(r={}));class RequestUrl{constructor(t,e,n,s,o){this.model=t,this.task=e,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){var t;let e=`${(null===(t=this.requestOptions)||void 0===t?void 0:t.baseUrl)||"https://firebaseml.googleapis.com"}/v2beta`;return e+=`/projects/${this.apiSettings.project}`,e+=`/locations/${this.apiSettings.location}`,e+=`/${this.model}`,e+=`:${this.task}`,this.stream&&(e+="?alt=sse"),e}get fullModelString(){let t=`projects/${this.apiSettings.project}`;return t+=`/locations/${this.apiSettings.location}`,t+=`/${this.model}`,t}}async function getHeaders(t){const e=new Headers;if(e.append("Content-Type","application/json"),e.append("x-goog-api-client",function getClientHeaders(){const t=[];return t.push("gl-js/0.0.3"),t.push("fire/0.0.3"),t.join(" ")}()),e.append("x-goog-api-key",t.apiSettings.apiKey),t.apiSettings.getAppCheckToken){const n=await t.apiSettings.getAppCheckToken();n&&!n.error&&e.append("X-Firebase-AppCheck",n.token)}if(t.apiSettings.getAuthToken){const n=await t.apiSettings.getAuthToken();n&&e.append("Authorization",`Firebase ${n.accessToken}`)}return e}async function makeRequest(t,e,n,s,o,r){const i=new RequestUrl(t,e,n,s,r);let a;try{const c=await async function constructRequest(t,e,n,s,o,r){const i=new RequestUrl(t,e,n,s,r);return{url:i.toString(),fetchOptions:Object.assign(Object.assign({},buildFetchOptions(r)),{method:"POST",headers:await getHeaders(i),body:o})}}(t,e,n,s,o,r);if(a=await fetch(c.url,c.fetchOptions),!a.ok){let t,e="";try{const n=await a.json();e=n.error.message,n.error.details&&(e+=` ${JSON.stringify(n.error.details)}`,t=n.error.details)}catch(t){}throw new VertexAIError("fetch-error",`Error fetching from ${i}: [${a.status} ${a.statusText}] ${e}`,{status:a.status,statusText:a.statusText,errorDetails:t})}}catch(t){let e=t;throw"fetch-error"!==t.code&&t instanceof Error&&(e=new VertexAIError("error",`Error fetching from ${i.toString()}: ${t.message}`),e.stack=t.stack),e}return a}function buildFetchOptions(t){const e={};if((null==t?void 0:t.timeout)&&(null==t?void 0:t.timeout)>=0){const n=new AbortController,s=n.signal;setTimeout((()=>n.abort()),t.timeout),e.signal=s}return e}const i=["user","model","function","system"];var a,c,l,d,u,h,p,f,E;function addHelpers(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(t.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(t)}. Response body stored in error.response`,{response:t});return function getText(t){var e,n,s,o;const r=[];if(null===(n=null===(e=t.candidates)||void 0===e?void 0:e[0].content)||void 0===n?void 0:n.parts)for(const e of null===(o=null===(s=t.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)e.text&&r.push(e.text);return r.length>0?r.join(""):""}(t)}if(t.promptFeedback)throw new VertexAIError("response-error",`Text not available. ${formatBlockErrorMessage(t)}`,{response:t});return""},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(t.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(t)}. Response body stored in error.response`,{response:t});return function getFunctionCalls(t){var e,n,s,o;const r=[];if(null===(n=null===(e=t.candidates)||void 0===e?void 0:e[0].content)||void 0===n?void 0:n.parts)for(const e of null===(o=null===(s=t.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)e.functionCall&&r.push(e.functionCall);return r.length>0?r:void 0}(t)}if(t.promptFeedback)throw new VertexAIError("response-error",`Function call not available. ${formatBlockErrorMessage(t)}`,{response:t})},t}!function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"}(a||(a={})),function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"}(c||(c={})),function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"}(l||(l={})),function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"}(d||(d={})),function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(u||(u={})),function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"}(h||(h={})),function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.OTHER="OTHER"}(p||(p={})),function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"}(f||(f={})),function(t){t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT"}(E||(E={}));const g=[p.RECITATION,p.SAFETY];function hadBadFinishReason(t){return!!t.finishReason&&g.includes(t.finishReason)}function formatBlockErrorMessage(t){var e,n,s;let o="";if(t.candidates&&0!==t.candidates.length||!t.promptFeedback){if(null===(s=t.candidates)||void 0===s?void 0:s[0]){const e=t.candidates[0];hadBadFinishReason(e)&&(o+=`Candidate was blocked due to ${e.finishReason}`,e.finishMessage&&(o+=`: ${e.finishMessage}`))}}else o+="Response was blocked",(null===(e=t.promptFeedback)||void 0===e?void 0:e.blockReason)&&(o+=` due to ${t.promptFeedback.blockReason}`),(null===(n=t.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);return o}const m=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(t){const e=function getResponseStream(t){const e=t.getReader();return new ReadableStream({start(t){let n="";return pump();function pump(){return e.read().then((({value:e,done:s})=>{if(s)return n.trim()?void t.error(new VertexAIError("parse-failed","Failed to parse stream")):void t.close();n+=e;let o,r=n.match(m);for(;r;){try{o=JSON.parse(r[1])}catch(e){return void t.error(new VertexAIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}t.enqueue(o),n=n.substring(r[0].length),r=n.match(m)}return pump()}))}}})}(t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,s]=e.tee();return{stream:generateResponseSequence(n),response:getResponsePromise(s)}}async function getResponsePromise(t){const e=[],n=t.getReader();for(;;){const{done:t,value:s}=await n.read();if(t)return addHelpers(aggregateResponses(e));e.push(s)}}function generateResponseSequence(t){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const e=t.getReader();for(;;){const{value:t,done:n}=yield __await(e.read());if(n)break;yield yield __await(addHelpers(t))}}))}function aggregateResponses(t){const e=t[t.length-1],n={promptFeedback:null==e?void 0:e.promptFeedback};for(const e of t)if(e.candidates)for(const t of e.candidates){const e=t.index;if(n.candidates||(n.candidates=[]),n.candidates[e]||(n.candidates[e]={index:t.index}),n.candidates[e].citationMetadata=t.citationMetadata,n.candidates[e].finishReason=t.finishReason,n.candidates[e].finishMessage=t.finishMessage,n.candidates[e].safetyRatings=t.safetyRatings,t.content&&t.content.parts){n.candidates[e].content||(n.candidates[e].content={role:t.content.role||"user",parts:[]});const s={};for(const o of t.content.parts)o.text&&(s.text=o.text),o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length&&(s.text=""),n.candidates[e].content.parts.push(s)}}return n}async function generateContentStream(t,e,n,s){return processStream(await makeRequest(e,r.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s))}async function generateContent(t,e,n,s){const o=await makeRequest(e,r.GENERATE_CONTENT,t,!1,JSON.stringify(n),s);return{response:addHelpers(await o.json())}}function formatSystemInstruction(t){if(null!=t)return"string"==typeof t?{role:"system",parts:[{text:t}]}:t.text?{role:"system",parts:[t]}:t.parts?t.role?t:{role:"system",parts:t.parts}:void 0}function formatNewContent(t){let e=[];if("string"==typeof t)e=[{text:t}];else for(const n of t)"string"==typeof n?e.push({text:n}):e.push(n);return function assignRoleToPartsAndValidateSendMessageRequest(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,o=!1;for(const r of t)"functionResponse"in r?(n.parts.push(r),o=!0):(e.parts.push(r),s=!0);if(s&&o)throw new VertexAIError("invalid-content","Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.");if(!s&&!o)throw new VertexAIError("invalid-content","No Content is provided for sending chat message.");if(s)return e;return n}(e)}function formatGenerateContentInput(t){let e;if(t.contents)e=t;else{e={contents:[formatNewContent(t)]}}return t.systemInstruction&&(e.systemInstruction=formatSystemInstruction(t.systemInstruction)),e}const I=["text","inlineData","functionCall","functionResponse"],_={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},v={user:["model"],function:["model"],model:["user","function"],system:[]};class ChatSession{constructor(t,e,n,s){this.model=e,this.params=n,this.requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiSettings=t,(null==n?void 0:n.history)&&(!function validateChatHistory(t){let e=null;for(const n of t){const{role:t,parts:s}=n;if(!e&&"user"!==t)throw new VertexAIError("invalid-content",`First Content should be with role 'user', got ${t}`);if(!i.includes(t))throw new VertexAIError("invalid-content",`Each item should include role field. Got ${t} but valid roles are: ${JSON.stringify(i)}`);if(!Array.isArray(s))throw new VertexAIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new VertexAIError("invalid-content","Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0};for(const t of s)for(const e of I)e in t&&(o[e]+=1);const r=_[t];for(const e of I)if(!r.includes(e)&&o[e]>0)throw new VertexAIError("invalid-content",`Content with role '${t}' can't contain '${e}' part`);if(e&&!v[t].includes(e.role))throw new VertexAIError("invalid-content",`Content with role '${t} can't follow '${e.role}'. Valid previous roles: ${JSON.stringify(v)}`);e=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(t){var e,n,s,o,r;await this._sendPromise;const i=formatNewContent(t),a={safetySettings:null===(e=this.params)||void 0===e?void 0:e.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]};let c={};return this._sendPromise=this._sendPromise.then((()=>generateContent(this._apiSettings,this.model,a,this.requestOptions))).then((t=>{var e,n;if(t.response.candidates&&t.response.candidates.length>0){this._history.push(i);const s={parts:(null===(e=t.response.candidates)||void 0===e?void 0:e[0].content.parts)||[],role:(null===(n=t.response.candidates)||void 0===n?void 0:n[0].content.role)||"model"};this._history.push(s)}else{const e=formatBlockErrorMessage(t.response);e&&console.warn(`sendMessage() was unsuccessful. ${e}. Inspect response object for details.`)}c=t})),await this._sendPromise,c}async sendMessageStream(t){var e,n,s,o,r;await this._sendPromise;const i=formatNewContent(t),a={safetySettings:null===(e=this.params)||void 0===e?void 0:e.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((t=>{throw new Error("SILENT_ERROR")})).then((t=>t.response)).then((t=>{if(t.candidates&&t.candidates.length>0){this._history.push(i);const e=Object.assign({},t.candidates[0].content);e.role||(e.role="model"),this._history.push(e)}else{const e=formatBlockErrorMessage(t);e&&console.warn(`sendMessageStream() was unsuccessful. ${e}. Inspect response object for details.`)}})).catch((t=>{"SILENT_ERROR"!==t.message&&console.error(t)})),c}}class GenerativeModel{constructor(t,e,n){var s,o,r,i;if(!(null===(o=null===(s=t.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw new VertexAIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.');if(!(null===(i=null===(r=t.app)||void 0===r?void 0:r.options)||void 0===i?void 0:i.projectId))throw new VertexAIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.');this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,location:t.location},t.appCheck&&(this._apiSettings.getAppCheckToken=()=>t.appCheck.getToken()),t.auth&&(this._apiSettings.getAuthToken=()=>t.auth.getToken()),e.model.includes("/")?e.model.startsWith("models/")?this.model=`publishers/google/${e.model}`:this.model=e.model:this.model=`publishers/google/models/${e.model}`,this.generationConfig=e.generationConfig||{},this.safetySettings=e.safetySettings||[],this.tools=e.tools,this.toolConfig=e.toolConfig,this.systemInstruction=formatSystemInstruction(e.systemInstruction),this.requestOptions=n||{}}async generateContent(t){const e=formatGenerateContentInput(t);return generateContent(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}async generateContentStream(t){const e=formatGenerateContentInput(t);return generateContentStream(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}startChat(t){return new ChatSession(this._apiSettings,this.model,Object.assign({tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}async countTokens(t){const e=formatGenerateContentInput(t);return async function countTokens(t,e,n,s){return(await makeRequest(e,r.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,e)}}function getVertexAI(e=t(),n){e=function getModularInstance(t){return t&&t._delegate?t._delegate:t}(e);return _getProvider(e,"vertexAI").getImmediate({identifier:(null==n?void 0:n.location)||"us-central1"})}function getGenerativeModel(t,e,n){if(!e.model)throw new VertexAIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(t,e,n)}!function registerVertex(){e(new Component("vertexAI",((t,{instanceIdentifier:e})=>{const n=t.getProvider("app").getImmediate(),s=t.getProvider("auth-internal"),o=t.getProvider("app-check-internal");return new VertexAIService(n,s,o,{location:e})}),"PUBLIC").setMultipleInstances(!0)),n(o,"0.0.3"),n(o,"0.0.3","esm2017")}();export{h as BlockReason,ChatSession,p as FinishReason,f as FunctionCallingMode,E as FunctionDeclarationSchemaType,GenerativeModel,l as HarmBlockMethod,c as HarmBlockThreshold,a as HarmCategory,d as HarmProbability,u as HarmSeverity,i as POSSIBLE_ROLES,VertexAIError,getGenerativeModel,getVertexAI}; | ||
//# sourceMappingURL=firebase-vertexai-preview.js.map |
{ | ||
"name": "firebase", | ||
"version": "10.12.3", | ||
"version": "10.12.4-20240716220314", | ||
"description": "Firebase JavaScript library for web and Node.js", | ||
@@ -411,6 +411,6 @@ "author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)", | ||
"@firebase/remote-config-compat": "0.2.8", | ||
"@firebase/analytics": "0.10.5", | ||
"@firebase/analytics-compat": "0.2.11", | ||
"@firebase/app-check": "0.8.5", | ||
"@firebase/app-check-compat": "0.3.12", | ||
"@firebase/analytics": "0.10.6-20240716220314", | ||
"@firebase/analytics-compat": "0.2.12-20240716220314", | ||
"@firebase/app-check": "0.8.6-20240716220314", | ||
"@firebase/app-check-compat": "0.3.13-20240716220314", | ||
"@firebase/util": "1.9.7", | ||
@@ -417,0 +417,0 @@ "@firebase/vertexai-preview": "0.0.3" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 2 instances in 1 package
24757179
14
64570
13
38
27
48
312
+ Added@firebase/analytics@0.10.6-20240716220314(transitive)
+ Added@firebase/analytics-compat@0.2.12-20240716220314(transitive)
+ Added@firebase/app-check@0.8.6-20240716220314(transitive)
+ Added@firebase/app-check-compat@0.3.13-20240716220314(transitive)
+ Addedsafevalues@0.6.0(transitive)
- Removed@firebase/analytics@0.10.5(transitive)
- Removed@firebase/analytics-compat@0.2.11(transitive)
- Removed@firebase/app-check@0.8.5(transitive)
- Removed@firebase/app-check-compat@0.3.12(transitive)