firebase 10.7.1 → 10.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/app/dist/esm/index.esm.js +1 -1
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.mjs +1 -1
  4. package/compat/app/dist/esm/index.esm.js +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.mjs +1 -1
  7. package/compat/dist/esm/index.esm.js +2 -2
  8. package/compat/dist/index.node.cjs +2 -2
  9. package/compat/dist/index.rn.cjs.js +2 -2
  10. package/firebase-analytics.js +1 -1
  11. package/firebase-app-check.js +1 -1
  12. package/firebase-app-compat.js +2 -2
  13. package/firebase-app-compat.js.map +1 -1
  14. package/firebase-app.js +14 -6
  15. package/firebase-app.js.map +1 -1
  16. package/firebase-auth-cordova.js +1 -1
  17. package/firebase-auth.js +1 -1
  18. package/firebase-compat.js +4 -4
  19. package/firebase-compat.js.map +1 -1
  20. package/firebase-database.js +1 -1
  21. package/firebase-firestore-compat.js +1 -1
  22. package/firebase-firestore-compat.js.map +1 -1
  23. package/firebase-firestore-lite.js +1 -1
  24. package/firebase-firestore-lite.js.map +1 -1
  25. package/firebase-firestore.js +1 -1
  26. package/firebase-firestore.js.map +1 -1
  27. package/firebase-functions.js +1 -1
  28. package/firebase-installations.js +1 -1
  29. package/firebase-messaging-sw.js +1 -1
  30. package/firebase-messaging.js +1 -1
  31. package/firebase-performance-standalone-compat.es2017.js +20 -20
  32. package/firebase-performance-standalone-compat.es2017.js.map +1 -1
  33. package/firebase-performance-standalone-compat.js +1 -1
  34. package/firebase-performance-standalone-compat.js.map +1 -1
  35. package/firebase-performance.js +1 -1
  36. package/firebase-remote-config.js +1 -1
  37. package/firebase-storage.js +1 -1
  38. package/package.json +5 -5
@@ -1,3 +1,3 @@
1
- import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.7.1/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.4"},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.4",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.4"),e(w,"0.6.4","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.4",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.4",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.4"),e(A,"0.6.4","esm2017")}();export{getPerformance,initializePerformance,trace};
1
+ import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n}from"https://www.gstatic.com/firebasejs/10.7.2/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.4"},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.4",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.4"),e(w,"0.6.4","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.4",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.4",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.4"),e(A,"0.6.4","esm2017")}();export{getPerformance,initializePerformance,trace};
2
2
 
3
3
  //# sourceMappingURL=firebase-performance.js.map
@@ -1,3 +1,3 @@
1
- import{registerVersion as e,_registerComponent as t,_getProvider,getApp as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.7.1/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.4"},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.4",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.4"),e(y,"0.6.4","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.4"),e(F,"0.4.4","esm2017")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,setLogLevel};
1
+ import{registerVersion as e,_registerComponent as t,_getProvider,getApp as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.7.2/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.4"},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.4",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.4"),e(y,"0.6.4","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.4"),e(F,"0.4.4","esm2017")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,setLogLevel};
2
2
 
3
3
  //# sourceMappingURL=firebase-remote-config.js.map
@@ -1,3 +1,3 @@
1
- import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.7.1/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.0",""),r(d,"0.12.0","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};
1
+ import{_getProvider,getApp as e,_registerComponent as t,registerVersion as r,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/10.7.2/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.0",""),r(d,"0.12.0","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};
2
2
 
3
3
  //# sourceMappingURL=firebase-storage.js.map