firebase
Version:
Firebase JavaScript library for web and Node.js
3 lines (2 loc) • 27.7 kB
JavaScript
import{registerVersion as t,_registerComponent as e,_getProvider as n,getApp as r,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/9.0.0-beta.7/firebase-app.js";var o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function s(t,e){for(var n=0,r=e.length,i=t.length;n<r;n++,i++)t[i]=e[n];return t}var a=function(t){function e(n,r,i){var o=t.call(this,r)||this;return o.code=n,o.customData=i,o.name="FirebaseError",Object.setPrototypeOf(o,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(o,c.prototype.create),o}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e}(Error),c=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n}return t.prototype.create=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var r=e[0]||{},i=this.service+"/"+t,o=this.errors[t],s=o?u(o,r):"Error",c=this.serviceName+": "+s+" ("+i+").",l=new a(i,c,r);return l},t}();function u(t,e){return t.replace(l,(function(t,n){var r=e[n];return null!=r?String(r):"<"+n+"?>"}))}var l=/\{\$([^}]+)}/g;function f(t,e,n){void 0===e&&(e=1e3),void 0===n&&(n=2);var r=e*Math.pow(n,t),i=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+i)}function h(t){return t&&t._delegate?t._delegate:t}var p,g,d=function(){function t(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}return t.prototype.setInstantiationMode=function(t){return this.instantiationMode=t,this},t.prototype.setMultipleInstances=function(t){return this.multipleInstances=t,this},t.prototype.setServiceProps=function(t){return this.serviceProps=t,this},t.prototype.setInstanceCreatedCallback=function(t){return this.onInstanceCreated=t,this},t}();!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(g||(g={}));var m={debug:g.DEBUG,verbose:g.VERBOSE,info:g.INFO,warn:g.WARN,error:g.ERROR,silent:g.SILENT},w=g.INFO,y=((p={})[g.DEBUG]="log",p[g.VERBOSE]="log",p[g.INFO]="info",p[g.WARN]="warn",p[g.ERROR]="error",p),_=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var i=(new Date).toISOString(),o=y[e];if(!o)throw new Error("Attempted to log a message with an invalid logType (value: "+e+")");console[o].apply(console,s(["["+i+"] "+t.name+":"],n))}},v=function(){function t(t){this.name=t,this._logLevel=w,this._logHandler=_,this._userLogHandler=null}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in g))throw new TypeError('Invalid value "'+t+'" assigned to `logLevel`');this._logLevel=t},enumerable:!1,configurable:!0}),t.prototype.setLogLevel=function(t){this._logLevel="string"==typeof t?m[t]:t},Object.defineProperty(t.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(t){this._userLogHandler=t},enumerable:!1,configurable:!0}),t.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,g.DEBUG],t)),this._logHandler.apply(this,s([this,g.DEBUG],t))},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,g.VERBOSE],t)),this._logHandler.apply(this,s([this,g.VERBOSE],t))},t.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,g.INFO],t)),this._logHandler.apply(this,s([this,g.INFO],t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,g.WARN],t)),this._logHandler.apply(this,s([this,g.WARN],t))},t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,g.ERROR],t)),this._logHandler.apply(this,s([this,g.ERROR],t))},t}();function b(t){return Array.prototype.slice.call(t)}function S(t){return new Promise((function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function C(t,e,n){var r,i=new Promise((function(i,o){S(r=t[e].apply(t,n)).then(i,o)}));return i.request=r,i}function E(t,e,n){var r=C(t,e,n);return r.then((function(t){if(t)return new M(t,r.request)}))}function I(t,e,n){n.forEach((function(n){Object.defineProperty(t.prototype,n,{get:function(){return this[e][n]},set:function(t){this[e][n]=t}})}))}function T(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return C(this[e],r,arguments)})}))}function O(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return this[e][r].apply(this[e],arguments)})}))}function P(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return E(this[e],r,arguments)})}))}function L(t){this._index=t}function M(t,e){this._cursor=t,this._request=e}function F(t){this._store=t}function j(t){this._tx=t,this.complete=new Promise((function(e,n){t.oncomplete=function(){e()},t.onerror=function(){n(t.error)},t.onabort=function(){n(t.error)}}))}function k(t,e,n){this._db=t,this.oldVersion=e,this.transaction=new j(n)}function D(t){this._db=t}I(L,"_index",["name","keyPath","multiEntry","unique"]),T(L,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),P(L,"_index",IDBIndex,["openCursor","openKeyCursor"]),I(M,"_cursor",["direction","key","primaryKey","value"]),T(M,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(t){t in IDBCursor.prototype&&(M.prototype[t]=function(){var e=this,n=arguments;return Promise.resolve().then((function(){return e._cursor[t].apply(e._cursor,n),S(e._request).then((function(t){if(t)return new M(t,e._request)}))}))})})),F.prototype.createIndex=function(){return new L(this._store.createIndex.apply(this._store,arguments))},F.prototype.index=function(){return new L(this._store.index.apply(this._store,arguments))},I(F,"_store",["name","keyPath","indexNames","autoIncrement"]),T(F,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),P(F,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),O(F,"_store",IDBObjectStore,["deleteIndex"]),j.prototype.objectStore=function(){return new F(this._tx.objectStore.apply(this._tx,arguments))},I(j,"_tx",["objectStoreNames","mode"]),O(j,"_tx",IDBTransaction,["abort"]),k.prototype.createObjectStore=function(){return new F(this._db.createObjectStore.apply(this._db,arguments))},I(k,"_db",["name","version","objectStoreNames"]),O(k,"_db",IDBDatabase,["deleteObjectStore","close"]),D.prototype.transaction=function(){return new j(this._db.transaction.apply(this._db,arguments))},I(D,"_db",["name","version","objectStoreNames"]),O(D,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(t){[F,L].forEach((function(e){t in e.prototype&&(e.prototype[t.replace("open","iterate")]=function(){var e=b(arguments),n=e[e.length-1],r=this._store||this._index,i=r[t].apply(r,e.slice(0,-1));i.onsuccess=function(){n(i.result)}})}))})),[L,F].forEach((function(t){t.prototype.getAll||(t.prototype.getAll=function(t,e){var n=this,r=[];return new Promise((function(i){n.iterateCursor(t,(function(t){t?(r.push(t.value),void 0===e||r.length!=e?t.continue():i(r)):i(r)}))}))})}));const A=new c("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function N(t){return t instanceof a&&t.code.includes("request-failed")}function x({projectId:t}){return`https://firebaseinstallations.googleapis.com/v1/projects/${t}/installations`}function R(t){return{token:t.token,requestStatus:2,expiresIn:(e=t.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()};var e}async function B(t,e){const n=(await e.json()).error;return A.create("request-failed",{requestName:t,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function q({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function $(t,{refreshToken:e}){const n=q(t);return n.append("Authorization",function(t){return`FIS_v2 ${t}`}(e)),n}async function H(t){const e=await t();return e.status>=500&&e.status<600?t():e}function K(t){return new Promise((e=>{setTimeout(e,t)}))}const V=/^[cdef][\w-]{21}$/;function U(){try{const t=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(t),t[0]=112+t[0]%16;const e=function(t){return(e=t,btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var e}(t);return V.test(e)?e:""}catch(t){return""}}function z(t){return`${t.appName}!${t.appId}`}const G=new Map;function W(t,e){const n=z(t);J(n,e),function(t,e){const n=function(){!Y&&"BroadcastChannel"in self&&(Y=new BroadcastChannel("[Firebase] FID Change"),Y.onmessage=t=>{J(t.data.key,t.data.fid)});return Y}();n&&n.postMessage({key:t,fid:e});0===G.size&&Y&&(Y.close(),Y=null)}(n,e)}function J(t,e){const n=G.get(t);if(n)for(const t of n)t(e)}let Y=null;const Z="firebase-installations-store";let Q=null;function X(){return Q||(Q=function(t,e,n){var r=C(indexedDB,"open",[t,e]),i=r.request;return i&&(i.onupgradeneeded=function(t){n&&n(new k(i.result,t.oldVersion,i.transaction))}),r.then((function(t){return new D(t)}))}("firebase-installations-database",1,(t=>{switch(t.oldVersion){case 0:t.createObjectStore(Z)}}))),Q}async function tt(t,e){const n=z(t),r=(await X()).transaction(Z,"readwrite"),i=r.objectStore(Z),o=await i.get(n);return await i.put(e,n),await r.complete,o&&o.fid===e.fid||W(t,e.fid),e}async function et(t){const e=z(t),n=(await X()).transaction(Z,"readwrite");await n.objectStore(Z).delete(e),await n.complete}async function nt(t,e){const n=z(t),r=(await X()).transaction(Z,"readwrite"),i=r.objectStore(Z),o=await i.get(n),s=e(o);return void 0===s?await i.delete(n):await i.put(s,n),await r.complete,!s||o&&o.fid===s.fid||W(t,s.fid),s}async function rt(t){let e;const n=await nt(t,(n=>{const r=function(t){return st(t||{fid:U(),registrationStatus:0})}(n),i=function(t,e){if(0===e.registrationStatus){if(!navigator.onLine){return{installationEntry:e,registrationPromise:Promise.reject(A.create("app-offline"))}}const n={fid:e.fid,registrationStatus:1,registrationTime:Date.now()};return{installationEntry:n,registrationPromise:async function(t,e){try{return tt(t,await async function(t,{fid:e}){const n=x(t),r=q(t),i={fid:e,authVersion:"FIS_v2",appId:t.appId,sdkVersion:"w:0.0.900-exp.6ef484a04"},o={method:"POST",headers:r,body:JSON.stringify(i)},s=await H((()=>fetch(n,o)));if(s.ok){const t=await s.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:R(t.authToken)}}throw await B("Create Installation",s)}(t,e))}catch(n){throw N(n)&&409===n.customData.serverCode?await et(t):await tt(t,{fid:e.fid,registrationStatus:0}),n}}(t,n)}}return 1===e.registrationStatus?{installationEntry:e,registrationPromise:it(t)}:{installationEntry:e}}(t,r);return e=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await e}:{installationEntry:n,registrationPromise:e}}async function it(t){let e=await ot(t);for(;1===e.registrationStatus;)await K(100),e=await ot(t);if(0===e.registrationStatus){const{installationEntry:e,registrationPromise:n}=await rt(t);return n||e}return e}function ot(t){return nt(t,(t=>{if(!t)throw A.create("installation-not-found");return st(t)}))}function st(t){return 1===(e=t).registrationStatus&&e.registrationTime+1e4<Date.now()?{fid:t.fid,registrationStatus:0}:t;var e}async function at({appConfig:t,platformLoggerProvider:e},n){const r=function(t,{fid:e}){return`${x(t)}/${e}/authTokens:generate`}(t,n),i=$(t,n),o=e.getImmediate({optional:!0});o&&i.append("x-firebase-client",o.getPlatformInfoString());const s={installation:{sdkVersion:"w:0.0.900-exp.6ef484a04"}},a={method:"POST",headers:i,body:JSON.stringify(s)},c=await H((()=>fetch(r,a)));if(c.ok){return R(await c.json())}throw await B("Generate Auth Token",c)}async function ct(t,e=!1){let n;const r=await nt(t.appConfig,(r=>{if(!lt(r))throw A.create("not-registered");const i=r.authToken;if(!e&&function(t){return 2===t.requestStatus&&!function(t){const e=Date.now();return e<t.creationTime||t.creationTime+t.expiresIn<e+36e5}(t)}(i))return r;if(1===i.requestStatus)return n=async function(t,e){let n=await ut(t.appConfig);for(;1===n.authToken.requestStatus;)await K(100),n=await ut(t.appConfig);const r=n.authToken;return 0===r.requestStatus?ct(t,e):r}(t,e),r;{if(!navigator.onLine)throw A.create("app-offline");const e=function(t){const e={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},t),{authToken:e})}(r);return n=async function(t,e){try{const n=await at(t,e),r=Object.assign(Object.assign({},e),{authToken:n});return await tt(t.appConfig,r),n}catch(n){if(!N(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},e),{authToken:{requestStatus:0}});await tt(t.appConfig,n)}else await et(t.appConfig);throw n}}(t,e),e}}));return n?await n:r.authToken}function ut(t){return nt(t,(t=>{if(!lt(t))throw A.create("not-registered");const e=t.authToken;return 1===(n=e).requestStatus&&n.requestTime+1e4<Date.now()?Object.assign(Object.assign({},t),{authToken:{requestStatus:0}}):t;var n}))}function lt(t){return void 0!==t&&2===t.registrationStatus}async function ft(t,e=!1){const n=t;await async function(t){const{registrationPromise:e}=await rt(t);e&&await e}(n.appConfig);return(await ct(n,e)).token}function ht(t){return A.create("missing-app-config-values",{valueName:t})}const pt=t=>{const e=t.getProvider("app-exp").getImmediate(),r=n(e,"installations-exp").getImmediate();return{getId:()=>async function(t){const e=t,{installationEntry:n,registrationPromise:r}=await rt(e.appConfig);return r?r.catch(console.error):ct(e).catch(console.error),n.fid}(r),getToken:t=>ft(r,t)}};e(new d("installations-exp",(t=>{const e=t.getProvider("app-exp").getImmediate();return{app:e,appConfig:function(t){if(!t||!t.options)throw ht("App Configuration");if(!t.name)throw ht("App Name");const e=["projectId","apiKey","appId"];for(const n of e)if(!t.options[n])throw ht(n);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(e),platformLoggerProvider:n(e,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),e(new d("installations-exp-internal",pt,"PRIVATE")),t("@firebase/installations-exp","0.0.900-exp.6ef484a04");const gt="@firebase/remote-config-exp";class dt{constructor(){this.listeners=[]}addEventListener(t){this.listeners.push(t)}abort(){this.listeners.forEach((t=>t()))}}const mt=new c("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}."});const wt=["1","true","t","yes","y","on"];class yt{constructor(t,e=""){this._source=t,this._value=e}asString(){return this._value}asBoolean(){return"static"!==this._source&&wt.indexOf(this._value.toLowerCase())>=0}asNumber(){if("static"===this._source)return 0;let t=Number(this._value);return isNaN(t)&&(t=0),t}getSource(){return this._source}}function _t(t=r()){t=h(t);return n(t,"remote-config-exp").getImmediate()}async function vt(t){const e=h(t),[n,r]=await Promise.all([e._storage.getLastSuccessfulFetchResponse(),e._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([e._storageCache.setActiveConfig(n.config),e._storage.setActiveConfigEtag(n.eTag)]),!0)}function bt(t){const e=h(t);return e._initializePromise||(e._initializePromise=e._storageCache.loadFromStorage().then((()=>{e._isInitializationComplete=!0}))),e._initializePromise}async function St(t){const e=h(t),n=new dt;setTimeout((async()=>{n.abort()}),e.settings.fetchTimeoutMillis);try{await e._client.fetch({cacheMaxAgeMillis:e.settings.minimumFetchIntervalMillis,signal:n}),await e._storageCache.setLastFetchStatus("success")}catch(t){const n=function(t,e){return t instanceof a&&-1!==t.code.indexOf(e)}(t,"fetch-throttle")?"throttle":"failure";throw await e._storageCache.setLastFetchStatus(n),t}}function Ct(t){const e=h(t);return function(t={},e={}){return Object.keys(Object.assign(Object.assign({},t),e))}(e._storageCache.getActiveConfig(),e.defaultConfig).reduce(((e,n)=>(e[n]=Ot(t,n),e)),{})}function Et(t,e){return Ot(h(t),e).asBoolean()}function It(t,e){return Ot(h(t),e).asNumber()}function Tt(t,e){return Ot(h(t),e).asString()}function Ot(t,e){const n=h(t);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${e}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const r=n._storageCache.getActiveConfig();return r&&void 0!==r[e]?new yt("remote",r[e]):n.defaultConfig&&void 0!==n.defaultConfig[e]?new yt("default",String(n.defaultConfig[e])):(n._logger.debug(`Returning static value for key "${e}". Define a default or remote value if this is unintentional.`),new yt("static"))}function Pt(t,e){const n=h(t);switch(e){case"debug":n._logger.logLevel=g.DEBUG;break;case"silent":n._logger.logLevel=g.SILENT;break;default:n._logger.logLevel=g.ERROR}}class Lt{constructor(t,e,n,r){this.client=t,this.storage=e,this.storageCache=n,this.logger=r}isCachedDataFresh(t,e){if(!e)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const n=Date.now()-e,r=n<=t;return this.logger.debug(`Config fetch cache check. Cache age millis: ${n}. Cache max age millis (minimumFetchIntervalMillis setting): ${t}. Is cache hit: ${r}.`),r}async fetch(t){const[e,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(t.cacheMaxAgeMillis,e))return n;t.eTag=n&&n.eTag;const r=await this.client.fetch(t),i=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===r.status&&i.push(this.storage.setLastSuccessfulFetchResponse(r)),await Promise.all(i),r}}function Mt(t=navigator){return t.languages&&t.languages[0]||t.language}class Ft{constructor(t,e,n,r,i,o){this.firebaseInstallations=t,this.sdkVersion=e,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=o}async fetch(t){const[e,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),r=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,i={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":t.eTag||"*"},o={sdk_version:this.sdkVersion,app_instance_id:e,app_instance_id_token:n,app_id:this.appId,language_code:Mt()},s={method:"POST",headers:i,body:JSON.stringify(o)},a=fetch(r,s),c=new Promise(((e,n)=>{t.signal.addEventListener((()=>{const t=new Error("The operation was aborted.");t.name="AbortError",n(t)}))}));let u;try{await Promise.race([a,c]),u=await a}catch(t){let e="fetch-client-network";throw"AbortError"===t.name&&(e="fetch-timeout"),mt.create(e,{originalErrorMessage:t.message})}let l=u.status;const f=u.headers.get("ETag")||void 0;let h,p;if(200===u.status){let t;try{t=await u.json()}catch(t){throw mt.create("fetch-client-parse",{originalErrorMessage:t.message})}h=t.entries,p=t.state}if("INSTANCE_STATE_UNSPECIFIED"===p?l=500:"NO_CHANGE"===p?l=304:"NO_TEMPLATE"!==p&&"EMPTY_CONFIG"!==p||(h={}),304!==l&&200!==l)throw mt.create("fetch-status",{httpStatus:l});return{status:l,eTag:f,config:h}}}class jt{constructor(t,e){this.client=t,this.storage=e}async fetch(t){const e=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(t,e)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){await function(t,e){return new Promise(((n,r)=>{const i=Math.max(e-Date.now(),0),o=setTimeout(n,i);t.addEventListener((()=>{clearTimeout(o),r(mt.create("fetch-throttle",{throttleEndTimeMillis:e}))}))}))}(t.signal,e);try{const e=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),e}catch(e){if(!function(t){if(!(t instanceof a&&t.customData))return!1;const e=Number(t.customData.httpStatus);return 429===e||500===e||503===e||504===e}(e))throw e;const r={throttleEndTimeMillis:Date.now()+f(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class kt{constructor(t,e,n,r,i){this.app=t,this._client=e,this._storageCache=n,this._storage=r,this._logger=i,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 Dt(t,e){const n=t.target.error||void 0;return mt.create(e,{originalErrorMessage:n&&n.message})}class At{constructor(t,e,n,r=function(){return new Promise(((t,e)=>{const n=indexedDB.open("firebase_remote_config",1);n.onerror=t=>{e(Dt(t,"storage-open"))},n.onsuccess=e=>{t(e.target.result)},n.onupgradeneeded=t=>{const e=t.target.result;switch(t.oldVersion){case 0:e.createObjectStore("app_namespace_store",{keyPath:"compositeKey"})}}}))}()){this.appId=t,this.appName=e,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(t){return this.set("last_fetch_status",t)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(t){return this.set("last_successful_fetch_timestamp_millis",t)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(t){return this.set("last_successful_fetch_response",t)}getActiveConfig(){return this.get("active_config")}setActiveConfig(t){return this.set("active_config",t)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(t){return this.set("active_config_etag",t)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(t){return this.set("throttle_metadata",t)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(t){const e=await this.openDbPromise;return new Promise(((n,r)=>{const i=e.transaction(["app_namespace_store"],"readonly").objectStore("app_namespace_store"),o=this.createCompositeKey(t);try{const t=i.get(o);t.onerror=t=>{r(Dt(t,"storage-get"))},t.onsuccess=t=>{const e=t.target.result;n(e?e.value:void 0)}}catch(t){r(mt.create("storage-get",{originalErrorMessage:t&&t.message}))}}))}async set(t,e){const n=await this.openDbPromise;return new Promise(((r,i)=>{const o=n.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),s=this.createCompositeKey(t);try{const t=o.put({compositeKey:s,value:e});t.onerror=t=>{i(Dt(t,"storage-set"))},t.onsuccess=()=>{r()}}catch(t){i(mt.create("storage-set",{originalErrorMessage:t&&t.message}))}}))}async delete(t){const e=await this.openDbPromise;return new Promise(((n,r)=>{const i=e.transaction(["app_namespace_store"],"readwrite").objectStore("app_namespace_store"),o=this.createCompositeKey(t);try{const t=i.delete(o);t.onerror=t=>{r(Dt(t,"storage-delete"))},t.onsuccess=()=>{n()}}catch(t){r(mt.create("storage-delete",{originalErrorMessage:t&&t.message}))}}))}createCompositeKey(t){return[this.appId,this.appName,this.namespace,t].join()}}class Nt{constructor(t){this.storage=t}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){const t=this.storage.getLastFetchStatus(),e=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),r=await t;r&&(this.lastFetchStatus=r);const i=await e;i&&(this.lastSuccessfulFetchTimestampMillis=i);const o=await n;o&&(this.activeConfig=o)}setLastFetchStatus(t){return this.lastFetchStatus=t,this.storage.setLastFetchStatus(t)}setLastSuccessfulFetchTimestampMillis(t){return this.lastSuccessfulFetchTimestampMillis=t,this.storage.setLastSuccessfulFetchTimestampMillis(t)}setActiveConfig(t){return this.activeConfig=t,this.storage.setActiveConfig(t)}}async function xt(t){return t=h(t),await St(t),vt(t)}e(new d("remote-config-exp",(function(t,{instanceIdentifier:e}){const n=t.getProvider("app-exp").getImmediate(),r=t.getProvider("installations-exp-internal").getImmediate();if("undefined"==typeof window)throw mt.create("registration-window");const{projectId:o,apiKey:s,appId:a}=n.options;if(!o)throw mt.create("registration-project-id");if(!s)throw mt.create("registration-api-key");if(!a)throw mt.create("registration-app-id");e=e||"firebase";const c=new At(a,n.name,e),u=new Nt(c),l=new v(gt);l.logLevel=g.ERROR;const f=new Ft(r,i,e,o,s,a),h=new jt(f,c),p=new Lt(h,c,u,l),d=new kt(n,p,u,c,l);return bt(d),d}),"PUBLIC").setMultipleInstances(!0)),t(gt,"0.0.900-exp.6ef484a04");export{vt as activate,bt as ensureInitialized,xt as fetchAndActivate,St as fetchConfig,Ct as getAll,Et as getBoolean,It as getNumber,_t as getRemoteConfig,Tt as getString,Ot as getValue,Pt as setLogLevel};
//# sourceMappingURL=firebase-remote-config.js.map