UNPKG

firebase

Version:

Firebase JavaScript library for web and Node.js

4 lines (2 loc) • 32.7 kB
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n,SDK_VERSION as s}from"https://www.gstatic.com/firebasejs/11.6.0/firebase-app.js";function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}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]||{},s=`${this.service}/${e}`,a=this.errors[e],i=a?function replaceTemplate(e,t){return e.replace(r,((e,n)=>{const s=t[n];return null!=s?String(s):`<${n}?>`}))}(a,n):"Error",o=`${this.serviceName}: ${i} (${s}).`;return new FirebaseError(s,o,n)}}const r=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),s=Object.keys(t);for(const r of n){if(!s.includes(r))return!1;const n=e[r],a=t[r];if(isObject(n)&&isObject(a)){if(!deepEqual(n,a))return!1}else if(n!==a)return!1}for(const e of s)if(!n.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,n=2){const s=t*Math.pow(n,e),r=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+r)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const i={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},o=a.INFO,c={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),r=c[t];if(!r)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[r](`[${s}] ${e.name}:`,...n)};class Logger{constructor(e){this.name=e,this._logLevel=o,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?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,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}let l,u;const g=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap;let m={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||d.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return 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(g.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const s=e.call(unwrap(this),t,...n);return d.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(h.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));h.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return 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,n)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{n(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&g.set(t,e)})).catch((()=>{})),p.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=transformCachableValue(e);return t!==e&&(f.set(e,t),p.set(t,e)),t}const unwrap=e=>p.get(e);const w=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],y=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(y.get(t))return y.get(t);const n=t.replace(/FromIndex$/,""),s=t!==n,r=v.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!r&&!w.includes(n))return;const method=async function(e,...t){const a=this.transaction(e,r?"readwrite":"readonly");let i=a.store;return s&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),r&&a.done]))[0]};return y.set(t,method),method}!function replaceTraps(e){m=e(m)}((e=>Object.assign(Object.assign({},e),{get:(t,n,s)=>getMethod(t,n)||e.get(t,n,s),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const C="@firebase/installations",b="0.6.13",E=1e4,S=`w:${b}`,I="FIS_v2",T=36e5,_=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 _.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`${I} ${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 F=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return F.test(t)?t:""}catch(e){return""}}function getKey(e){return`${e.appName}!${e.appId}`}const M=new Map;function fidChanged(e,t){const n=getKey(e);callFidChangeCallbacks(n,t),function broadcastFidChange(e,t){const n=function getBroadcastChannel(){!k&&"BroadcastChannel"in self&&(k=new BroadcastChannel("[Firebase] FID Change"),k.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return k}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===M.size&&k&&(k.close(),k=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=M.get(e);if(n)for(const e of n)e(t)}let k=null;const R="firebase-installations-store";let L=null;function getDbPromise(){return L||(L=function openDB(e,t,{blocked:n,upgrade:s,blocking:r,terminated:a}={}){const i=indexedDB.open(e,t),o=wrap(i);return s&&i.addEventListener("upgradeneeded",(e=>{s(wrap(i.result),e.oldVersion,e.newVersion,wrap(i.transaction),e)})),n&&i.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),r&&e.addEventListener("versionchange",(e=>r(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(R)}})),L}async function set(e,t){const n=getKey(e),s=(await getDbPromise()).transaction(R,"readwrite"),r=s.objectStore(R),a=await r.get(n);return await r.put(t,n),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(R,"readwrite");await n.objectStore(R).delete(t),await n.done}async function update(e,t){const n=getKey(e),s=(await getDbPromise()).transaction(R,"readwrite"),r=s.objectStore(R),a=await r.get(n),i=t(a);return void 0===i?await r.delete(n):await r.put(i,n),await s.done,!i||a&&a.fid===i.fid||fidChanged(e,i.fid),i}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),r=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(_.create("app-offline"))}}const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const s=getInstallationsEndpoint(e),r=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&r.append("x-firebase-client",e)}const i={fid:n,authVersion:I,appId:e.appId,sdkVersion:S},o={method:"POST",headers:r,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(s,o)));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:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=r.registrationPromise,r.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 _.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+E<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),r=getHeadersWithAuth(e,n),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&r.append("x-firebase-client",e)}const i={installation:{sdkVersion:S,appId:e.appId}},o={method:"POST",headers:r,body:JSON.stringify(i)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let n;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw _.create("not-registered");const r=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+T}(e)}(r))return s;if(1===r.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 s=n.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw _.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(s);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),s=Object.assign(Object.assign({},t),{authToken:n});return await set(e.appConfig,s),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:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw _.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+E<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 _.create("missing-app-config-values",{valueName:e})}const A="installations",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,A).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(A,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(C,b),e(C,b,"esm2017");const D="@firebase/remote-config",O="0.6.0";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",j=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported."});const B=["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&&B.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=n(),t={}){var s,r;e=getModularInstance(e);const a=_getProvider(e,P);if(a.isInitialized()){if(deepEqual(a.getOptions(),t))return a.getImmediate();throw j.create("already-initialized")}a.initialize({options:t});const i=a.getImmediate();return t.initialFetchResponse&&(i._initializePromise=Promise.all([i._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),i._storage.setActiveConfigEtag((null===(s=t.initialFetchResponse)||void 0===s?void 0:s.eTag)||""),i._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),i._storageCache.setLastFetchStatus("success"),i._storageCache.setActiveConfig((null===(r=t.initialFetchResponse)||void 0===r?void 0:r.config)||{})]).then(),i._isInitializationComplete=!0),i}async function activate(e){const t=getModularInstance(e),[n,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==s)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.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),n=new RemoteConfigAbortSignal;setTimeout((async()=>{n.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:n,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const n=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(n),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,n)=>(t[n]=getValue(e,n),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 n=getModularInstance(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=n._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new Value("default",String(n.defaultConfig[t])):(n._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 n=getModularInstance(e);switch(t){case"debug":n._logger.logLevel=a.DEBUG;break;case"silent":n._logger.logLevel=a.SILENT;break;default:n._logger.logLevel=a.ERROR}}async function setCustomSignals(e,t){const n=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void n._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void n._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await n._storageCache.setCustomSignals(t)}catch(e){n._logger.error(`Error encountered while setting custom signals: ${e}`)}}}class CachingClient{constructor(e,t,n,s){this.client=e,this.storage=t,this.storageCache=n,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const n=Date.now()-t,s=n<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${n}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;const s=await this.client.fetch(e),r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&r.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(r),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,n,s,r,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=s,this.apiKey=r,this.appId=a}async fetch(e){const[t,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,r={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},a={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:n,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},i={method:"POST",headers:r,body:JSON.stringify(a)},o=fetch(s,i),c=new Promise(((t,n)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",n(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"),j.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 j.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 j.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:n}){await function setAbortableTimeout(e,t){return new Promise(((n,s)=>{const r=Math.max(t-Date.now(),0),a=setTimeout(n,r);e.addEventListener((()=>{clearTimeout(a),s(j.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(e.signal,t);try{const t=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),t}catch(t){if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t))throw t;const s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,n,s,r){this.app=e,this._client=t,this._storageCache=n,this._storage=s,this._logger=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const n=e.target.error||void 0;return j.create(t,{originalErrorMessage:n&&(null==n?void 0:n.message)})}const N="app_namespace_store";class Storage{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}}class IndexedDbStorage extends Storage{constructor(e,t,n,s=function openDatabase(){return new Promise(((e,t)=>{try{const n=indexedDB.open("firebase_remote_config",1);n.onerror=e=>{t(toFirebaseError(e,"storage-open"))},n.onsuccess=t=>{e(t.target.result)},n.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(N,{keyPath:"compositeKey"})}}catch(e){t(j.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([N],"readwrite"),n=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",n,t),n}async getWithTransaction(e,t){return new Promise(((n,s)=>{const r=t.objectStore(N),a=this.createCompositeKey(e);try{const e=r.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;n(t?t.value:void 0)}}catch(e){s(j.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}}))}async setWithTransaction(e,t,n){return new Promise(((s,r)=>{const a=n.objectStore(N),i=this.createCompositeKey(e);try{const e=a.put({compositeKey:i,value:t});e.onerror=e=>{r(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){r(j.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([N],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const n=(await this.openDbPromise).transaction([N],"readwrite");return this.setWithTransaction(e,t,n)}async delete(e){const t=await this.openDbPromise;return new Promise(((n,s)=>{const r=t.transaction([N],"readwrite").objectStore(N),a=this.createCompositeKey(e);try{const e=r.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{n()}}catch(e){s(j.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const n=Object.assign(Object.assign({},t),e),s=Object.fromEntries(Object.entries(n).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw j.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),r=await e;r&&(this.lastFetchStatus=r);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const i=await n;i&&(this.activeConfig=i);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}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 n=!0;const s="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(s);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(s),e(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var e;t((null===(e=r.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(P,(function remoteConfigFactory(e,{options:t}){const n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate(),{projectId:i,apiKey:o,appId:c}=n.options;if(!i)throw j.create("registration-project-id");if(!o)throw j.create("registration-api-key");if(!c)throw j.create("registration-app-id");const l=(null==t?void 0:t.templateId)||"firebase",u=isIndexedDBAvailable()?new IndexedDbStorage(c,n.name,l):new InMemoryStorage,g=new StorageCache(u),h=new Logger(D);h.logLevel=a.ERROR;const d=new RestClient(r,s,l,i,o,c),f=new RetryingClient(d,u),p=new CachingClient(f,u,g,h),m=new RemoteConfig(n,p,g,u,h);return ensureInitialized(m),m}),"PUBLIC").setMultipleInstances(!0)),e(D,O),e(D,O,"esm2017")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,setCustomSignals,setLogLevel}; //# sourceMappingURL=firebase-remote-config.js.map