firebase 12.6.0-canary.9101b4611 → 12.6.0-canary.a09ef786f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-ai.js +1 -1
- package/firebase-ai.js.map +1 -1
- package/firebase-analytics-compat.js +1 -1
- package/firebase-analytics.js +1 -1
- package/firebase-app-check-compat.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- package/firebase-auth-compat.js +1 -1
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +6 -6
- package/firebase-data-connect.js +1 -1
- package/firebase-database-compat.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +2 -2
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-functions-compat.js +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations-compat.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-compat.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-compat.js +1 -1
- package/firebase-performance-standalone-compat.js +7 -7
- package/firebase-performance.js +1 -1
- package/firebase-remote-config-compat.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage-compat.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +29 -29
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.6.0-canary.9101b4611/firebase-app.js";const s="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+s+") INTERNAL ASSERT FAILED: "+e)};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]||{},i=`${this.service}/${e}`,s=this.errors[e],r=s?function replaceTemplate(e,t){return e.replace(a,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(s,n):"Error",o=`${this.serviceName}: ${r} (${i}).`;return new FirebaseError(i,o,n)}}const a=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const s of n){if(!i.includes(s))return!1;const n=e[s],a=t[s];if(isObject(n)&&isObject(a)){if(!deepEqual(n,a))return!1}else if(n!==a)return!1}for(const e of i)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 i=t*Math.pow(n,e),s=Math.round(.5*i*(Math.random()-.5)*2);return Math.min(144e5,i+s)}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 r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const o={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},c=r.INFO,l={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const i=(new Date).toISOString(),s=l[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${i}] ${e.name}:`,...n)};class Logger{constructor(e){this.name=e,this._logLevel=c,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?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,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}let g,u;const h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap;let w={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||f.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(h.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const i=e.call(unwrap(this),t,...n);return f.set(i,t.sort?t.sort():[t]),wrap(i)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,w):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&&h.set(t,e)})).catch((()=>{})),m.set(t,e),t}(e);if(p.has(e))return p.get(e);const t=transformCachableValue(e);return t!==e&&(p.set(e,t),m.set(t,e)),t}const unwrap=e=>m.get(e);const b=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],v=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(v.get(t))return v.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=y.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!b.includes(n))return;const method=async function(e,...t){const a=this.transaction(e,s?"readwrite":"readonly");let r=a.store;return i&&(r=r.index(t.shift())),(await Promise.all([r[n](...t),s&&a.done]))[0]};return v.set(t,method),method}!function replaceTraps(e){w=e(w)}((e=>({...e,get:(t,n,i)=>getMethod(t,n)||e.get(t,n,i),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const C="@firebase/installations",E="0.6.19-canary.9101b4611",I=1e4,S=`w:${E}`,T="FIS_v2",R=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`${T} ${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 k=/^[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 k.test(t)?t:""}catch{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(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===M.size&&F&&(F.close(),F=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=M.get(e);if(n)for(const e of n)e(t)}let F=null;const A="firebase-installations-store";let L=null;function getDbPromise(){return L||(L=function openDB(e,t,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return i&&r.addEventListener("upgradeneeded",(e=>{i(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),n&&r.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(A)}})),L}async function set(e,t){const n=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite"),s=i.objectStore(A),a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(A,"readwrite");await n.objectStore(A).delete(t),await n.done}async function update(e,t){const n=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite"),s=i.objectStore(A),a=await s.get(n),r=t(a);return void 0===r?await s.delete(n):await s.put(r,n),await i.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const i=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),s=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()},i=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const i=getInstallationsEndpoint(e),s=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const r={fid:n,authVersion:T,appId:e.appId,sdkVersion:S},o={method:"POST",headers:s,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(i,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:i}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,i);return t=s.registrationPromise,s.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+I<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const i=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),s=getHeadersWithAuth(e,n),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const r={installation:{sdkVersion:S,appId:e.appId}},o={method:"POST",headers:s,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(i,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 i=await update(e.appConfig,(i=>{if(!isEntryRegistered(i))throw _.create("not-registered");const s=i.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+R}(e)}(s))return i;if(1===s.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 i=n.authToken;return 0===i.requestStatus?refreshAuthToken(e,t):i}(e,t),i;{if(!navigator.onLine)throw _.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(i);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),i={...t,authToken:n};return await set(e.appConfig,i),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n={...t,authToken:{requestStatus:0}};await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:i.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+I<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const 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 D="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,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:i}=await getInstallationEntry(t);return i?i.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(C,E),e(C,E,"esm2020");const B="@firebase/remote-config",O="0.7.0-canary.9101b4611";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",N=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}"});const H=["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&&H.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={}){e=getModularInstance(e);const i=_getProvider(e,P);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw N.create("already-initialized")}i.initialize({options:t});const s=i.getImmediate();return t.initialFetchResponse&&(s._initializePromise=Promise.all([s._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),s._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),s._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),s._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),s._storageCache.setLastFetchStatus("success"),s._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),s._isInitializationComplete=!0),s}async function activate(e){const t=getModularInstance(e),[n,i]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.templateVersion&&n.eTag!==i)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag),t._storage.setActiveConfigTemplateVersion(n.templateVersion)]),!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 i=t._storageCache.getCustomSignals();i&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(i)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:n,customSignals:i}),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({...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 i=n._storageCache.getActiveConfig();return i&&void 0!==i[t]?new Value("remote",i[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=r.DEBUG;break;case"silent":n._logger.logLevel=r.SILENT;break;default:n._logger.logLevel=r.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 i=t[e];if("string"==typeof i&&i.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}`)}}}function onConfigUpdate(e,t){const n=getModularInstance(e);return n._realtimeHandler.addObserver(t),()=>{n._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,n,i){this.client=e,this.storage=t,this.storageCache=n,this.logger=i}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const n=Date.now()-t,i=n<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${n}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${i}.`),i}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 i=await this.client.fetch(e),s=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===i.status&&s.push(this.storage.setLastSuccessfulFetchResponse(i)),await Promise.all(s),i}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,n,i,s,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=i,this.apiKey=s,this.appId=a}async fetch(e){const[t,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"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},r={method:"POST",headers:s,body:JSON.stringify(a)},o=fetch(i,r),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"===e?.name&&(t="fetch-timeout"),N.create(t,{originalErrorMessage:e?.message})}let g=l.status;const u=l.headers.get("ETag")||void 0;let h,d,f;if(200===l.status){let e;try{e=await l.json()}catch(e){throw N.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion}if("INSTANCE_STATE_UNSPECIFIED"===d?g=500:"NO_CHANGE"===d?g=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={}),304!==g&&200!==g)throw N.create("fetch-status",{httpStatus:g});return{status:g,eTag:u,config:h,templateVersion:f}}}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,i)=>{const s=Math.max(t-Date.now(),0),a=setTimeout(n,s);e.addEventListener((()=>{clearTimeout(a),i(N.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 i={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(i),this.attemptFetch(e,i)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,n,i,s,a){this.app=e,this._client=t,this._storageCache=n,this._storage=i,this._logger=s,this._realtimeHandler=a,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const n=e.target.error||void 0;return N.create(t,{originalErrorMessage:n&&n?.message})}const x="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")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,n,i=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(x,{keyPath:"compositeKey"})}}catch(e){t(N.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=i}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([x],"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,i)=>{const s=t.objectStore(x),a=this.createCompositeKey(e);try{const e=s.get(a);e.onerror=e=>{i(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;n(t?t.value:void 0)}}catch(e){i(N.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,n){return new Promise(((i,s)=>{const a=n.objectStore(x),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{s(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{i()}}catch(e){s(N.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([x],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const n=(await this.openDbPromise).transaction([x],"readwrite");return this.setWithTransaction(e,t,n)}async delete(e){const t=await this.openDbPromise;return new Promise(((n,i)=>{const s=t.transaction([x],"readwrite").objectStore(x),a=this.createCompositeKey(e);try{const e=s.delete(a);e.onerror=e=>{i(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{n()}}catch(e){i(N.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const n={...t,...e},i=Object.fromEntries(Object.entries(n).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(i).length>100)throw N.create("custom-signal-max-allowed-signals",{maxSignals:100});return i}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(),i=this.storage.getCustomSignals(),s=await e;s&&(this.lastFetchStatus=s);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await n;r&&(this.activeConfig=r);const o=await i;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context))return void i.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const V="X-Goog-Api-Key",j="X-Goog-Firebase-Installations-Auth",$="featureDisabled",q="retryIntervalSeconds",U="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,n,i,s,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=n,this.namespace=i,this.projectId=s,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,n=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+n),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),n=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:n,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,n,i){const s=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[V]:this.apiKey,[j]:n,"Content-Type":"application/json",Accept:"application/json","If-None-Match":s||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:i})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const n=this.getRealtimeUrl();return await this.establishRealtimeConnection(n,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),n=Date.now(),i=Math.max(0,t-n);await this.makeRealtimeHttpConnection(i)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),n=e.indexOf("}",t);return t<0||n<0||t>=n?"":e.substring(t,n+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t){const n=new Set,i=new Set(Object.keys(e||{})),s=new Set(Object.keys(t||{}));for(const a of i)s.has(a)&&e[a]===t[a]||n.add(a);for(const e of s)i.has(e)||n.add(e);return n}async fetchLatestConfig(e,t){const n=e-1,i=3-n,s=this.storageCache.getCustomSignals();s&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:s,fetchType:"REALTIME",fetchAttempt:i},r=await this.cachingClient.fetch(e);let o=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(r,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(n,t);if(null==r.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==o&&(o={});const c=this.getChangedParams(r.config,o);if(0===c.size)return void this.logger.debug("Config was fetched, but no params changed.");const l={getUpdatedKeys:()=>new Set(c)};this.executeAllListenerCallbacks(l)}catch(e){const t=e instanceof Error?e.message:String(e),n=N.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(n)}}async autoFetch(e,t){if(0===e){const e=N.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const n=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,n))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,n="";for(;;){const{done:i,value:s}=await e.read();if(i)break;if(t=this.decoder.decode(s,{stream:!0}),n+=t,t.includes("}")){if(n=this.parseAndValidateConfigUpdateMessage(n),0===n.length)continue;try{const e=JSON.parse(n);if(this.isEventListenersEmpty())break;if($ in e&&!0===e[$]){const e=N.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(U in e){const t=await this.storage.getActiveConfigTemplateVersion(),n=Number(e[U]);t&&n>t&&await this.autoFetch(3,n)}if(q in e){const t=Number(e[q]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(N.create("update-message-invalid",{originalErrorMessage:t}))}n=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let n,i;try{if(n=await this.createRealtimeConnection(),i=n.status,n.ok&&n.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=n.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===i||this.isStatusCodeRetryable(i));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||n?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${i}`,t=N.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,n=!this.isConnectionActive,i=!this.isInBackground;return e&&t&&n&&i}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=N.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{t(s.error?.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(),s=e.getProvider("installations-internal").getImmediate(),{projectId:a,apiKey:o,appId:c}=n.options;if(!a)throw N.create("registration-project-id");if(!o)throw N.create("registration-api-key");if(!c)throw N.create("registration-app-id");const l=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(c,n.name,l):new InMemoryStorage,u=new StorageCache(g),h=new Logger(B);h.logLevel=r.ERROR;const d=new RestClient(s,i,l,a,o,c),f=new RetryingClient(d,g),p=new CachingClient(f,g,u,h),m=new RealtimeHandler(s,g,i,l,a,o,c,h,u,p),w=new RemoteConfig(n,p,u,g,h,m);return ensureInitialized(w),w}),"PUBLIC").setMultipleInstances(!0)),e(B,O),e(B,O,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
|
|
1
|
+
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/12.6.0-canary.a09ef786f/firebase-app.js";const s="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+s+") INTERNAL ASSERT FAILED: "+e)};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]||{},i=`${this.service}/${e}`,s=this.errors[e],r=s?function replaceTemplate(e,t){return e.replace(a,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(s,n):"Error",o=`${this.serviceName}: ${r} (${i}).`;return new FirebaseError(i,o,n)}}const a=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const s of n){if(!i.includes(s))return!1;const n=e[s],a=t[s];if(isObject(n)&&isObject(a)){if(!deepEqual(n,a))return!1}else if(n!==a)return!1}for(const e of i)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 i=t*Math.pow(n,e),s=Math.round(.5*i*(Math.random()-.5)*2);return Math.min(144e5,i+s)}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 r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const o={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},c=r.INFO,l={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const i=(new Date).toISOString(),s=l[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${i}] ${e.name}:`,...n)};class Logger{constructor(e){this.name=e,this._logLevel=c,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?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,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}let g,u;const h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap;let w={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||f.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(h.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...n){const i=e.call(unwrap(this),t,...n);return f.set(i,t.sort?t.sort():[t]),wrap(i)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{n(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,w):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&&h.set(t,e)})).catch((()=>{})),m.set(t,e),t}(e);if(p.has(e))return p.get(e);const t=transformCachableValue(e);return t!==e&&(p.set(e,t),m.set(t,e)),t}const unwrap=e=>m.get(e);const b=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],v=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(v.get(t))return v.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=y.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!b.includes(n))return;const method=async function(e,...t){const a=this.transaction(e,s?"readwrite":"readonly");let r=a.store;return i&&(r=r.index(t.shift())),(await Promise.all([r[n](...t),s&&a.done]))[0]};return v.set(t,method),method}!function replaceTraps(e){w=e(w)}((e=>({...e,get:(t,n,i)=>getMethod(t,n)||e.get(t,n,i),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})));const C="@firebase/installations",E="0.6.19-canary.a09ef786f",I=1e4,S=`w:${E}`,T="FIS_v2",R=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`${T} ${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 k=/^[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 k.test(t)?t:""}catch{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(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();n&&n.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===M.size&&F&&(F.close(),F=null)}()}(n,t)}function callFidChangeCallbacks(e,t){const n=M.get(e);if(n)for(const e of n)e(t)}let F=null;const A="firebase-installations-store";let L=null;function getDbPromise(){return L||(L=function openDB(e,t,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return i&&r.addEventListener("upgradeneeded",(e=>{i(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),n&&r.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(A)}})),L}async function set(e,t){const n=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite"),s=i.objectStore(A),a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),n=(await getDbPromise()).transaction(A,"readwrite");await n.objectStore(A).delete(t),await n.done}async function update(e,t){const n=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite"),s=i.objectStore(A),a=await s.get(n),r=t(a);return void 0===r?await s.delete(n):await s.put(r,n),await i.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const n=await update(e.appConfig,(n=>{const i=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(n),s=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()},i=async function registerInstallation(e,t){try{const n=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const i=getInstallationsEndpoint(e),s=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const r={fid:n,authVersion:T,appId:e.appId,sdkVersion:S},o={method:"POST",headers:s,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(i,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:i}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,i);return t=s.registrationPromise,s.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+I<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},n){const i=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,n),s=getHeadersWithAuth(e,n),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&s.append("x-firebase-client",e)}const r={installation:{sdkVersion:S,appId:e.appId}},o={method:"POST",headers:s,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(i,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 i=await update(e.appConfig,(i=>{if(!isEntryRegistered(i))throw _.create("not-registered");const s=i.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+R}(e)}(s))return i;if(1===s.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 i=n.authToken;return 0===i.requestStatus?refreshAuthToken(e,t):i}(e,t),i;{if(!navigator.onLine)throw _.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(i);return n=async function fetchAuthTokenFromServer(e,t){try{const n=await generateAuthTokenRequest(e,t),i={...t,authToken:n};return await set(e.appConfig,i),n}catch(n){if(!isServerError(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n={...t,authToken:{requestStatus:0}};await set(e.appConfig,n)}else await remove(e.appConfig);throw n}}(e,t),t}}));return n?await n:i.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+I<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const 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 D="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,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:n,registrationPromise:i}=await getInstallationEntry(t);return i?i.catch(console.error):refreshAuthToken(t).catch(console.error),n.fid}(n),getToken:e=>getToken(n,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(C,E),e(C,E,"esm2020");const B="@firebase/remote-config",O="0.7.0-canary.a09ef786f";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",N=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}"});const H=["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&&H.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={}){e=getModularInstance(e);const i=_getProvider(e,P);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw N.create("already-initialized")}i.initialize({options:t});const s=i.getImmediate();return t.initialFetchResponse&&(s._initializePromise=Promise.all([s._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),s._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),s._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),s._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),s._storageCache.setLastFetchStatus("success"),s._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),s._isInitializationComplete=!0),s}async function activate(e){const t=getModularInstance(e),[n,i]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.templateVersion&&n.eTag!==i)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag),t._storage.setActiveConfigTemplateVersion(n.templateVersion)]),!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 i=t._storageCache.getCustomSignals();i&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(i)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:n,customSignals:i}),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({...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 i=n._storageCache.getActiveConfig();return i&&void 0!==i[t]?new Value("remote",i[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=r.DEBUG;break;case"silent":n._logger.logLevel=r.SILENT;break;default:n._logger.logLevel=r.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 i=t[e];if("string"==typeof i&&i.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}`)}}}function onConfigUpdate(e,t){const n=getModularInstance(e);return n._realtimeHandler.addObserver(t),()=>{n._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,n,i){this.client=e,this.storage=t,this.storageCache=n,this.logger=i}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const n=Date.now()-t,i=n<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${n}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${i}.`),i}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 i=await this.client.fetch(e),s=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===i.status&&s.push(this.storage.setLastSuccessfulFetchResponse(i)),await Promise.all(s),i}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,n,i,s,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=i,this.apiKey=s,this.appId=a}async fetch(e){const[t,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"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},r={method:"POST",headers:s,body:JSON.stringify(a)},o=fetch(i,r),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"===e?.name&&(t="fetch-timeout"),N.create(t,{originalErrorMessage:e?.message})}let g=l.status;const u=l.headers.get("ETag")||void 0;let h,d,f;if(200===l.status){let e;try{e=await l.json()}catch(e){throw N.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion}if("INSTANCE_STATE_UNSPECIFIED"===d?g=500:"NO_CHANGE"===d?g=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={}),304!==g&&200!==g)throw N.create("fetch-status",{httpStatus:g});return{status:g,eTag:u,config:h,templateVersion:f}}}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,i)=>{const s=Math.max(t-Date.now(),0),a=setTimeout(n,s);e.addEventListener((()=>{clearTimeout(a),i(N.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 i={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(i),this.attemptFetch(e,i)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,n,i,s,a){this.app=e,this._client=t,this._storageCache=n,this._storage=i,this._logger=s,this._realtimeHandler=a,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const n=e.target.error||void 0;return N.create(t,{originalErrorMessage:n&&n?.message})}const x="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")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,n,i=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(x,{keyPath:"compositeKey"})}}catch(e){t(N.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=i}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([x],"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,i)=>{const s=t.objectStore(x),a=this.createCompositeKey(e);try{const e=s.get(a);e.onerror=e=>{i(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;n(t?t.value:void 0)}}catch(e){i(N.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,n){return new Promise(((i,s)=>{const a=n.objectStore(x),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{s(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{i()}}catch(e){s(N.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([x],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const n=(await this.openDbPromise).transaction([x],"readwrite");return this.setWithTransaction(e,t,n)}async delete(e){const t=await this.openDbPromise;return new Promise(((n,i)=>{const s=t.transaction([x],"readwrite").objectStore(x),a=this.createCompositeKey(e);try{const e=s.delete(a);e.onerror=e=>{i(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{n()}}catch(e){i(N.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const n={...t,...e},i=Object.fromEntries(Object.entries(n).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(i).length>100)throw N.create("custom-signal-max-allowed-signals",{maxSignals:100});return i}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(),i=this.storage.getCustomSignals(),s=await e;s&&(this.lastFetchStatus=s);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await n;r&&(this.activeConfig=r);const o=await i;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context))return void i.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const V="X-Goog-Api-Key",j="X-Goog-Firebase-Installations-Auth",$="featureDisabled",q="retryIntervalSeconds",U="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,n,i,s,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=n,this.namespace=i,this.projectId=s,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,n=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+n),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),n=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:n,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,n,i){const s=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[V]:this.apiKey,[j]:n,"Content-Type":"application/json",Accept:"application/json","If-None-Match":s||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:i})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const n=this.getRealtimeUrl();return await this.establishRealtimeConnection(n,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),n=Date.now(),i=Math.max(0,t-n);await this.makeRealtimeHttpConnection(i)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),n=e.indexOf("}",t);return t<0||n<0||t>=n?"":e.substring(t,n+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t){const n=new Set,i=new Set(Object.keys(e||{})),s=new Set(Object.keys(t||{}));for(const a of i)s.has(a)&&e[a]===t[a]||n.add(a);for(const e of s)i.has(e)||n.add(e);return n}async fetchLatestConfig(e,t){const n=e-1,i=3-n,s=this.storageCache.getCustomSignals();s&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:s,fetchType:"REALTIME",fetchAttempt:i},r=await this.cachingClient.fetch(e);let o=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(r,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(n,t);if(null==r.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==o&&(o={});const c=this.getChangedParams(r.config,o);if(0===c.size)return void this.logger.debug("Config was fetched, but no params changed.");const l={getUpdatedKeys:()=>new Set(c)};this.executeAllListenerCallbacks(l)}catch(e){const t=e instanceof Error?e.message:String(e),n=N.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(n)}}async autoFetch(e,t){if(0===e){const e=N.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const n=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,n))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,n="";for(;;){const{done:i,value:s}=await e.read();if(i)break;if(t=this.decoder.decode(s,{stream:!0}),n+=t,t.includes("}")){if(n=this.parseAndValidateConfigUpdateMessage(n),0===n.length)continue;try{const e=JSON.parse(n);if(this.isEventListenersEmpty())break;if($ in e&&!0===e[$]){const e=N.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(U in e){const t=await this.storage.getActiveConfigTemplateVersion(),n=Number(e[U]);t&&n>t&&await this.autoFetch(3,n)}if(q in e){const t=Number(e[q]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(N.create("update-message-invalid",{originalErrorMessage:t}))}n=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let n,i;try{if(n=await this.createRealtimeConnection(),i=n.status,n.ok&&n.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=n.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===i||this.isStatusCodeRetryable(i));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||n?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${i}`,t=N.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,n=!this.isConnectionActive,i=!this.isInBackground;return e&&t&&n&&i}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=N.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{t(s.error?.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(),s=e.getProvider("installations-internal").getImmediate(),{projectId:a,apiKey:o,appId:c}=n.options;if(!a)throw N.create("registration-project-id");if(!o)throw N.create("registration-api-key");if(!c)throw N.create("registration-app-id");const l=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(c,n.name,l):new InMemoryStorage,u=new StorageCache(g),h=new Logger(B);h.logLevel=r.ERROR;const d=new RestClient(s,i,l,a,o,c),f=new RetryingClient(d,g),p=new CachingClient(f,g,u,h),m=new RealtimeHandler(s,g,i,l,a,o,c,h,u,p),w=new RemoteConfig(n,p,u,g,h,m);return ensureInitialized(w),w}),"PUBLIC").setMultipleInstances(!0)),e(B,O),e(B,O,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=firebase-remote-config.js.map
|
|
@@ -13,5 +13,5 @@
|
|
|
13
13
|
<rect width="24" height="24" fill="white"/>
|
|
14
14
|
</clipPath>
|
|
15
15
|
</defs>`,n.innerText="Preview backend running in this workspace."),n.setAttribute("id",s)}"loading"===document.readyState?window.addEventListener("DOMContentLoaded",r):r()}}class o extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,j.prototype.create)}}class j{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var s,r=t[0]||{},n=this.service+"/"+e,i=this.errors[e],i=i?(s=r,i.replace(G,(e,t)=>{var r=s[t];return null!=r?String(r):`<${t}?>`})):"Error",i=this.serviceName+`: ${i} (${n}).`;return new o(n,i,r)}}let G=/\{\$([^}]+)}/g;function n(e){return e&&e._delegate?e._delegate:e}class X{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}}let Z="firebasestorage.googleapis.com",$="storageBucket";class p extends o{constructor(e,t,r=0){super(h(e),`Firebase Storage: ${t} (${h(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,p.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return h(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=this._baseMessage+`
|
|
16
|
-
`+this.customData.serverResponse:this.message=this._baseMessage}}var f,i,e,K;function h(e){return"storage/"+e}function l(){return new p(f.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function J(){return new p(f.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Y(){return new p(f.CANCELED,"User canceled the upload/download.")}function Q(){return new p(f.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function u(e){return new p(f.INVALID_ARGUMENT,e)}function ee(){return new p(f.APP_DELETED,"The Firebase app was deleted.")}function te(e){return new p(f.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 c(e,t){return new p(f.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function d(e){throw new p(f.INTERNAL_ERROR,"Internal error: "+e)}(e=f=f||{}).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";class _{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){var e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let r;try{r=_.makeFromUrl(t,e)}catch(e){return new _(t,"")}if(""===r.path)return r;throw e=t,new p(f.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}static makeFromUrl(e,t){let r=null;var s="([A-Za-z0-9.\\-_]+)";var n=new RegExp("^gs://"+s+"(/(.*))?$","i");function i(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${s}/o(/([^?#]*).*)?$`,"i"),o=t===Z?"(?:storage.googleapis.com|storage.cloud.google.com)":t,h=[{regex:n,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:i},{regex:new RegExp(`^https?://${o}/${s}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:i}];for(let d=0;d<h.length;d++){var l=h[d],u=l.regex.exec(e);if(u){var c=u[l.indices.bucket];let e=u[l.indices.path];e=e||"",r=new _(c,e),l.postModify(r);break}}if(null==r)throw t=e,new p(f.INVALID_URL,"Invalid URL '"+t+"'.");return r}}class re{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function g(e){return"string"==typeof e||e instanceof String}function se(e){return m()&&e instanceof Blob}function m(){return"undefined"!=typeof Blob}function b(e,t,r,s){if(s<t)throw u(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r<s)throw u(`Invalid value for '${e}'. Expected ${r} or less.`)}function v(e,t,r){let s=null==r?"https://"+t:t;return`${r}://${s}/v0`+e}function ne(e){var t,r,s=encodeURIComponent;let n="?";for(t in e)e.hasOwnProperty(t)&&(r=s(t)+"="+s(e[t]),n=n+r+"&");return n=n.slice(0,-1)}function ie(e,t){var r=500<=e&&e<600,s=-1!==[408,429].indexOf(e),n=-1!==t.indexOf(e);return r||s||n}(e=i=i||{})[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT";class ae{constructor(e,t,r,s,n,i,a,o,h,l,u,c=!0,d=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=n,this.additionalRetryCodes_=i,this.callback_=a,this.errorCallback_=o,this.timeout_=h,this.progressCallback_=l,this.connectionFactory_=u,this.retry=c,this.isUsingEmulator=d,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_(){var e=(n,e)=>{if(e)n(!1,new T(!1,null,!0));else{let r=this.connectionFactory_(),s=(this.pendingConnection_=r,e=>{var t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)});null!==this.progressCallback_&&r.addUploadProgressListener(s),r.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(s),this.pendingConnection_=null;var e=r.getErrorCode()===i.NO_ERROR,t=r.getStatus();!e||ie(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===i.ABORT,n(!1,new T(!1,null,e))):(e=-1!==this.successCodes_.indexOf(t),n(!0,new T(e,r)))})}},t=(e,t)=>{var r=this.resolve_,s=this.reject_,n=t.connection;if(t.wasSuccessCode)try{var i=this.callback_(n,n.getResponse());void 0!==i?r(i):r()}catch(e){s(e)}else null!==n?((i=l()).serverResponse=n.getErrorText(),this.errorCallback_?s(this.errorCallback_(n,i)):s(i)):t.canceled?s((this.appDelete_?ee:Y)()):s(J())};this.canceled_?t(0,new T(!1,null,!0)):this.backoffId_=((t,r,e)=>{let s=1,n=null,i=null,a=!1,o=0;function h(){return 2===o}let l=!1;function u(...e){l||(l=!0,r.apply(null,e))}function c(e){n=setTimeout(()=>{n=null,t(_,h())},e)}function d(){i&&clearTimeout(i)}function _(e,...t){if(l)d();else if(e)d(),u.call(null,e,...t);else if(h()||a)d(),u.call(null,e,...t);else{s<64&&(s*=2);let e;c(e=1===o?(o=2,0):1e3*(s+Math.random()))}}let p=!1;function f(e){p||(p=!0,d(),l)||(null!==n?(e||(o=2),clearTimeout(n),c(0)):e||(o=1))}return c(0),i=setTimeout(()=>{f(a=!0)},e),f})(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class T{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function oe(...t){var r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==r){var s=new r;for(let e=0;e<t.length;e++)s.append(t[e]);return s.getBlob()}if(m())return new Blob(t);throw new p(f.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function he(e){if("undefined"==typeof atob)throw new p(f.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}let y={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class w{constructor(e,t){this.data=e,this.contentType=t||null}}function le(e,t){switch(e){case y.RAW:return new w(ue(t));case y.BASE64:case y.BASE64URL:return new w(ce(e,t));case y.DATA_URL:return new w((r=t,(s=new de(r)).base64?ce(y.BASE64,s.rest):(e=>{let t;try{t=decodeURIComponent(e)}catch(e){throw c(y.DATA_URL,"Malformed data URL.")}return ue(t)})(s.rest)),(r=t,new de(r).contentType))}var r,s;throw l()}function ue(t){var r,s,n=[];for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?i<t.length-1&&56320==(64512&t.charCodeAt(i+1))?(r=e,s=t.charCodeAt(++i),e=65536|(1023&r)<<10|1023&s,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function ce(t,e){switch(t){case y.BASE64:var r=-1!==e.indexOf("-"),s=-1!==e.indexOf("_");if(r||s)throw c(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break;case y.BASE64URL:s=-1!==e.indexOf("+"),r=-1!==e.indexOf("/");if(s||r)throw c(t,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let n;try{n=he(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw c(t,"Invalid character found")}var i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return i}class de{constructor(e){this.base64=!1,this.contentType=null;var t=e.match(/^data:([^,]+)?,/);if(null===t)throw c(y.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var r,s,t=t[1]||null;null!=t&&(this.base64=(s=";base64",(r=t).length>=s.length&&r.substring(r.length-s.length)===s),this.contentType=this.base64?t.substring(0,t.length-";base64".length):t),this.rest=e.substring(e.indexOf(",")+1)}}class E{constructor(e,t){let r=0,s="";se(e)?(this.data_=e,r=e.size,s=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_=s}size(){return this.size_}type(){return this.type_}slice(e,t){var r,s,n,i;return se(this.data_)?(r=this.data_,n=e,i=t,null===(r=(s=r).webkitSlice?s.webkitSlice(n,i):s.mozSlice?s.mozSlice(n,i):s.slice?s.slice(n,i):null)?null:new E(r)):(r=new Uint8Array(this.data_.buffer,e,t-e),new E(r,!0))}static getBlob(...e){if(m())return n=e.map(e=>e instanceof E?e.data_:e),new E(oe.apply(null,n));{var n=e.map(e=>g(e)?le(y.RAW,e).data:e.data_);let t=0,r=(n.forEach(e=>{t+=e.byteLength}),new Uint8Array(t)),s=0;return n.forEach(e=>{for(let t=0;t<e.length;t++)r[s++]=e[t]}),new E(r,!0)}}uploadData(){return this.data_}}function _e(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function pe(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function fe(e,t){return t}class r{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||fe}}let ge=null;function R(){var e,t;return ge||((e=[]).push(new r("bucket")),e.push(new r("generation")),e.push(new r("metageneration")),e.push(new r("name","fullPath",!0)),(t=new r("name")).xform=function(e,t){return!g(t=t)||t.length<2?t:pe(t)},e.push(t),(t=new r("size")).xform=function(e,t){return void 0!==t?Number(t):t},e.push(t),e.push(new r("timeCreated")),e.push(new r("updated")),e.push(new r("md5Hash",null,!0)),e.push(new r("cacheControl",null,!0)),e.push(new r("contentDisposition",null,!0)),e.push(new r("contentEncoding",null,!0)),e.push(new r("contentLanguage",null,!0)),e.push(new r("contentType",null,!0)),e.push(new r("metadata","customMetadata",!0)),ge=e),ge}function me(r,s){Object.defineProperty(r,"ref",{get:function(){var e=r.bucket,t=r.fullPath,e=new _(e,t);return s._makeStorageReference(e)}})}function be(e,t,r){var s=_e(t);if(null===s)return null;var t=e,n=s,i=r,a={type:"file"},o=i.length;for(let l=0;l<o;l++){var h=i[l];a[h.local]=h.xform(a,n[h.server])}return me(a,t),a}function ve(e,t){var r={},s=t.length;for(let i=0;i<s;i++){var n=t[i];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}let Te="prefixes",ye="items";function we(e,t,r){var s=_e(r);if(null===s)return null;var n=e,i=t,r=s,a={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[Te])for(var o of r[Te]){o=o.replace(/\/$/,""),o=n._makeStorageReference(new _(i,o));a.prefixes.push(o)}if(r[ye])for(var h of r[ye]){h=n._makeStorageReference(new _(i,h.name));a.items.push(h)}return a}class C{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function k(e){if(!e)throw l()}function A(s,n){return function(e,t){var r=be(s,t,n);return k(null!==r),r}}function Ee(s,n){return function(e,t){var r=we(s,n,t);return k(null!==r),r}}function Re(o,s){return function(e,t){var r=be(o,t,s);k(null!==r);{var n=r,i=o.host,a=o._protocol;if(null===(r=_e(t)))return null;if(!g(r.downloadTokens))return null;if(0===(r=r.downloadTokens).length)return null;let s=encodeURIComponent;return r.split(",").map(e=>{var t=n.bucket,r=n.fullPath;return v("/b/"+s(t)+"/o/"+s(r),i,a)+ne({alt:"media",token:e})})[0]}}}function S(n){return function(e,t){let r;var s;return(r=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new p(f.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new p(f.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(s=n.bucket,new p(f.QUOTA_EXCEEDED,"Quota for bucket '"+s+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(s=n.path,new p(f.UNAUTHORIZED,"User does not have permission to access '"+s+"'.")):t).status=e.getStatus(),r.serverResponse=t.serverResponse,r}}function U(s){let n=S(s);return function(e,t){let r=n(e,t);return(r=404===e.getStatus()?(e=s.path,new p(f.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")):r).serverResponse=t.serverResponse,r}}function Ce(e,t,r){var s=v(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime,s=new C(s,"GET",A(e,r),n);return s.errorHandler=U(t),s}function ke(e,t,r){var s=Object.assign({},r);return s.fullPath=e.path,s.size=t.size(),s.contentType||(s.contentType=(r=t,(e=null)&&e.contentType||r&&r.type()||"application/octet-stream")),s}function Ae(e,t,r,s,n){var i=t.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};var o=(()=>{let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e})(),h=(a["Content-Type"]="multipart/related; boundary="+o,ke(t,s,n)),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+ve(h,r)+"\r\n--"+o+"\r\nContent-Type: "+h.contentType+"\r\n\r\n",o="\r\n--"+o+"--",l=E.getBlob(l,s,o);if(null===l)throw Q();o={name:h.fullPath},h=v(i,e.host,e._protocol),i=e.maxUploadRetryTime,h=new C(h,"POST",A(e,r),i);return h.urlParams=o,h.headers=a,h.body=l.uploadData(),h.errorHandler=S(t),h}class O{constructor(e,t,r,s){this.current=e,this.total=t,this.finalized=!!r,this.metadata=s||null}}function Se(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){k(!1)}return k(!!r&&-1!==(t||["active"]).indexOf(r)),r}function Ue(e,t,r,s,n){var i=t.bucketOnlyServerUrl(),a=ke(t,s,n),o={name:a.fullPath},i=v(i,e.host,e._protocol),h={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":""+s.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},a=ve(a,r),l=e.maxUploadRetryTime;i=new C(i,"POST",function(e){Se(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){k(!1)}return k(g(t)),t},l);return i.urlParams=o,i.headers=h,i.body=a,i.errorHandler=S(t),i}function Oe(e,t,r,n){var s=e.maxUploadRetryTime,s=new C(r,"POST",function(e){var t=Se(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){k(!1)}r||k(!1);var s=Number(r);return k(!isNaN(s)),new O(s,n.size(),"final"===t)},s);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=S(t),s}function xe(e,a,t,o,r,h,s,n){let l=new O(0,0);if(s?(l.current=s.current,l.total=s.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new p(f.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var i=l.total-l.current;let u=i;0<r&&(u=Math.min(u,r));var c=l.current,d=c+u;let _="";i={"X-Goog-Upload-Command":_=0===u?"finalize":i===u?"upload, finalize":"upload","X-Goog-Upload-Offset":""+l.current},c=o.slice(c,d);if(null===c)throw Q();d=a.maxUploadRetryTime,d=new C(t,"POST",function(e,t){var r=Se(e,["active","final"]),s=l.current+u,n=o.size();let i;return i="final"===r?A(a,h)(e,t):null,new O(s,n,"final"===r,i)},d);return d.headers=i,d.body=c.uploadData(),d.progressCallback=n||null,d.errorHandler=S(e),d}let Ne={STATE_CHANGED:"state_changed"},t={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Ie(e){switch(e){case"running":case"pausing":case"canceling":return t.RUNNING;case"paused":return t.PAUSED;case"success":return t.SUCCESS;case"canceled":return t.CANCELED;default:return t.ERROR}}class Pe{constructor(e,t,r){var s;"function"==typeof e||null!=t||null!=r?(this.next=e,this.error=t??void 0,this.complete=r??void 0):(this.next=(s=e).next,this.error=s.error,this.complete=s.complete)}}function x(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class De extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=i.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=i.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=i.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,s,n){if(this.sent_)throw d("cannot .send() more than once");if(a(e)&&r&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(var i in n)n.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,n[i].toString());return void 0!==s?this.xhr_.send(s):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(this.sent_)return this.errorCode_;throw d("cannot .getErrorCode() before sending")}getStatus(){if(!this.sent_)throw d("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(this.sent_)return this.xhr_.response;throw d("cannot .getResponse() before sending")}getErrorText(){if(this.sent_)return this.xhr_.statusText;throw d("cannot .getErrorText() before sending")}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)}}{initXhr(){this.xhr_.responseType="text"}}function N(){return new De}class Le{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}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=R(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(f.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(ie(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=J()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(f.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,()=>{})}_makeProgressCallback(){let t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_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(r){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":r(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var r=Ue(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let s=this._uploadUrl;this._resolveToken((e,t)=>{var r=Oe(this._ref.storage,this._ref._location,s,this._blob),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let n=262144*this._chunkMultiplier,i=new O(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let r;try{r=xe(this._ref._location,this._ref.storage,a,this._blob,n,this._mappings,i,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}var s=this._ref.storage._makeRequest(r,N,e,t,!1);(this._request=s).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)=>{var r=Ce(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var r=Ae(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var 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":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Y(),this._state=e,this._notifyObservers();break;case"error":case"success":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(){var e=Ie(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,s){let n=new Pe(t||void 0,r||void 0,s||void 0);return this._addObserver(n),()=>{this._removeObserver(n)}}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){var 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(Ie(this._state)){case t.SUCCESS:x(this._resolve.bind(null,this.snapshot))();break;case t.CANCELED:case t.ERROR:x(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Ie(this._state)){case t.RUNNING:case t.PAUSED:e.next&&x(e.next.bind(e,this.snapshot))();break;case t.SUCCESS:e.complete&&x(e.complete.bind(e))();break;case t.CANCELED:case t.ERROR:default:e.error&&x(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class I{constructor(e,t){this._service=e,t instanceof _?this._location=t:this._location=_.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new I(e,t)}get root(){var e=new _(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return pe(this._location.path)}get storage(){return this._service}get parent(){var e,t,r=0===(e=this._location.path).length?null:-1===(r=e.lastIndexOf("/"))?"":e.slice(0,r);return null===r?null:(t=new _(this._location.bucket,r),new I(this._service,t))}_throwIfRoot(e){if(""===this._location.path)throw te(e)}}function Me(e){let t={prefixes:[],items:[]};return async function e(t,r,s){let n={pageToken:s};let i=await Be(t,n);r.prefixes.push(...i.prefixes);r.items.push(...i.items);null!=i.nextPageToken&&await e(t,r,i.nextPageToken)}(e,t).then(()=>t)}function Be(e,t){null!=t&&"number"==typeof t.maxResults&&b("options.maxResults",1,1e3,t.maxResults);var r,s,n,i,a,o=t||{},h=(t=e.storage,r=e._location,s="/",n=o.pageToken,i=o.maxResults,o={},r.isRoot?o.prefix="":o.prefix=r.path+"/",s&&0<s.length&&(o.delimiter=s),n&&(o.pageToken=n),i&&(o.maxResults=i),a=v(a=r.bucketOnlyServerUrl(),t.host,t._protocol),h=t.maxOperationRetryTime,(a=new C(a,"GET",Ee(t,r.bucket),h)).urlParams=o,a.errorHandler=S(r),a);return e.storage.makeRequestWithTokens(h,N)}function Fe(e,t){e._throwIfRoot("updateMetadata");r=e.storage,s=e._location,t=t,n=R(),i=v(s.fullServerUrl(),r.host,r._protocol),a=ve(t,n),o=r.maxOperationRetryTime,(i=new C(i,"PATCH",A(r,n),o)).headers={"Content-Type":"application/json; charset=utf-8"},i.body=a,i.errorHandler=U(s);var r,s,n,i,a,o=i;return e.storage.makeRequestWithTokens(o,N)}function He(e){e._throwIfRoot("getDownloadURL");t=e.storage,r=e._location,s=R(),n=v(r.fullServerUrl(),t.host,t._protocol),i=t.maxOperationRetryTime,(n=new C(n,"GET",Re(t,s),i)).errorHandler=U(r);var t,r,s,n,i=n;return e.storage.makeRequestWithTokens(i,N).then(e=>{if(null===e)throw new p(f.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function qe(e){e._throwIfRoot("deleteObject");t=e.storage,s=v((r=e._location).fullServerUrl(),t.host,t._protocol),n=t.maxOperationRetryTime,(s=new C(s,"DELETE",function(e,t){},n)).successCodes=[200,204],s.errorHandler=U(r);var t,r,s,n=s;return e.storage.makeRequestWithTokens(n,N)}function Ve(e,t){r=e._location.path,s=t.split("/").filter(e=>0<e.length).join("/");var r,s=0===r.length?s:r+"/"+s,s=new _(e._location.bucket,s);return new I(e.storage,s)}function We(e,t){if(e instanceof Xe){var r=e;if(null==r._bucket)throw new p(f.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+$+"' property when initializing the app?");r=new I(r,r._bucket);return null!=t?We(r,t):r}return void 0!==t?Ve(e,t):e}function ze(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof Xe)return r=e,s=t,new I(r,s);throw u("To use ref(service, url), the first argument must be a Storage instance.")}return We(e,t);var r,s}function je(e,t){var r=t?.[$];return null==r?null:_.makeFromBucketSpec(r,e)}function Ge(e,t,r,s={}){e.host=t+":"+r;var n=a(t),n=(n&&((async e=>(await fetch(e,{credentials:"include"})).ok)(`https://${e.host}/b`),z("Storage",!0)),e._isUsingEmulator=!0,e._protocol=n?"https":"http",s).mockUserToken;n&&(e._overrideAuthToken="string"==typeof n?n:((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.');var r=t||"demo-project",s=e.iat||0,n=e.sub||e.user_id;if(n)return r={iss:"https://securetoken.google.com/"+r,aud:r,iat:s,exp:s+3600,auth_time:s,sub:n,user_id:n,firebase:{sign_in_provider:"custom",identities:{}},...e},[V(JSON.stringify({alg:"none",type:"JWT"})),V(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")})(n,e.app.options.projectId))}class Xe{constructor(e,t,r,s,n,i=!1){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=s,this._firebaseVersion=n,this._isUsingEmulator=i,this._bucket=null,this._host=Z,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=s?_.makeFromBucketSpec(s,this._host):je(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=_.makeFromBucketSpec(this._url,e):this._bucket=je(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){b("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){b("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;var e=this._authProvider.getImmediate({optional:!0});if(e){e=await e.getToken();if(null!==e)return e.accessToken}return null}async _getAppCheckToken(){var e;return at._isFirebaseServerApp(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:(e=this._appCheckProvider.getImmediate({optional:!0}))?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new I(this,e)}_makeRequest(t,r,s,n,i=!0){if(this._deleted)return new re(ee());{[t,s,n,r,i,a,o=!0,h=!1]=[t,this._appId,s,n,r,this._firebaseVersion,i,this._isUsingEmulator],u=ne(t.urlParams),u=t.url+u,c=Object.assign({},t.headers),l=c,(s=s)&&(l["X-Firebase-GMPID"]=s),l=c,null!==(s=n)&&0<s.length&&(l.Authorization="Firebase "+s),c["X-Firebase-Storage-Version"]="webjs/"+(a??"AppManager"),n=c,null!==(l=r)&&(n["X-Firebase-AppCheck"]=l);let e=new ae(u,t.method,c,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,i,o,h);return this._requests.add(e),e.getPromise().then(()=>this._requests.delete(e),()=>this._requests.delete(e)),e}var a,o,h,l,u,c}async makeRequestWithTokens(e,t){var[r,s]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,s).getPromise()}}let Ze="@firebase/storage",$e="0.14.0-canary.9101b4611";function Ke(e,t,r){return e=n(e),t=t,r=r,(e=e)._throwIfRoot("uploadBytesResumable"),new Le(e,new E(t),r)}function Je(e){return e=n(e),(e=e)._throwIfRoot("getMetadata"),t=Ce(e.storage,e._location,R()),e.storage.makeRequestWithTokens(t,N);var t}function Ye(e,t){return ze(e=n(e),t)}function Qe(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),n=e.getProvider("app-check-internal");return new Xe(r,s,n,t,at.SDK_VERSION)}at._registerComponent(new X("storage",Qe,"PUBLIC").setMultipleInstances(!0)),at.registerVersion(Ze,$e,""),at.registerVersion(Ze,$e,"esm2020");class P{constructor(e,t,r){this._delegate=e,this.task=t,this.ref=r}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class et{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new P(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new P(e,this,this._ref))},e)}on(e,t,r,s){let n=void 0;return t&&(n="function"==typeof t?e=>t(new P(e,this,this._ref)):{next:t.next?e=>t.next(new P(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,n,r||void 0,s||void 0)}}class tt{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new D(e,this._service))}get items(){return this._delegate.items.map(e=>new D(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class D{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=Ve(this._delegate,e);return new D(t,this.storage)}get root(){return new D(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new D(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new et(Ke(this._delegate,e,t),this)}putString(e,t=y.RAW,r){this._throwIfRoot("putString");var s=le(t,e),n={...r};return null==n.contentType&&null!=s.contentType&&(n.contentType=s.contentType),new et(new Le(this._delegate,new E(s.data,!0),n),this)}listAll(){return Me(n(this._delegate)).then(e=>new tt(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,Be(t=n(t),e).then(e=>new tt(e,this.storage));var t}getMetadata(){return Je(this._delegate)}updateMetadata(e){return Fe(n(this._delegate),e)}getDownloadURL(){return He(n(this._delegate))}delete(){return this._throwIfRoot("delete"),qe(n(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw te(e)}}class rt{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(st(e))throw u("ref() expected a child path but got a URL, use refFromURL instead.");return new D(Ye(this._delegate,e),this)}refFromURL(e){if(!st(e))throw u("refFromURL() expected a full URL but got a child path, use ref() instead.");try{_.makeFromUrl(e,this._delegate.host)}catch(e){throw u("refFromUrl() expected a valid full URL but got an invalid one.")}return new D(Ye(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,r={}){var s;[e,t,r,s={}]=[this._delegate,e,t,r],Ge(e,t,r,s)}}function st(e){return/^[A-Za-z]+:\/\//.test(e)}function nt(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("storage").getImmediate({identifier:t});return new rt(r,s)}e=M.default,K={TaskState:t,TaskEvent:Ne,StringFormat:y,Storage:rt,Reference:D},e.INTERNAL.registerComponent(new X("storage-compat",nt,"PUBLIC").setServiceProps(K).setMultipleInstances(!0)),e.registerVersion("@firebase/storage-compat","0.4.0-canary.9101b4611")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-storage-compat.js - be sure to load firebase-app.js first.")}});
|
|
16
|
+
`+this.customData.serverResponse:this.message=this._baseMessage}}var f,i,e,K;function h(e){return"storage/"+e}function l(){return new p(f.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function J(){return new p(f.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Y(){return new p(f.CANCELED,"User canceled the upload/download.")}function Q(){return new p(f.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function u(e){return new p(f.INVALID_ARGUMENT,e)}function ee(){return new p(f.APP_DELETED,"The Firebase app was deleted.")}function te(e){return new p(f.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 c(e,t){return new p(f.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function d(e){throw new p(f.INTERNAL_ERROR,"Internal error: "+e)}(e=f=f||{}).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";class _{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){var e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let r;try{r=_.makeFromUrl(t,e)}catch(e){return new _(t,"")}if(""===r.path)return r;throw e=t,new p(f.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}static makeFromUrl(e,t){let r=null;var s="([A-Za-z0-9.\\-_]+)";var n=new RegExp("^gs://"+s+"(/(.*))?$","i");function i(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${s}/o(/([^?#]*).*)?$`,"i"),o=t===Z?"(?:storage.googleapis.com|storage.cloud.google.com)":t,h=[{regex:n,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:i},{regex:new RegExp(`^https?://${o}/${s}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:i}];for(let d=0;d<h.length;d++){var l=h[d],u=l.regex.exec(e);if(u){var c=u[l.indices.bucket];let e=u[l.indices.path];e=e||"",r=new _(c,e),l.postModify(r);break}}if(null==r)throw t=e,new p(f.INVALID_URL,"Invalid URL '"+t+"'.");return r}}class re{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function g(e){return"string"==typeof e||e instanceof String}function se(e){return m()&&e instanceof Blob}function m(){return"undefined"!=typeof Blob}function b(e,t,r,s){if(s<t)throw u(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r<s)throw u(`Invalid value for '${e}'. Expected ${r} or less.`)}function v(e,t,r){let s=null==r?"https://"+t:t;return`${r}://${s}/v0`+e}function ne(e){var t,r,s=encodeURIComponent;let n="?";for(t in e)e.hasOwnProperty(t)&&(r=s(t)+"="+s(e[t]),n=n+r+"&");return n=n.slice(0,-1)}function ie(e,t){var r=500<=e&&e<600,s=-1!==[408,429].indexOf(e),n=-1!==t.indexOf(e);return r||s||n}(e=i=i||{})[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT";class ae{constructor(e,t,r,s,n,i,a,o,h,l,u,c=!0,d=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=n,this.additionalRetryCodes_=i,this.callback_=a,this.errorCallback_=o,this.timeout_=h,this.progressCallback_=l,this.connectionFactory_=u,this.retry=c,this.isUsingEmulator=d,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_(){var e=(n,e)=>{if(e)n(!1,new T(!1,null,!0));else{let r=this.connectionFactory_(),s=(this.pendingConnection_=r,e=>{var t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)});null!==this.progressCallback_&&r.addUploadProgressListener(s),r.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(s),this.pendingConnection_=null;var e=r.getErrorCode()===i.NO_ERROR,t=r.getStatus();!e||ie(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===i.ABORT,n(!1,new T(!1,null,e))):(e=-1!==this.successCodes_.indexOf(t),n(!0,new T(e,r)))})}},t=(e,t)=>{var r=this.resolve_,s=this.reject_,n=t.connection;if(t.wasSuccessCode)try{var i=this.callback_(n,n.getResponse());void 0!==i?r(i):r()}catch(e){s(e)}else null!==n?((i=l()).serverResponse=n.getErrorText(),this.errorCallback_?s(this.errorCallback_(n,i)):s(i)):t.canceled?s((this.appDelete_?ee:Y)()):s(J())};this.canceled_?t(0,new T(!1,null,!0)):this.backoffId_=((t,r,e)=>{let s=1,n=null,i=null,a=!1,o=0;function h(){return 2===o}let l=!1;function u(...e){l||(l=!0,r.apply(null,e))}function c(e){n=setTimeout(()=>{n=null,t(_,h())},e)}function d(){i&&clearTimeout(i)}function _(e,...t){if(l)d();else if(e)d(),u.call(null,e,...t);else if(h()||a)d(),u.call(null,e,...t);else{s<64&&(s*=2);let e;c(e=1===o?(o=2,0):1e3*(s+Math.random()))}}let p=!1;function f(e){p||(p=!0,d(),l)||(null!==n?(e||(o=2),clearTimeout(n),c(0)):e||(o=1))}return c(0),i=setTimeout(()=>{f(a=!0)},e),f})(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class T{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function oe(...t){var r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==r){var s=new r;for(let e=0;e<t.length;e++)s.append(t[e]);return s.getBlob()}if(m())return new Blob(t);throw new p(f.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function he(e){if("undefined"==typeof atob)throw new p(f.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}let y={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class w{constructor(e,t){this.data=e,this.contentType=t||null}}function le(e,t){switch(e){case y.RAW:return new w(ue(t));case y.BASE64:case y.BASE64URL:return new w(ce(e,t));case y.DATA_URL:return new w((r=t,(s=new de(r)).base64?ce(y.BASE64,s.rest):(e=>{let t;try{t=decodeURIComponent(e)}catch(e){throw c(y.DATA_URL,"Malformed data URL.")}return ue(t)})(s.rest)),(r=t,new de(r).contentType))}var r,s;throw l()}function ue(t){var r,s,n=[];for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?i<t.length-1&&56320==(64512&t.charCodeAt(i+1))?(r=e,s=t.charCodeAt(++i),e=65536|(1023&r)<<10|1023&s,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function ce(t,e){switch(t){case y.BASE64:var r=-1!==e.indexOf("-"),s=-1!==e.indexOf("_");if(r||s)throw c(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break;case y.BASE64URL:s=-1!==e.indexOf("+"),r=-1!==e.indexOf("/");if(s||r)throw c(t,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let n;try{n=he(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw c(t,"Invalid character found")}var i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return i}class de{constructor(e){this.base64=!1,this.contentType=null;var t=e.match(/^data:([^,]+)?,/);if(null===t)throw c(y.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var r,s,t=t[1]||null;null!=t&&(this.base64=(s=";base64",(r=t).length>=s.length&&r.substring(r.length-s.length)===s),this.contentType=this.base64?t.substring(0,t.length-";base64".length):t),this.rest=e.substring(e.indexOf(",")+1)}}class E{constructor(e,t){let r=0,s="";se(e)?(this.data_=e,r=e.size,s=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_=s}size(){return this.size_}type(){return this.type_}slice(e,t){var r,s,n,i;return se(this.data_)?(r=this.data_,n=e,i=t,null===(r=(s=r).webkitSlice?s.webkitSlice(n,i):s.mozSlice?s.mozSlice(n,i):s.slice?s.slice(n,i):null)?null:new E(r)):(r=new Uint8Array(this.data_.buffer,e,t-e),new E(r,!0))}static getBlob(...e){if(m())return n=e.map(e=>e instanceof E?e.data_:e),new E(oe.apply(null,n));{var n=e.map(e=>g(e)?le(y.RAW,e).data:e.data_);let t=0,r=(n.forEach(e=>{t+=e.byteLength}),new Uint8Array(t)),s=0;return n.forEach(e=>{for(let t=0;t<e.length;t++)r[s++]=e[t]}),new E(r,!0)}}uploadData(){return this.data_}}function _e(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function pe(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function fe(e,t){return t}class r{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||fe}}let ge=null;function R(){var e,t;return ge||((e=[]).push(new r("bucket")),e.push(new r("generation")),e.push(new r("metageneration")),e.push(new r("name","fullPath",!0)),(t=new r("name")).xform=function(e,t){return!g(t=t)||t.length<2?t:pe(t)},e.push(t),(t=new r("size")).xform=function(e,t){return void 0!==t?Number(t):t},e.push(t),e.push(new r("timeCreated")),e.push(new r("updated")),e.push(new r("md5Hash",null,!0)),e.push(new r("cacheControl",null,!0)),e.push(new r("contentDisposition",null,!0)),e.push(new r("contentEncoding",null,!0)),e.push(new r("contentLanguage",null,!0)),e.push(new r("contentType",null,!0)),e.push(new r("metadata","customMetadata",!0)),ge=e),ge}function me(r,s){Object.defineProperty(r,"ref",{get:function(){var e=r.bucket,t=r.fullPath,e=new _(e,t);return s._makeStorageReference(e)}})}function be(e,t,r){var s=_e(t);if(null===s)return null;var t=e,n=s,i=r,a={type:"file"},o=i.length;for(let l=0;l<o;l++){var h=i[l];a[h.local]=h.xform(a,n[h.server])}return me(a,t),a}function ve(e,t){var r={},s=t.length;for(let i=0;i<s;i++){var n=t[i];n.writable&&(r[n.server]=e[n.local])}return JSON.stringify(r)}let Te="prefixes",ye="items";function we(e,t,r){var s=_e(r);if(null===s)return null;var n=e,i=t,r=s,a={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[Te])for(var o of r[Te]){o=o.replace(/\/$/,""),o=n._makeStorageReference(new _(i,o));a.prefixes.push(o)}if(r[ye])for(var h of r[ye]){h=n._makeStorageReference(new _(i,h.name));a.items.push(h)}return a}class C{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function k(e){if(!e)throw l()}function A(s,n){return function(e,t){var r=be(s,t,n);return k(null!==r),r}}function Ee(s,n){return function(e,t){var r=we(s,n,t);return k(null!==r),r}}function Re(o,s){return function(e,t){var r=be(o,t,s);k(null!==r);{var n=r,i=o.host,a=o._protocol;if(null===(r=_e(t)))return null;if(!g(r.downloadTokens))return null;if(0===(r=r.downloadTokens).length)return null;let s=encodeURIComponent;return r.split(",").map(e=>{var t=n.bucket,r=n.fullPath;return v("/b/"+s(t)+"/o/"+s(r),i,a)+ne({alt:"media",token:e})})[0]}}}function S(n){return function(e,t){let r;var s;return(r=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new p(f.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new p(f.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(s=n.bucket,new p(f.QUOTA_EXCEEDED,"Quota for bucket '"+s+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(s=n.path,new p(f.UNAUTHORIZED,"User does not have permission to access '"+s+"'.")):t).status=e.getStatus(),r.serverResponse=t.serverResponse,r}}function U(s){let n=S(s);return function(e,t){let r=n(e,t);return(r=404===e.getStatus()?(e=s.path,new p(f.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")):r).serverResponse=t.serverResponse,r}}function Ce(e,t,r){var s=v(t.fullServerUrl(),e.host,e._protocol),n=e.maxOperationRetryTime,s=new C(s,"GET",A(e,r),n);return s.errorHandler=U(t),s}function ke(e,t,r){var s=Object.assign({},r);return s.fullPath=e.path,s.size=t.size(),s.contentType||(s.contentType=(r=t,(e=null)&&e.contentType||r&&r.type()||"application/octet-stream")),s}function Ae(e,t,r,s,n){var i=t.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};var o=(()=>{let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e})(),h=(a["Content-Type"]="multipart/related; boundary="+o,ke(t,s,n)),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+ve(h,r)+"\r\n--"+o+"\r\nContent-Type: "+h.contentType+"\r\n\r\n",o="\r\n--"+o+"--",l=E.getBlob(l,s,o);if(null===l)throw Q();o={name:h.fullPath},h=v(i,e.host,e._protocol),i=e.maxUploadRetryTime,h=new C(h,"POST",A(e,r),i);return h.urlParams=o,h.headers=a,h.body=l.uploadData(),h.errorHandler=S(t),h}class O{constructor(e,t,r,s){this.current=e,this.total=t,this.finalized=!!r,this.metadata=s||null}}function Se(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){k(!1)}return k(!!r&&-1!==(t||["active"]).indexOf(r)),r}function Ue(e,t,r,s,n){var i=t.bucketOnlyServerUrl(),a=ke(t,s,n),o={name:a.fullPath},i=v(i,e.host,e._protocol),h={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":""+s.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},a=ve(a,r),l=e.maxUploadRetryTime;i=new C(i,"POST",function(e){Se(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){k(!1)}return k(g(t)),t},l);return i.urlParams=o,i.headers=h,i.body=a,i.errorHandler=S(t),i}function Oe(e,t,r,n){var s=e.maxUploadRetryTime,s=new C(r,"POST",function(e){var t=Se(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){k(!1)}r||k(!1);var s=Number(r);return k(!isNaN(s)),new O(s,n.size(),"final"===t)},s);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=S(t),s}function xe(e,a,t,o,r,h,s,n){let l=new O(0,0);if(s?(l.current=s.current,l.total=s.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new p(f.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var i=l.total-l.current;let u=i;0<r&&(u=Math.min(u,r));var c=l.current,d=c+u;let _="";i={"X-Goog-Upload-Command":_=0===u?"finalize":i===u?"upload, finalize":"upload","X-Goog-Upload-Offset":""+l.current},c=o.slice(c,d);if(null===c)throw Q();d=a.maxUploadRetryTime,d=new C(t,"POST",function(e,t){var r=Se(e,["active","final"]),s=l.current+u,n=o.size();let i;return i="final"===r?A(a,h)(e,t):null,new O(s,n,"final"===r,i)},d);return d.headers=i,d.body=c.uploadData(),d.progressCallback=n||null,d.errorHandler=S(e),d}let Ne={STATE_CHANGED:"state_changed"},t={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Ie(e){switch(e){case"running":case"pausing":case"canceling":return t.RUNNING;case"paused":return t.PAUSED;case"success":return t.SUCCESS;case"canceled":return t.CANCELED;default:return t.ERROR}}class Pe{constructor(e,t,r){var s;"function"==typeof e||null!=t||null!=r?(this.next=e,this.error=t??void 0,this.complete=r??void 0):(this.next=(s=e).next,this.error=s.error,this.complete=s.complete)}}function x(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class De extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=i.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=i.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=i.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,s,n){if(this.sent_)throw d("cannot .send() more than once");if(a(e)&&r&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(var i in n)n.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,n[i].toString());return void 0!==s?this.xhr_.send(s):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(this.sent_)return this.errorCode_;throw d("cannot .getErrorCode() before sending")}getStatus(){if(!this.sent_)throw d("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(this.sent_)return this.xhr_.response;throw d("cannot .getResponse() before sending")}getErrorText(){if(this.sent_)return this.xhr_.statusText;throw d("cannot .getErrorText() before sending")}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)}}{initXhr(){this.xhr_.responseType="text"}}function N(){return new De}class Le{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}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=R(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(f.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(ie(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=J()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(f.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,()=>{})}_makeProgressCallback(){let t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_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(r){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":r(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var r=Ue(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let s=this._uploadUrl;this._resolveToken((e,t)=>{var r=Oe(this._ref.storage,this._ref._location,s,this._blob),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let n=262144*this._chunkMultiplier,i=new O(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let r;try{r=xe(this._ref._location,this._ref.storage,a,this._blob,n,this._mappings,i,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}var s=this._ref.storage._makeRequest(r,N,e,t,!1);(this._request=s).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)=>{var r=Ce(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var r=Ae(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,N,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var 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":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Y(),this._state=e,this._notifyObservers();break;case"error":case"success":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(){var e=Ie(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,s){let n=new Pe(t||void 0,r||void 0,s||void 0);return this._addObserver(n),()=>{this._removeObserver(n)}}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){var 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(Ie(this._state)){case t.SUCCESS:x(this._resolve.bind(null,this.snapshot))();break;case t.CANCELED:case t.ERROR:x(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Ie(this._state)){case t.RUNNING:case t.PAUSED:e.next&&x(e.next.bind(e,this.snapshot))();break;case t.SUCCESS:e.complete&&x(e.complete.bind(e))();break;case t.CANCELED:case t.ERROR:default:e.error&&x(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class I{constructor(e,t){this._service=e,t instanceof _?this._location=t:this._location=_.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new I(e,t)}get root(){var e=new _(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return pe(this._location.path)}get storage(){return this._service}get parent(){var e,t,r=0===(e=this._location.path).length?null:-1===(r=e.lastIndexOf("/"))?"":e.slice(0,r);return null===r?null:(t=new _(this._location.bucket,r),new I(this._service,t))}_throwIfRoot(e){if(""===this._location.path)throw te(e)}}function Me(e){let t={prefixes:[],items:[]};return async function e(t,r,s){let n={pageToken:s};let i=await Be(t,n);r.prefixes.push(...i.prefixes);r.items.push(...i.items);null!=i.nextPageToken&&await e(t,r,i.nextPageToken)}(e,t).then(()=>t)}function Be(e,t){null!=t&&"number"==typeof t.maxResults&&b("options.maxResults",1,1e3,t.maxResults);var r,s,n,i,a,o=t||{},h=(t=e.storage,r=e._location,s="/",n=o.pageToken,i=o.maxResults,o={},r.isRoot?o.prefix="":o.prefix=r.path+"/",s&&0<s.length&&(o.delimiter=s),n&&(o.pageToken=n),i&&(o.maxResults=i),a=v(a=r.bucketOnlyServerUrl(),t.host,t._protocol),h=t.maxOperationRetryTime,(a=new C(a,"GET",Ee(t,r.bucket),h)).urlParams=o,a.errorHandler=S(r),a);return e.storage.makeRequestWithTokens(h,N)}function Fe(e,t){e._throwIfRoot("updateMetadata");r=e.storage,s=e._location,t=t,n=R(),i=v(s.fullServerUrl(),r.host,r._protocol),a=ve(t,n),o=r.maxOperationRetryTime,(i=new C(i,"PATCH",A(r,n),o)).headers={"Content-Type":"application/json; charset=utf-8"},i.body=a,i.errorHandler=U(s);var r,s,n,i,a,o=i;return e.storage.makeRequestWithTokens(o,N)}function He(e){e._throwIfRoot("getDownloadURL");t=e.storage,r=e._location,s=R(),n=v(r.fullServerUrl(),t.host,t._protocol),i=t.maxOperationRetryTime,(n=new C(n,"GET",Re(t,s),i)).errorHandler=U(r);var t,r,s,n,i=n;return e.storage.makeRequestWithTokens(i,N).then(e=>{if(null===e)throw new p(f.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function qe(e){e._throwIfRoot("deleteObject");t=e.storage,s=v((r=e._location).fullServerUrl(),t.host,t._protocol),n=t.maxOperationRetryTime,(s=new C(s,"DELETE",function(e,t){},n)).successCodes=[200,204],s.errorHandler=U(r);var t,r,s,n=s;return e.storage.makeRequestWithTokens(n,N)}function Ve(e,t){r=e._location.path,s=t.split("/").filter(e=>0<e.length).join("/");var r,s=0===r.length?s:r+"/"+s,s=new _(e._location.bucket,s);return new I(e.storage,s)}function We(e,t){if(e instanceof Xe){var r=e;if(null==r._bucket)throw new p(f.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+$+"' property when initializing the app?");r=new I(r,r._bucket);return null!=t?We(r,t):r}return void 0!==t?Ve(e,t):e}function ze(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof Xe)return r=e,s=t,new I(r,s);throw u("To use ref(service, url), the first argument must be a Storage instance.")}return We(e,t);var r,s}function je(e,t){var r=t?.[$];return null==r?null:_.makeFromBucketSpec(r,e)}function Ge(e,t,r,s={}){e.host=t+":"+r;var n=a(t),n=(n&&((async e=>(await fetch(e,{credentials:"include"})).ok)(`https://${e.host}/b`),z("Storage",!0)),e._isUsingEmulator=!0,e._protocol=n?"https":"http",s).mockUserToken;n&&(e._overrideAuthToken="string"==typeof n?n:((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.');var r=t||"demo-project",s=e.iat||0,n=e.sub||e.user_id;if(n)return r={iss:"https://securetoken.google.com/"+r,aud:r,iat:s,exp:s+3600,auth_time:s,sub:n,user_id:n,firebase:{sign_in_provider:"custom",identities:{}},...e},[V(JSON.stringify({alg:"none",type:"JWT"})),V(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")})(n,e.app.options.projectId))}class Xe{constructor(e,t,r,s,n,i=!1){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=s,this._firebaseVersion=n,this._isUsingEmulator=i,this._bucket=null,this._host=Z,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=s?_.makeFromBucketSpec(s,this._host):je(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=_.makeFromBucketSpec(this._url,e):this._bucket=je(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){b("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){b("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;var e=this._authProvider.getImmediate({optional:!0});if(e){e=await e.getToken();if(null!==e)return e.accessToken}return null}async _getAppCheckToken(){var e;return at._isFirebaseServerApp(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:(e=this._appCheckProvider.getImmediate({optional:!0}))?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new I(this,e)}_makeRequest(t,r,s,n,i=!0){if(this._deleted)return new re(ee());{[t,s,n,r,i,a,o=!0,h=!1]=[t,this._appId,s,n,r,this._firebaseVersion,i,this._isUsingEmulator],u=ne(t.urlParams),u=t.url+u,c=Object.assign({},t.headers),l=c,(s=s)&&(l["X-Firebase-GMPID"]=s),l=c,null!==(s=n)&&0<s.length&&(l.Authorization="Firebase "+s),c["X-Firebase-Storage-Version"]="webjs/"+(a??"AppManager"),n=c,null!==(l=r)&&(n["X-Firebase-AppCheck"]=l);let e=new ae(u,t.method,c,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,i,o,h);return this._requests.add(e),e.getPromise().then(()=>this._requests.delete(e),()=>this._requests.delete(e)),e}var a,o,h,l,u,c}async makeRequestWithTokens(e,t){var[r,s]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,s).getPromise()}}let Ze="@firebase/storage",$e="0.14.0-canary.a09ef786f";function Ke(e,t,r){return e=n(e),t=t,r=r,(e=e)._throwIfRoot("uploadBytesResumable"),new Le(e,new E(t),r)}function Je(e){return e=n(e),(e=e)._throwIfRoot("getMetadata"),t=Ce(e.storage,e._location,R()),e.storage.makeRequestWithTokens(t,N);var t}function Ye(e,t){return ze(e=n(e),t)}function Qe(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),n=e.getProvider("app-check-internal");return new Xe(r,s,n,t,at.SDK_VERSION)}at._registerComponent(new X("storage",Qe,"PUBLIC").setMultipleInstances(!0)),at.registerVersion(Ze,$e,""),at.registerVersion(Ze,$e,"esm2020");class P{constructor(e,t,r){this._delegate=e,this.task=t,this.ref=r}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class et{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new P(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new P(e,this,this._ref))},e)}on(e,t,r,s){let n=void 0;return t&&(n="function"==typeof t?e=>t(new P(e,this,this._ref)):{next:t.next?e=>t.next(new P(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,n,r||void 0,s||void 0)}}class tt{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new D(e,this._service))}get items(){return this._delegate.items.map(e=>new D(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class D{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=Ve(this._delegate,e);return new D(t,this.storage)}get root(){return new D(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new D(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new et(Ke(this._delegate,e,t),this)}putString(e,t=y.RAW,r){this._throwIfRoot("putString");var s=le(t,e),n={...r};return null==n.contentType&&null!=s.contentType&&(n.contentType=s.contentType),new et(new Le(this._delegate,new E(s.data,!0),n),this)}listAll(){return Me(n(this._delegate)).then(e=>new tt(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,Be(t=n(t),e).then(e=>new tt(e,this.storage));var t}getMetadata(){return Je(this._delegate)}updateMetadata(e){return Fe(n(this._delegate),e)}getDownloadURL(){return He(n(this._delegate))}delete(){return this._throwIfRoot("delete"),qe(n(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw te(e)}}class rt{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(st(e))throw u("ref() expected a child path but got a URL, use refFromURL instead.");return new D(Ye(this._delegate,e),this)}refFromURL(e){if(!st(e))throw u("refFromURL() expected a full URL but got a child path, use ref() instead.");try{_.makeFromUrl(e,this._delegate.host)}catch(e){throw u("refFromUrl() expected a valid full URL but got an invalid one.")}return new D(Ye(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,r={}){var s;[e,t,r,s={}]=[this._delegate,e,t,r],Ge(e,t,r,s)}}function st(e){return/^[A-Za-z]+:\/\//.test(e)}function nt(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("storage").getImmediate({identifier:t});return new rt(r,s)}e=M.default,K={TaskState:t,TaskEvent:Ne,StringFormat:y,Storage:rt,Reference:D},e.INTERNAL.registerComponent(new X("storage-compat",nt,"PUBLIC").setServiceProps(K).setMultipleInstances(!0)),e.registerVersion("@firebase/storage-compat","0.4.0-canary.a09ef786f")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-storage-compat.js - be sure to load firebase-app.js first.")}});
|
|
17
17
|
//# sourceMappingURL=firebase-storage-compat.js.map
|