firebase 13.2.0-eap-sql.a9a137e67 → 13.2.0-eap-sql.b903ef716

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/app/dist/esm/index.esm.js +1 -1
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.mjs +1 -1
  4. package/compat/app/dist/esm/index.esm.js +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.mjs +1 -1
  7. package/compat/dist/esm/index.esm.js +2 -2
  8. package/compat/dist/index.node.cjs +2 -2
  9. package/compat/dist/index.rn.cjs.js +2 -2
  10. package/firebase-ai.js +1 -1
  11. package/firebase-analytics-compat.js +1 -1
  12. package/firebase-analytics.js +1 -1
  13. package/firebase-app-check-compat.js +1 -1
  14. package/firebase-app-check.js +1 -1
  15. package/firebase-app-compat.js +2 -2
  16. package/firebase-app.js +5 -5
  17. package/firebase-auth-compat.js +1 -1
  18. package/firebase-auth-cordova.js +1 -1
  19. package/firebase-auth-web-extension.js +1 -1
  20. package/firebase-auth.js +1 -1
  21. package/firebase-compat.js +6 -6
  22. package/firebase-crashlytics.js +1 -1
  23. package/firebase-data-connect.js +1 -1
  24. package/firebase-database-compat.js +1 -1
  25. package/firebase-database.js +1 -1
  26. package/firebase-firestore-compat.js +2 -2
  27. package/firebase-firestore-lite-pipelines.js +1 -1
  28. package/firebase-firestore-lite.js +1 -1
  29. package/firebase-firestore-pipelines.js +1 -1
  30. package/firebase-firestore.js +1 -1
  31. package/firebase-functions-compat.js +1 -1
  32. package/firebase-functions.js +1 -1
  33. package/firebase-installations-compat.js +1 -1
  34. package/firebase-installations.js +1 -1
  35. package/firebase-messaging-compat.js +1 -1
  36. package/firebase-messaging-sw.js +1 -1
  37. package/firebase-messaging.js +1 -1
  38. package/firebase-performance-compat.js +1 -1
  39. package/firebase-performance-standalone-compat.js +7 -7
  40. package/firebase-performance.js +1 -1
  41. package/firebase-remote-config-compat.js +1 -1
  42. package/firebase-remote-config.js +1 -1
  43. package/firebase-sql.js +1 -1
  44. package/firebase-sql.js.map +1 -1
  45. package/firebase-storage-compat.js +1 -1
  46. package/firebase-storage.js +1 -1
  47. package/package.json +31 -31
@@ -1,3 +1,3 @@
1
- import{registerVersion as e,_registerComponent as t,_getProvider,SDK_VERSION as i,getApp as s}from"https://www.gstatic.com/firebasejs/13.2.0-eap-sql.a9a137e67/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],a=n?function replaceTemplate(e,t){try{let i=0,s="";for(;i<e.length;){const n=e.indexOf("{$",i);if(-1===n){s+=e.substring(i);break}const a=e.indexOf("}",n+2);if(-1===a){s+=e.substring(i);break}const r=e.substring(n+2,a),o=t[r];s+=e.substring(i,n)+(null!=o?String(o):`<${r}?>`),i=a+1}return s}catch(t){return e}}(n,i):"Error",r=`${this.serviceName}: ${a} (${s}).`;return new FirebaseError(s,r,i)}}function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a,r,o;!function(e){e.LAZY="LAZY",e.EAGER="EAGER",e.EXPLICIT="EXPLICIT"}(a||(a={})),function(e){e.PUBLIC="PUBLIC",e.PRIVATE="PRIVATE",e.VERSION="VERSION"}(r||(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"}(o||(o={}));const c={debug:o.DEBUG,verbose:o.VERBOSE,info:o.INFO,warn:o.WARN,error:o.ERROR,silent:o.SILENT},l=o.INFO,u={[o.DEBUG]:"log",[o.VERBOSE]:"log",[o.INFO]:"info",[o.WARN]:"warn",[o.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=u[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=l,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in o))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[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,o.DEBUG,...e),this._logHandler(this,o.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,o.VERBOSE,...e),this._logHandler(this,o.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,o.INFO,...e),this._logHandler(this,o.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,o.WARN,...e),this._logHandler(this,o.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,o.ERROR,...e),this._logHandler(this,o.ERROR,...e)}}let g,h;const d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap,w=new WeakMap;let v={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return f.get(e);if("objectStoreNames"===t)return e.objectStoreNames||p.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!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 h||(h=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(d.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return p.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(f.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));f.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,v):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&d.set(t,e)})).catch((()=>{})),w.set(t,e),t}(e);if(m.has(e))return m.get(e);const t=transformCachableValue(e);return t!==e&&(m.set(e,t),w.set(t,e)),t}const unwrap=e=>w.get(e);const y=["get","getKey","getAll","getAllKeys","count"],b=["put","add","delete","clear"],E=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(E.get(t))return E.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=b.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!y.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return E.set(t,method),method}!function replaceTraps(e){v=e(v)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const C="@firebase/installations",I="0.6.24-eap-sql.a9a137e67",S=1e4,T=`w:${I}`,R="FIS_v2",_=36e5,k=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return k.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.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 i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${R} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const M=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return M.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const A=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===A.size&&F&&(F.close(),F=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=A.get(e);if(i)for(const e of i)e(t)}let F=null;const L="firebase-installations-store";let x=null;function getDbPromise(){return x||(x=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(L)}})),x}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(L,"readwrite"),n=s.objectStore(L),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(L,"readwrite");await i.objectStore(L).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(L,"readwrite"),n=s.objectStore(L),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(k.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:R,appId:e.appId,sdkVersion:T},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,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:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw k.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+S<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:T,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw k.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+_}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw k.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw k.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+S<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 i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return k.create("missing-app-config-values",{valueName:e})}const D="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=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 i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(C,I),e(C,I,"esm2020");const P="@firebase/remote-config",B="0.9.3-eap-sql.a9a137e67";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const O="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}","analytics-unavailable":"Connection to Firebase Analytics failed: {$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}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw N.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=s(),t={}){e=getModularInstance(e);const i=_getProvider(e,O);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw N.create("already-initialized")}i.initialize({options:t});const n=i.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t).updateActiveExperiments(i.experiments||[]);return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),n]),!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),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),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,i)=>(t[i]=getValue(e,i),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 i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._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 i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=o.DEBUG;break;case"silent":i._logger.logLevel=o.SILENT;break;default:i._logger.logLevel=o.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"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:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(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 u=l.status;const g=l.headers.get("ETag")||void 0;let h,d,f,p,m;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,p=e.experimentDescriptions,m=e.rolloutMetadata}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[],m=[]),304!==u&&200!==u)throw N.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h,templateVersion:f,experiments:p,rollouts:m}}}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:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(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 s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return N.create(t,{originalErrorMessage:i&&i?.message})}const V="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)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",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,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(V,{keyPath:"compositeKey"})}}catch(e){t(N.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([V],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(V),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(N.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(V),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(N.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([V],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([V],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([V],"readwrite").objectStore(V),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(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 i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw N.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}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 i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.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 $="X-Goog-Api-Key",j="X-Goog-Firebase-Installations-Auth",q="featureDisabled",U="retryIntervalSeconds",K="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,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,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,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,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[$]:this.apiKey,[j]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","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:s})}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 i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,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(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}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("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+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,i,s){const n=new Set,a=new Set(Object.keys(e||{})),r=new Set(Object.keys(t||{})),o=i.experiments||[],c=s?.experiments||[],l=this.createExperimentsMap(o),u=this.createExperimentsMap(c),g=i.rollouts||[],h=s?.rollouts||[],d=this.createRolloutsMap(g),f=this.createRolloutsMap(h);for(const i of a){if(!r.has(i)||e[i]!==t[i]){n.add(i);continue}if(l.has(i)!==u.has(i)){n.add(i);continue}const s=l.get(i),a=u.get(i);if(s&&a&&!this.areExperimentsEqual(s,a)){n.add(i);continue}if(d.has(i)!==f.has(i)){n.add(i);continue}const o=d.get(i),c=f.get(i);o&&c&&!this.areRolloutsEqual(o,c)&&n.add(i)}for(const e of r)a.has(e)||n.add(e);return n}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}areRolloutsEqual(e,t){if(e.size!==t.size)return!1;for(const[i,s]of e)if(t.get(i)!==s)return!1;return!0}createExperimentsMap(e){const t=new Map;for(const i of e)if(i.affectedParameterKeys&&!i.experimentId.startsWith("_exp_rollout"))for(const e of i.affectedParameterKeys)t.set(e,i);return t}createRolloutsMap(e){const t=new Map;for(const i of e){const e=i.rolloutId,s=i.variantId,n=i.affectedParameterKeys||[];for(const i of n){let n=t.get(i);n||(n=new Map,t.set(i,n)),n.set(e,s)}}return t}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.storage.getLastSuccessfulFetchResponse(),o=await this.cachingClient.fetch(e);let c=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(o,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==o.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==c&&(c={});const l=this.getChangedParams(o.config,c,o,r);if(0===l.size)return void this.logger.debug("Config was fetched, but no params changed.");const u={getUpdatedKeys:()=>new Set(l)};this.executeAllListenerCallbacks(u)}catch(e){const t=e instanceof Error?e.message:String(e),i=N.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}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 i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if(q in e&&!0===e[q]){const e=N.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(K in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[K]);t&&i>t&&await this.autoFetch(3,i)}if(U in e){const t=Number(e[U]);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}))}i=""}}}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 i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.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{const e=this.isInBackground;if(await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1),!this.isInBackground)if(e)this.resetRetryCount(),await this.retryHttpConnectionWhenBackoffEnds();else{const e=void 0===s||this.isStatusCodeRetryable(s);if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=N.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}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 i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(O,(function remoteConfigFactory(e,{options:t}){const s=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),a=e.getProvider("analytics-internal"),{projectId:r,apiKey:c,appId:l}=s.options;if(!r)throw N.create("registration-project-id");if(!c)throw N.create("registration-api-key");if(!l)throw N.create("registration-app-id");const u=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(l,s.name,u):new InMemoryStorage,h=new StorageCache(g),d=new Logger(P);d.logLevel=o.ERROR;const f=new RestClient(n,i,u,r,c,l),p=new RetryingClient(f,g),m=new CachingClient(p,g,h,d),w=new RealtimeHandler(n,g,i,u,r,c,l,d,h,m),v=new RemoteConfig(s,m,h,g,d,w,a);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(P,B),e(P,B,"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,SDK_VERSION as i,getApp as s}from"https://www.gstatic.com/firebasejs/13.2.0-eap-sql.b903ef716/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],a=n?function replaceTemplate(e,t){try{let i=0,s="";for(;i<e.length;){const n=e.indexOf("{$",i);if(-1===n){s+=e.substring(i);break}const a=e.indexOf("}",n+2);if(-1===a){s+=e.substring(i);break}const r=e.substring(n+2,a),o=t[r];s+=e.substring(i,n)+(null!=o?String(o):`<${r}?>`),i=a+1}return s}catch(t){return e}}(n,i):"Error",r=`${this.serviceName}: ${a} (${s}).`;return new FirebaseError(s,r,i)}}function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a,r,o;!function(e){e.LAZY="LAZY",e.EAGER="EAGER",e.EXPLICIT="EXPLICIT"}(a||(a={})),function(e){e.PUBLIC="PUBLIC",e.PRIVATE="PRIVATE",e.VERSION="VERSION"}(r||(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"}(o||(o={}));const c={debug:o.DEBUG,verbose:o.VERBOSE,info:o.INFO,warn:o.WARN,error:o.ERROR,silent:o.SILENT},l=o.INFO,u={[o.DEBUG]:"log",[o.VERBOSE]:"log",[o.INFO]:"info",[o.WARN]:"warn",[o.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=u[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=l,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in o))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?c[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,o.DEBUG,...e),this._logHandler(this,o.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,o.VERBOSE,...e),this._logHandler(this,o.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,o.INFO,...e),this._logHandler(this,o.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,o.WARN,...e),this._logHandler(this,o.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,o.ERROR,...e),this._logHandler(this,o.ERROR,...e)}}let g,h;const d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap,w=new WeakMap;let v={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return f.get(e);if("objectStoreNames"===t)return e.objectStoreNames||p.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!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 h||(h=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(d.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return p.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(f.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));f.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,v):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&d.set(t,e)})).catch((()=>{})),w.set(t,e),t}(e);if(m.has(e))return m.get(e);const t=transformCachableValue(e);return t!==e&&(m.set(e,t),w.set(t,e)),t}const unwrap=e=>w.get(e);const y=["get","getKey","getAll","getAllKeys","count"],b=["put","add","delete","clear"],E=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(E.get(t))return E.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=b.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!y.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return E.set(t,method),method}!function replaceTraps(e){v=e(v)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const C="@firebase/installations",I="0.6.24-eap-sql.b903ef716",S=1e4,T=`w:${I}`,R="FIS_v2",_=36e5,k=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return k.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.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 i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${R} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const M=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return M.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const A=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===A.size&&F&&(F.close(),F=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=A.get(e);if(i)for(const e of i)e(t)}let F=null;const L="firebase-installations-store";let x=null;function getDbPromise(){return x||(x=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(L)}})),x}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(L,"readwrite"),n=s.objectStore(L),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(L,"readwrite");await i.objectStore(L).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(L,"readwrite"),n=s.objectStore(L),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(k.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:R,appId:e.appId,sdkVersion:T},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,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:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw k.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+S<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:T,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw k.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+_}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw k.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw k.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+S<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 i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return k.create("missing-app-config-values",{valueName:e})}const D="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=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 i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(C,I),e(C,I,"esm2020");const P="@firebase/remote-config",B="0.9.3-eap-sql.b903ef716";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const O="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}","analytics-unavailable":"Connection to Firebase Analytics failed: {$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}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw N.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=s(),t={}){e=getModularInstance(e);const i=_getProvider(e,O);if(i.isInitialized()){if(deepEqual(i.getOptions(),t))return i.getImmediate();throw N.create("already-initialized")}i.initialize({options:t});const n=i.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t).updateActiveExperiments(i.experiments||[]);return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),n]),!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),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),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,i)=>(t[i]=getValue(e,i),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 i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._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 i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=o.DEBUG;break;case"silent":i._logger.logLevel=o.SILENT;break;default:i._logger.logLevel=o.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"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:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(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 u=l.status;const g=l.headers.get("ETag")||void 0;let h,d,f,p,m;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,p=e.experimentDescriptions,m=e.rolloutMetadata}if("INSTANCE_STATE_UNSPECIFIED"===d?u=500:"NO_CHANGE"===d?u=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[],m=[]),304!==u&&200!==u)throw N.create("fetch-status",{httpStatus:u});return{status:u,eTag:g,config:h,templateVersion:f,experiments:p,rollouts:m}}}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:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(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 s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return N.create(t,{originalErrorMessage:i&&i?.message})}const V="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)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",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,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(V,{keyPath:"compositeKey"})}}catch(e){t(N.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([V],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(V),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(N.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(V),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(N.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([V],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([V],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([V],"readwrite").objectStore(V),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(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 i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw N.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}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 i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.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 $="X-Goog-Api-Key",j="X-Goog-Firebase-Installations-Auth",q="featureDisabled",U="retryIntervalSeconds",K="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,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,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,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,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[$]:this.apiKey,[j]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","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:s})}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 i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,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(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}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("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+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,i,s){const n=new Set,a=new Set(Object.keys(e||{})),r=new Set(Object.keys(t||{})),o=i.experiments||[],c=s?.experiments||[],l=this.createExperimentsMap(o),u=this.createExperimentsMap(c),g=i.rollouts||[],h=s?.rollouts||[],d=this.createRolloutsMap(g),f=this.createRolloutsMap(h);for(const i of a){if(!r.has(i)||e[i]!==t[i]){n.add(i);continue}if(l.has(i)!==u.has(i)){n.add(i);continue}const s=l.get(i),a=u.get(i);if(s&&a&&!this.areExperimentsEqual(s,a)){n.add(i);continue}if(d.has(i)!==f.has(i)){n.add(i);continue}const o=d.get(i),c=f.get(i);o&&c&&!this.areRolloutsEqual(o,c)&&n.add(i)}for(const e of r)a.has(e)||n.add(e);return n}areExperimentsEqual(e,t){return e.experimentId===t.experimentId&&e.variantId===t.variantId&&e.timeToLiveMillis===t.timeToLiveMillis&&e.triggerTimeoutMillis===t.triggerTimeoutMillis}areRolloutsEqual(e,t){if(e.size!==t.size)return!1;for(const[i,s]of e)if(t.get(i)!==s)return!1;return!0}createExperimentsMap(e){const t=new Map;for(const i of e)if(i.affectedParameterKeys&&!i.experimentId.startsWith("_exp_rollout"))for(const e of i.affectedParameterKeys)t.set(e,i);return t}createRolloutsMap(e){const t=new Map;for(const i of e){const e=i.rolloutId,s=i.variantId,n=i.affectedParameterKeys||[];for(const i of n){let n=t.get(i);n||(n=new Map,t.set(i,n)),n.set(e,s)}}return t}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.storage.getLastSuccessfulFetchResponse(),o=await this.cachingClient.fetch(e);let c=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(o,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==o.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==c&&(c={});const l=this.getChangedParams(o.config,c,o,r);if(0===l.size)return void this.logger.debug("Config was fetched, but no params changed.");const u={getUpdatedKeys:()=>new Set(l)};this.executeAllListenerCallbacks(u)}catch(e){const t=e instanceof Error?e.message:String(e),i=N.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}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 i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if(q in e&&!0===e[q]){const e=N.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(K in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[K]);t&&i>t&&await this.autoFetch(3,i)}if(U in e){const t=Number(e[U]);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}))}i=""}}}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 i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.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{const e=this.isInBackground;if(await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1),!this.isInBackground)if(e)this.resetRetryCount(),await this.retryHttpConnectionWhenBackoffEnds();else{const e=void 0===s||this.isStatusCodeRetryable(s);if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=N.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}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 i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(O,(function remoteConfigFactory(e,{options:t}){const s=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),a=e.getProvider("analytics-internal"),{projectId:r,apiKey:c,appId:l}=s.options;if(!r)throw N.create("registration-project-id");if(!c)throw N.create("registration-api-key");if(!l)throw N.create("registration-app-id");const u=t?.templateId||"firebase",g=isIndexedDBAvailable()?new IndexedDbStorage(l,s.name,u):new InMemoryStorage,h=new StorageCache(g),d=new Logger(P);d.logLevel=o.ERROR;const f=new RestClient(n,i,u,r,c,l),p=new RetryingClient(f,g),m=new CachingClient(p,g,h,d),w=new RealtimeHandler(n,g,i,u,r,c,l,d,h,m),v=new RemoteConfig(s,m,h,g,d,w,a);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(P,B),e(P,B,"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
package/firebase-sql.js CHANGED
@@ -1,3 +1,3 @@
1
- import{_registerComponent as e,registerVersion as t,_removeServiceInstance as r,_isFirebaseServerApp as s,getApp as i,_getProvider,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/13.2.0-eap-sql.a9a137e67/firebase-app.js";const a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let t=0;t<e.length;t+=3){const i=e[t],n=t+1<e.length,a=n?e[t+1]:0,o=t+2<e.length,l=o?e[t+2]:0,h=i>>2,c=(3&i)<<4|a>>4;let u=(15&a)<<2|l>>6,d=63&l;o||(d=64,n||(u=64)),s.push(r[h],r[c],r[u],r[d])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let s=0;s<e.length;s++){let i=e.charCodeAt(s);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&s+1<e.length&&56320==(64512&e.charCodeAt(s+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++s)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,s=0;for(;r<e.length;){const i=e[r++];if(i<128)t[s++]=String.fromCharCode(i);else if(i>191&&i<224){const n=e[r++];t[s++]=String.fromCharCode((31&i)<<6|63&n)}else if(i>239&&i<365){const n=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[s++]=String.fromCharCode(55296+(n>>10)),t[s++]=String.fromCharCode(56320+(1023&n))}else{const n=e[r++],a=e[r++];t[s++]=String.fromCharCode((15&i)<<12|(63&n)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],n=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const o=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==n||null==a||null==o)throw new DecodeBase64StringError;const l=i<<2|n>>4;if(s.push(l),64!==a){const e=n<<4&240|a>>2;if(s.push(e),64!==o){const e=a<<6&192|o;s.push(e)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],n=i?function replaceTemplate(e,t){try{let r=0,s="";for(;r<e.length;){const i=e.indexOf("{$",r);if(-1===i){s+=e.substring(r);break}const n=e.indexOf("}",i+2);if(-1===n){s+=e.substring(r);break}const a=e.substring(i+2,n),o=t[a];s+=e.substring(r,i)+(null!=o?String(o):`<${a}?>`),r=n+1}return s}catch(t){return e}}(i,r):"Error",a=`${this.serviceName}: ${n} (${s}).`;return new FirebaseError(s,a,r)}}function jsonEval(e){return JSON.parse(e)}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var o,l;!function(e){e.LAZY="LAZY",e.EAGER="EAGER",e.EXPLICIT="EXPLICIT"}(o||(o={})),function(e){e.PUBLIC="PUBLIC",e.PRIVATE="PRIVATE",e.VERSION="VERSION"}(l||(l={}));var h=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};const getRetryDelay=e=>Math.min(1e3*2**e,3e4),c=[520,503],u=["GET","HEAD","OPTIONS"];function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function toPropertyKey(e){var t=function toPrimitive(e,t){if("object"!=_typeof(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=_typeof(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==_typeof(t)?t:t+""}function _defineProperty(e,t,r){return(t=toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function sleep(e,t){return new Promise((r=>{if(null==t?void 0:t.aborted)return void r();const s=setTimeout((()=>{null==t||t.removeEventListener("abort",onAbort),r()}),e);function onAbort(){clearTimeout(s),r()}null==t||t.addEventListener("abort",onAbort)}))}function shouldRetry(e,t,r,s){return!(!s||r>=3)&&(!!u.includes(e)&&!!c.includes(t))}async function fetchWithRetry(e,t,r,s){let i=0;for(;;){const l=_objectSpread2({},r.headers);let h;i>0&&(l["X-Retry-Count"]=String(i));try{h=await e(t,{method:r.method,headers:l,body:r.body,signal:r.signal})}catch(e){var n;if("AbortError"===(null==e?void 0:e.name)||"ABORT_ERR"===(null==e?void 0:e.code)||"TimeoutError"===(null==e?void 0:e.name)&&(null===(n=r.signal)||void 0===n?void 0:n.aborted))throw e;if(!u.includes(r.method))throw e;if(s&&i<3){const e=getRetryDelay(i);i++,await sleep(e,r.signal);continue}throw e}if(!shouldRetry(r.method,h.status,i,s))return h;{var a,o;const e=null!==(a=null===(o=h.headers)||void 0===o?void 0:o.get("Retry-After"))&&void 0!==a?a:null,t=null!==e?1e3*Math.max(0,parseInt(e,10)||0):getRetryDelay(i);await h.text(),i++,await sleep(t,r.signal)}}}var d=class{constructor(e){var t,r,s,i,n;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,this.shouldStripNulls=null!==(s=e.shouldStripNulls)&&void 0!==s&&s,this.urlLengthLimit=null!==(i=e.urlLengthLimit)&&void 0!==i?i:8e3,this.retryEnabled=null===(n=e.retry)||void 0===n||n,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):e&&"application/json"!==e||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{const e={};r.headers.forEach(((t,r)=>{e[r]=t}));const t=await fetchWithRetry(s,r.url.toString(),{method:r.method,headers:e,body:JSON.stringify(r.body,((e,t)=>"bigint"==typeof t?t.toString():t)),signal:r.signal},r.retryEnabled);return await r.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch((e=>{var t;let r="",s="",i="";const n=null==e?void 0:e.cause;if(n){var a,o,l,h;const t=null!==(a=null==n?void 0:n.message)&&void 0!==a?a:"",s=null!==(o=null==n?void 0:n.code)&&void 0!==o?o:"";r=`${null!==(l=null==e?void 0:e.name)&&void 0!==l?l:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(h=null==n?void 0:n.name)&&void 0!==h?h:"Error"}: ${t}`,s&&(r+=` (${s})`),(null==n?void 0:n.stack)&&(r+=`\n${n.stack}`)}else{var c;r=null!==(c=null==e?void 0:e.stack)&&void 0!==c?c:""}const u=this.url.toString().length;return"AbortError"===(null==e?void 0:e.name)||"ABORT_ERR"===(null==e?void 0:e.code)?(i="",s="Request was aborted (timeout or manual cancellation)",u>this.urlLengthLimit&&(s+=`. Note: Your request URL is ${u} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):"HeadersOverflowError"!==(null==n?void 0:n.name)&&"UND_ERR_HEADERS_OVERFLOW"!==(null==n?void 0:n.code)||(i="",s="HTTP headers exceeded server limits (typically 16KB)",u>this.urlLengthLimit&&(s+=`. Your request URL is ${u} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:s,code:i},data:null,count:null,status:0,statusText:""}}))),i.then(e,t)}async processResponse(e){var t=this;let r=null,s=null,i=null,n=e.status,a=e.statusText;if(e.ok){var o,l;if("HEAD"!==t.method){var c;const i=await e.text();if(""===i);else if("text/csv"===t.headers.get("Accept"))s=i;else if(t.headers.get("Accept")&&(null===(c=t.headers.get("Accept"))||void 0===c?void 0:c.includes("application/vnd.pgrst.plan+text")))s=i;else try{s=JSON.parse(i)}catch(e){if(r={message:i},s=null,t.shouldThrowOnError)throw new h({message:i,details:"",hint:"",code:""})}}const d=null===(o=t.headers.get("Prefer"))||void 0===o?void 0:o.match(/count=(exact|planned|estimated)/),p=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");if(d&&p&&p.length>1&&(i=parseInt(p[1])),t.isMaybeSingle&&Array.isArray(s))if(s.length>1){var u;if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,i=null,n=406,a="Not Acceptable",t.shouldThrowOnError)throw new h(_objectSpread2(_objectSpread2({},r),{},{hint:null!==(u=r.hint)&&void 0!==u?u:""}))}else s=1===s.length?s[0]:null}else{const i=await e.text();try{r=JSON.parse(i),Array.isArray(r)&&404===e.status&&(s=[],r=null,n=200,a="OK")}catch(t){404===e.status&&""===i?(n=204,a="No Content"):r={message:i}}if(r&&t.shouldThrowOnError)throw new h(r)}return{success:null===r,error:r,data:s,count:i,status:n,statusText:a}}returns(){return this}overrideTypes(){return this}},p=class extends d{throwOnError(){return super.throwOnError()}select(e){let t=!1;const r=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const g=new RegExp("[,()]");var f=class extends p{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map((e=>"string"==typeof e&&g.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map((e=>"string"==typeof e&&g.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");const n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).forEach((([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)})),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},m=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3,retry:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i,this.retry=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},i=r?"HEAD":"GET";let n=!1;const a=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e))).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new f({method:i,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));i.searchParams.set("columns",e.join(","))}}return new f({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;const{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));a.searchParams.set("columns",e.join(","))}}return new f({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;const{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new f({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new f({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function toOpenApiError(e,t){try{const t=JSON.parse(e);var r,s,i,n;if(t&&"object"==typeof t&&!Array.isArray(t))return new h({message:String(null!==(r=t.message)&&void 0!==r?r:e),details:null!==(s=t.details)&&void 0!==s?s:"",hint:null!==(i=t.hint)&&void 0!==i?i:"",code:null!==(n=t.code)&&void 0!==n?n:""})}catch(e){}return new h({message:e||t,details:"",hint:"",code:""})}function toTransportFailure(e,t,r){var s;const i=e;return{success:!1,error:new h({message:`${null!==(s=null==i?void 0:i.name)&&void 0!==s?s:"FetchError"}: ${null==i?void 0:i.message}`,details:"",hint:"",code:""}),data:null,count:null,status:t,statusText:r}}var E,v=class PostgrestClient{constructor(e,{headers:t={},schema:r,fetch:s,timeout:i,urlLengthLimit:n=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=n;const o=null!=s?s:globalThis.fetch;this.fetch=void 0!==i&&i>0?(e,t)=>{const r=new AbortController,s=setTimeout((()=>r.abort()),i),n=null==t?void 0:t.signal;if(n){if(n.aborted)return clearTimeout(s),o(e,t);const abortHandler=()=>{clearTimeout(s),r.abort()};return n.addEventListener("abort",abortHandler,{once:!0}),o(e,_objectSpread2(_objectSpread2({},t),{},{signal:r.signal})).finally((()=>{clearTimeout(s),n.removeEventListener("abort",abortHandler)}))}return o(e,_objectSpread2(_objectSpread2({},t),{},{signal:r.signal})).finally((()=>clearTimeout(s)))}:o,this.retry=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new m(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new PostgrestClient(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e,t=this;const r=new Headers(t.headers);r.set("Accept","application/openapi+json"),t.schemaName&&r.set("Accept-Profile",t.schemaName);const s={};r.forEach(((e,t)=>{s[t]=e}));const i=null!==(e=t.fetch)&&void 0!==e?e:globalThis.fetch;let n,a;try{var o;n=await fetchWithRetry(i,`${t.url}/`,{method:"GET",headers:s},null===(o=t.retry)||void 0===o||o)}catch(e){return toTransportFailure(e,0,"")}try{a=await n.text()}catch(e){return toTransportFailure(e,n.status,n.statusText)}if(n.ok)try{return{success:!0,error:null,data:JSON.parse(a),count:null,status:n.status,statusText:n.statusText}}catch(e){}return{success:!1,error:toOpenApiError(a,n.statusText),data:null,count:null,status:n.status,statusText:n.statusText}}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a;const o=new URL(`${this.url}/rpc/${e}`);let l;const _isObject=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(_isObject)),h=r&&Object.values(t).some(_isObject);h?(a="POST",l=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter((([e,t])=>void 0!==t)).map((([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`])).forEach((([e,t])=>{o.searchParams.append(e,t)}))):(a="POST",l=t);const c=new Headers(this.headers);return h?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new f({method:a,url:o,headers:c,schema:this.schemaName,body:l,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};!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"}(E||(E={}));const b={debug:E.DEBUG,verbose:E.VERBOSE,info:E.INFO,warn:E.WARN,error:E.ERROR,silent:E.SILENT},y=E.INFO,_={[E.DEBUG]:"log",[E.VERBOSE]:"log",[E.INFO]:"info",[E.WARN]:"warn",[E.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),i=_[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${s}] ${e.name}:`,...r)};const T="@firebase/sql",S="0.0.1-eap-sql.a9a137e67",L=Object.freeze({OTHER:"other",ALREADY_INITIALIZED:"already-initialized",NOT_INITIALIZED:"not-initialized",NOT_SUPPORTED:"not-supported",INVALID_ARGUMENT:"invalid-argument",PARTIAL_ERROR:"partial-error",UNAUTHORIZED:"unauthorized"}),A=Object.freeze({SQL_POSTGREST:"sql-postgrest",SQL_PLATFORM:"sql-platform",SQL_CLIENT:"sql-client"});class FirebaseSqlError extends FirebaseError{constructor(e,t,r,s,i,n){super(e,t),this.name="FirebaseSqlError",this.code=e,this.category=r,this.details=s,this.hint=i,this.status=n,Object.setPrototypeOf(this,FirebaseSqlError.prototype)}toJSON(){const e={name:this.name,code:this.code,message:this.message,category:this.category};return void 0!==this.details&&(e.details=this.details),void 0!==this.hint&&(e.hint=this.hint),void 0!==this.status&&(e.status=this.status),e}toString(){const e=this.details?` (details: ${this.details})`:"",t=this.hint?` (hint: ${this.hint})`:"";return`${this.name}[code=${this.code}]: ${this.message}${e}${t}`.trim()}}function isPlainRecord(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function normalizeNonEmptyString(e){return"string"==typeof e&&e.length>0?e:void 0}function normalizeDetails(e){const t=normalizeNonEmptyString(e);return void 0!==t?t:"object"==typeof e&&null!==e?JSON.stringify(e):void 0}function normalizeHint(e){return normalizeNonEmptyString(e)}function mapPlatformStatusToCode(e,t){return 401===e||403===e||"UNAUTHENTICATED"===t||"PERMISSION_DENIED"===t?L.UNAUTHORIZED:400===e||"INVALID_ARGUMENT"===t?L.INVALID_ARGUMENT:501===e||"UNIMPLEMENTED"===t?L.NOT_SUPPORTED:L.OTHER}const mapPostgrestFailureToFirebaseSqlError=(e,t,r)=>{if(e instanceof FirebaseSqlError)return e;const s=t>0?t:void 0;if(0===t){const t=isPlainRecord(e)&&"string"==typeof e.message&&e.message.length>0||e instanceof Error&&e.message.length>0?e.message:"string"==typeof e&&e.length>0?e:"Network request failed.",r=isPlainRecord(e)?normalizeDetails(e.details):e instanceof Error?normalizeDetails(e.stack):void 0,s=isPlainRecord(e)?normalizeHint(e.hint):void 0;return new FirebaseSqlError(L.OTHER,t,A.SQL_CLIENT,r,s)}const i=Array.isArray(e)&&1===e.length?e[0]:e;if(isPlainRecord(i)&&isPlainRecord(i.error)){const e=i.error,n=mapPlatformStatusToCode(t,e.status),a="string"==typeof e.message&&e.message.length>0?e.message:r||`HTTP Error ${t}`;return new FirebaseSqlError(n,a,A.SQL_PLATFORM,normalizeDetails(e.details),normalizeHint(e.hint),s)}if(isPlainRecord(e)&&"string"==typeof e.error&&e.error.length>0){const r="string"==typeof e.error_description&&e.error_description.length>0?e.error_description:"string"==typeof e.message&&e.message.length>0?e.message:e.error;return new FirebaseSqlError(mapPlatformStatusToCode(t,e.status),r,A.SQL_PLATFORM,normalizeDetails(e.details),normalizeHint(e.hint),s)}if(isPlainRecord(e)&&"string"==typeof e.code&&e.code.length>0&&"string"!=typeof e.status){const t="string"==typeof e.message&&e.message.length>0?e.message:r||e.code;return new FirebaseSqlError(e.code,t,A.SQL_POSTGREST,normalizeDetails(e.details),normalizeHint(e.hint),s)}const n=isPlainRecord(e)&&"string"==typeof e.message&&e.message.length>0?e.message:"string"==typeof e&&e.length>0?e:r||`HTTP Error ${t}`,a=isPlainRecord(e)?normalizeDetails(e.details):Array.isArray(e)?normalizeDetails(e):void 0,o=isPlainRecord(e)?normalizeHint(e.hint):void 0;return new FirebaseSqlError(mapPlatformStatusToCode(t,isPlainRecord(e)?e.status:void 0),n,A.SQL_PLATFORM,a,o,s)};let I="";const w=Object.freeze({GOOG_API_CLIENT:"x-goog-api-client",CLIENT_VERSION:"x-client-version",FIREBASE_GMPID:"x-firebase-gmpid",FIREBASE_AUTH_TOKEN:"x-firebase-auth-token",FIREBASE_APPCHECK:"x-firebase-appcheck"}),P=["x-firebase-sqlconnect-affinity","x-goog-request-params","x-firebase-client","x-firebase-client-log-type","authorization"],O=new Set([...Object.values(w),...P]);function validateHeaderName(e){const t=String(e);if(O.has(t.trim().toLowerCase()))throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Cannot set protected header ${t}.`,A.SQL_CLIENT);return t}function resolveRequestHeaders(e,t,r,s){const i=new Headers;!function mergeHeadersInit(e,t){return t&&new Headers(t).forEach(((t,r)=>{e.set(r,t)})),e}(i,r?.headers);for(const e of P)i.delete(e);e?.accessToken?i.set(w.FIREBASE_AUTH_TOKEN,e.accessToken):i.delete(w.FIREBASE_AUTH_TOKEN),t?.token?i.set(w.FIREBASE_APPCHECK,t.token):i.delete(w.FIREBASE_APPCHECK),i.set(w.GOOG_API_CLIENT,function getGoogApiClientValue(){return"gl-js/ fire/"+I}()),i.set(w.CLIENT_VERSION,"web/"+I),void 0!==s?i.set(w.FIREBASE_GMPID,s):i.delete(w.FIREBASE_GMPID);const n={};return i.forEach(((e,t)=>{n[t]=e})),n}function copySqlServiceSettings(e){const t=Object.assign({},e);return void 0!==e.headers&&(t.headers=Object.assign({},e.headers)),t}function validateSqlServiceSettings(e){if(!e)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"SqlServiceSettings must be provided.",A.SQL_CLIENT);if(!e.serviceId)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"serviceId is required.",A.SQL_CLIENT);if(!e.location)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"location is required.",A.SQL_CLIENT);return function validatePort(e){if(void 0!==e&&("number"!=typeof e||!Number.isInteger(e)||e<1||e>65535))throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Port must be a valid integer between 1 and 65535 if provided. Received: ${String(e)}.`,A.SQL_CLIENT)}(e.port),function validateHeaders(e){if(e)for(const t of Object.keys(e))validateHeaderName(t)}(e.headers),function freezeSqlServiceSettings(e){const t=copySqlServiceSettings(e);return void 0!==t.headers&&Object.freeze(t.headers),Object.freeze(t)}(e)}const N="firebase-sql",R=new class Logger{constructor(e){this.name=e,this._logLevel=y,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in E))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?b[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,E.DEBUG,...e),this._logHandler(this,E.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,E.VERBOSE,...e),this._logHandler(this,E.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,E.INFO,...e),this._logHandler(this,E.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,E.WARN,...e),this._logHandler(this,E.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,E.ERROR,...e),this._logHandler(this,E.ERROR,...e)}}("@firebase/sql");function logDebug(e){R.debug(`Firebase SQL (${I}): ${e}`)}function logError(e){R.error(`Firebase SQL (${I}): ${e}`)}class AbstractTokenProvider{constructor(e,t){this.provider=e,this.serverAppToken=t,this.activeGetTokenPromise=void 0,this.activeForceRefreshPromise=void 0,this.resolveActiveGetTokenPromise=void 0,this.onInitUnsubscribe=void 0,this.activeListeners=[],this.queuedListeners=[],this.component=e?.getImmediate({optional:!0})??void 0,this.component||(this.onInitUnsubscribe=e?.onInit((e=>{this.component=e;const t=this.queuedListeners.length;for(let e=0;e<t;e++){const e=this.queuedListeners.shift();e&&this.addTokenChangeListener(e)}this.cancelOnInit()})))}getToken(e={forceRefresh:!1}){if(!this.activeForceRefreshPromise&&e.forceRefresh){const t=this.requestToken(e).then((e=>(this.resolveActiveGetTokenPromise?.(e),e))).finally((()=>{this.activeForceRefreshPromise===t&&(this.activeForceRefreshPromise=void 0)}));this.activeForceRefreshPromise=t}if(this.activeForceRefreshPromise)return this.activeForceRefreshPromise;if(!this.activeGetTokenPromise){const t=new Promise(((t,r)=>{this.resolveActiveGetTokenPromise=t,this.requestToken(e).then(t,r)})).finally((()=>{this.activeGetTokenPromise===t&&(this.activeGetTokenPromise=void 0,this.resolveActiveGetTokenPromise=void 0)}));this.activeGetTokenPromise=t}return this.activeGetTokenPromise}requestToken(e={forceRefresh:!1}){return this.component?this.fetchToken(this.component,e):this.provider?new Promise(((t,r)=>{setTimeout((()=>{this.component?this.requestToken(e).then(t,r):this.serverAppToken&&!e.forceRefresh?t(this.convertServerAppToken(this.serverAppToken)):t(null)}),0)})):this.serverAppToken&&!e.forceRefresh?Promise.resolve(this.convertServerAppToken(this.serverAppToken)):Promise.resolve(null)}addTokenChangeListener(e){if(this.component)try{this.activeListeners.push(e),this.addListener(this.component,e)}catch(e){this.activeListeners.pop(),logError(e instanceof Error?e.message:String(e))}else this.queuedListeners.push(e)}removeTokenChangeListener(e){if(this.component)try{removeFirstOccurrenceFromList(e,this.activeListeners),this.removeListener(this.component,e)}catch(e){logError(e instanceof Error?e.message:String(e))}removeFirstOccurrenceFromList(e,this.queuedListeners)}cancelOnInit(){this.onInitUnsubscribe?.(),this.onInitUnsubscribe=void 0,this.queuedListeners=[]}terminate(){this.cancelOnInit(),[...this.activeListeners].forEach((e=>this.removeTokenChangeListener(e)))}}function removeFirstOccurrenceFromList(e,t){const r=t.indexOf(e);return-1!==r&&t.splice(r,1),-1!==r}class AppCheckProvider extends AbstractTokenProvider{constructor(e,t){super(t,s(e)?e.settings.appCheckToken:void 0)}convertServerAppToken(e){return{token:e}}fetchToken(e,t={forceRefresh:!1}){return e.getToken(t.forceRefresh)}addListener(e,t){e.addTokenListener(t)}removeListener(e,t){e.removeTokenListener(t)}}class FirebaseAuthProvider extends AbstractTokenProvider{constructor(e,t){super(t,s(e)?e.settings.authIdToken:void 0)}getAuth(){return this.component}convertServerAppToken(e){return{accessToken:e}}fetchToken(e,t={forceRefresh:!1}){return e.getToken(t.forceRefresh).catch((e=>{if(e&&"object"==typeof e&&"code"in e&&"auth/token-not-initialized"===e.code)return logDebug("Got auth/token-not-initialized error. Treating as null token."),null;return logError("Error received when attempting to retrieve token: "+(e instanceof Error?e.message:String(e))),Promise.reject(e)}))}addListener(e,t){e.addAuthTokenListener(t)}removeListener(e,t){e.removeAuthTokenListener(t)}}function getAuthUidFromToken(e){if(!e)return null;try{if(3!==e.split(".").length)return null;const t=function(e){let t={},r={},s={},i="";try{const n=e.split(".");t=jsonEval(base64Decode(n[0])||""),r=jsonEval(base64Decode(n[1])||""),i=n[2],s=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:s,signature:i}}(e).claims,r=t?.sub;return"string"==typeof r&&r.length>0?r:null}catch{return null}}function toAbortError(e,t){const r=void 0!==t?t:e.reason;if(r instanceof Error&&("AbortError"===r.name||"TimeoutError"===r.name||r instanceof FirebaseSqlError))return r;const s=r instanceof Error?r.message:"string"==typeof r?r:"This operation was aborted",i=new Error(s);return i.name="AbortError",i}class FirebaseSqlTransport{constructor(e={}){this._isUsingEmulator=!1,this.settings=e.settings,this._appId=e.appId,this.authProvider=e.authTokenProvider,this.appCheckProvider=e.appCheckTokenProvider,this._terminationSignal=e.terminationSignal,this._state=e.state}async invokePostgrestOperation(e,t){if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);const r="string"==typeof e?e:e instanceof URL?e.toString():e.url,s=this._state?.active?.authTokenProvider??this.authProvider,i=this._state?.active?.appCheckTokenProvider??this.appCheckProvider,n=this._state?.active?.appId??this._appId,a=this._state?.terminationSignal??this._terminationSignal;if(a?.aborted)throw toAbortError(a);const o=void 0!==t?.signal?t.signal??void 0:"undefined"!=typeof Request&&e instanceof Request?e.signal:void 0,{signal:l,cleanup:h}=function composeSignals(e,t){if(!e)return{signal:t,cleanup:()=>{}};if(!t)return{signal:e,cleanup:()=>{}};if(e.aborted)return{signal:e,cleanup:()=>{}};if(t.aborted)return{signal:t,cleanup:()=>{}};if("function"==typeof AbortSignal.any)return{signal:AbortSignal.any([e,t]),cleanup:()=>{}};const r=new AbortController,onAbort1=()=>r.abort(e.reason),onAbort2=()=>r.abort(t.reason);return e.addEventListener("abort",onAbort1,{once:!0}),t.addEventListener("abort",onAbort2,{once:!0}),{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",onAbort1),t.removeEventListener("abort",onAbort2)}}}(o,a),c="undefined"!=typeof Request&&e instanceof Request;let u=t?.headers;if(c)if(void 0===t?.headers)u=e.headers;else{const r=new Headers(e.headers);new Headers(t.headers).forEach(((e,t)=>{r.set(t,e)})),u=r}const d={...c?{method:e.method,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity}:void 0,...t,headers:u};try{const a=function getFetch(){const e=globalThis.fetch;if(!e)throw new FirebaseSqlError(L.NOT_SUPPORTED,"No Fetch implementation detected in the current environment.",A.SQL_CLIENT);return e}();let o=null,h=null;try{const[e,t]=await Promise.all([s?s.getToken({forceRefresh:!1}):Promise.resolve(null),i?i.getToken({forceRefresh:!1}).catch((()=>null)):Promise.resolve(null)]);o=e,h=t}catch(e){if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l);const u=resolveRequestHeaders(o,h,d,n),p=this.buildRequestInit(d,u,r,l),g=getAuthUidFromToken(o?.accessToken),f=!("undefined"!=typeof ReadableStream&&(p.body instanceof ReadableStream||c&&void 0===t?.body&&e.bodyUsed));return await a(r,p).then((async e=>{if(this._state&&null===this._state.active)throw"function"==typeof e.body?.cancel&&await e.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);return 401===e.status&&o&&f&&s?this.refreshAuthAndRefetch(a,r,p,u,o,e,g,s):e})).catch((async e=>{if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}))}finally{h()}}buildRequestInit(e,t,r,s){const i=Object.assign({},e,{headers:t});return void 0!==s&&(i.signal=s),function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}(r)&&this._isUsingEmulator&&!i.credentials&&(i.credentials="include"),i}async refreshAuthAndRefetch(e,t,r,s,i,n,a,o){if(!o)return n;const l=r.signal;if(l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);let h=null;try{if(h=await o.getToken({forceRefresh:!1}).then((e=>e??null)).catch((()=>null)),l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);h?.accessToken&&h.accessToken!==i.accessToken||(h=await o.getToken({forceRefresh:!0}).then((e=>e??null)).catch((()=>null)))}catch(e){if("function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}if(l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(h?.accessToken&&h.accessToken!==i.accessToken){const i=getAuthUidFromToken(h.accessToken);if(null!==a&&i!==a)return n;"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{}));const o=Object.assign({},s);o[w.FIREBASE_AUTH_TOKEN]=h.accessToken;return e(t,Object.assign({},r,{headers:o}))}return n}toFetch(e){return async(t,r)=>{try{return await this.invokePostgrestOperation(t,r)}catch(t){const r=this._state&&null===this._state.active?new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT):t instanceof FirebaseSqlError?t:null;if(e&&r){e.clientError=r;const t=new Error(r.message);throw t.name="AbortError",t}throw t}}}}const createBuilderFetch=(e,t)=>new FirebaseSqlTransport({state:e}).toFetch(t);function resolvePostgrestUrl(e,t){const r=!1===e.sslEnabled?"http":"https",s=e.host??"firebasedataconnect.googleapis.com",i=new URL(`${r}://${s}`);void 0!==e.port&&(i.port=String(e.port));const n=encodeURIComponent(t),a=encodeURIComponent(e.location),o=encodeURIComponent(e.serviceId);return i.pathname=`/v1/projects/${n}/locations/${a}/services/${o}/postgrest`,i.toString()}class FilterBuilderImpl{constructor(e,t,r,s){this._shouldThrowOnError=!1,this._delegate=e,this._state=t,this._createFetch=r,this._mapError=s}throwOnError(){return this._shouldThrowOnError=!0,this}stripNulls(){return this._delegate.stripNulls(),this}setHeader(e,t){const r=validateHeaderName(e);return this._delegate.setHeader(r,t),this}retry(e){return this._delegate.retry(e),this}returns(){return this._delegate.returns(),this}overrideTypes(){return this._delegate.overrideTypes(),this}select(e){return this._delegate.select(e),this}order(e,t){return this._delegate.order(e,t),this}limit(e,t){return this._delegate.limit(e,t),this}range(e,t,r){return this._delegate.range(e,t,r),this}abortSignal(e){return this._delegate.abortSignal(e),this}single(){return this._delegate.single(),this}maybeSingle(){return this._delegate.maybeSingle(),this}csv(){return this._delegate.csv(),this}geojson(){return this._delegate.geojson(),this}explain(e){return this._delegate.explain(e),this}rollback(){return this._delegate.rollback(),this}maxAffected(e){return this._delegate.maxAffected(e),this}eq(e,t){return this._delegate.eq(e,t),this}neq(e,t){return this._delegate.neq(e,t),this}gt(e,t){return this._delegate.gt(e,t),this}gte(e,t){return this._delegate.gte(e,t),this}lt(e,t){return this._delegate.lt(e,t),this}lte(e,t){return this._delegate.lte(e,t),this}like(e,t){return this._delegate.like(e,t),this}likeAllOf(e,t){return this._delegate.likeAllOf(e,t),this}likeAnyOf(e,t){return this._delegate.likeAnyOf(e,t),this}ilike(e,t){return this._delegate.ilike(e,t),this}ilikeAllOf(e,t){return this._delegate.ilikeAllOf(e,t),this}ilikeAnyOf(e,t){return this._delegate.ilikeAnyOf(e,t),this}regexMatch(e,t){return this._delegate.regexMatch(e,t),this}regexIMatch(e,t){return this._delegate.regexIMatch(e,t),this}is(e,t){return this._delegate.is(e,t),this}isDistinct(e,t){return this._delegate.isDistinct(e,t),this}in(e,t){return this._delegate.in(e,t),this}notIn(e,t){return this._delegate.notIn(e,t),this}contains(e,t){return this._delegate.contains(e,t),this}containedBy(e,t){return this._delegate.containedBy(e,t),this}rangeGt(e,t){return this._delegate.rangeGt(e,t),this}rangeGte(e,t){return this._delegate.rangeGte(e,t),this}rangeLt(e,t){return this._delegate.rangeLt(e,t),this}rangeLte(e,t){return this._delegate.rangeLte(e,t),this}rangeAdjacent(e,t){return this._delegate.rangeAdjacent(e,t),this}overlaps(e,t){return this._delegate.overlaps(e,t),this}textSearch(e,t,r){return this._delegate.textSearch(e,t,r),this}match(e){return this._delegate.match(e),this}not(e,t,r){return this._delegate.not(e,t,r),this}or(e,t){return this._delegate.or(e,t),this}filter(e,t,r){return this._delegate.filter(e,t,r),this}then(e,t){const r=this._execute();return e||t?r.then(e,t):r}_fail(e,t,r){if(this._shouldThrowOnError)throw e;return{success:!1,error:e,data:null,count:null,status:t,statusText:r}}_execute(){const e={clientError:null};Reflect.set(this._delegate,"fetch",this._createFetch(this._state,e));try{return this._delegate.then((t=>{if(null===this._state.active)return this._fail(new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT),0,"");if(null!==e.clientError)return this._fail(e.clientError,0,"");if(!t.success||null!==t.error||t.status<200||t.status>=300)return this._fail(this._mapError(t.error,t.status,t.statusText),t.status,t.statusText);return{success:!0,error:null,data:t.data,count:t.count,status:t.status,statusText:t.statusText}}))}finally{Reflect.set(this._delegate,"fetch",void 0)}}}class QueryBuilderImpl{constructor(e,t,r,s){this._delegate=e,this._state=t,this._createFetch=r,this._mapError=s}_wrap(e){return new FilterBuilderImpl(e,this._state,this._createFetch,this._mapError)}select(e,t){return this._wrap(this._delegate.select(e,t))}insert(e,t){return this._wrap(this._delegate.insert(e,t))}upsert(e,t){return this._wrap(this._delegate.upsert(e,t))}update(e,t){return this._wrap(this._delegate.update(e,t))}delete(e){return this._wrap(this._delegate.delete(e))}}class FirebaseSql{constructor(e,t,r,s,i){this.app=e,this.settings=t,this._instanceIdentifier=r,this._terminationController=new AbortController,this._postgrestUrl=resolvePostgrestUrl(this.settings,e.options.projectId),this._state={active:{appId:e.options.appId,authTokenProvider:new FirebaseAuthProvider(e,s),appCheckTokenProvider:new AppCheckProvider(e,i)},terminationSignal:this._terminationController.signal},this._postgrestClient=new v(this._postgrestUrl,{headers:this.settings.headers,schema:this.settings.schemaName})}_delete(){if(null!==this._state.active){const e=this._state.active;this._state.active=null,this._terminationController.abort(new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT)),e.appCheckTokenProvider.terminate(),e.authTokenProvider.terminate(),r(this.app,N,this._instanceIdentifier)}return Promise.resolve()}_encodeResourceSegment(e,t){if("."===e||".."===e)throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Invalid resource name "${e}".`,A.SQL_CLIENT);return"string"!=typeof e||0===e.length||t&&""===e.trim()?e:encodeURIComponent(e)}from(e){if(null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT);const t=this._postgrestClient.from(this._encodeResourceSegment(e,!0));return new QueryBuilderImpl(t,this._state,createBuilderFetch,mapPostgrestFailureToFirebaseSqlError)}rpc(e,t,r){if(null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT);const s=this._postgrestClient.rpc(this._encodeResourceSegment(e,!1),t,r);return new FilterBuilderImpl(s,this._state,createBuilderFetch,mapPostgrestFailureToFirebaseSqlError)}}function getSql(e,t){let r,s;if(void 0===t)r=i(),s=e;else{if(void 0===e)r=i();else{if(!e||"object"!=typeof e||!("options"in e))throw new FirebaseSqlError(L.INVALID_ARGUMENT,"First argument passed to getSql() must be a FirebaseApp or SqlServiceSettings instance.",A.SQL_CLIENT);r=e}s=t}const n=validateSqlServiceSettings(s);if("string"!=typeof r.options?.projectId||0===r.options.projectId.length)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?",A.SQL_CLIENT);const a=getInstanceIdentifier(n,r.options.projectId),o=_getProvider(r,N);return o.isInitialized(a)?(logDebug("Re-using cached instance (NOTE: custom headers set on the original FSQL client are RE-USED when that client is re-used from the instance cache. Creating multiple FSQL clients with the same settings and app, but different headers, is NOT supported. Instead, use .setHeaders() while building an operation chain to set custom headers for that specific operation.)"),o.getImmediate({identifier:a})):(logDebug("Creating new Firebase SQL instance"),o.initialize({instanceIdentifier:a,options:n}))}function terminate(e){return e._delete()}function getInstanceIdentifier(e,t){const r=resolvePostgrestUrl(e,t);return JSON.stringify({resolvedUrl:r,schemaName:e.schemaName})}!function registerSql(r){!function setSDKVersion(e){I=e}(n),e(new Component(N,((e,{instanceIdentifier:t,options:r})=>{const s=r,i=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),a=e.getProvider("app-check-internal");if("string"!=typeof i.options?.projectId||0===i.options.projectId.length)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?",A.SQL_CLIENT);const o=t??getInstanceIdentifier(s,i.options.projectId);return new FirebaseSql(i,s,o,n,a)}),"PUBLIC").setMultipleInstances(!0)),t(T,S,r),t(T,S,"esm2020")}();export{L as Code,FirebaseSql,FirebaseSqlError,A as FirebaseSqlErrorCategory,copySqlServiceSettings,getSql,terminate};
1
+ import{_registerComponent as e,registerVersion as t,_removeServiceInstance as r,_isFirebaseServerApp as s,getApp as i,_getProvider,SDK_VERSION as n}from"https://www.gstatic.com/firebasejs/13.2.0-eap-sql.b903ef716/firebase-app.js";const a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let t=0;t<e.length;t+=3){const i=e[t],n=t+1<e.length,a=n?e[t+1]:0,o=t+2<e.length,l=o?e[t+2]:0,h=i>>2,c=(3&i)<<4|a>>4;let u=(15&a)<<2|l>>6,d=63&l;o||(d=64,n||(u=64)),s.push(r[h],r[c],r[u],r[d])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let s=0;s<e.length;s++){let i=e.charCodeAt(s);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&s+1<e.length&&56320==(64512&e.charCodeAt(s+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++s)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,s=0;for(;r<e.length;){const i=e[r++];if(i<128)t[s++]=String.fromCharCode(i);else if(i>191&&i<224){const n=e[r++];t[s++]=String.fromCharCode((31&i)<<6|63&n)}else if(i>239&&i<365){const n=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[s++]=String.fromCharCode(55296+(n>>10)),t[s++]=String.fromCharCode(56320+(1023&n))}else{const n=e[r++],a=e[r++];t[s++]=String.fromCharCode((15&i)<<12|(63&n)<<6|63&a)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],n=t<e.length?r[e.charAt(t)]:0;++t;const a=t<e.length?r[e.charAt(t)]:64;++t;const o=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==n||null==a||null==o)throw new DecodeBase64StringError;const l=i<<2|n>>4;if(s.push(l),64!==a){const e=n<<4&240|a>>2;if(s.push(e),64!==o){const e=a<<6&192|o;s.push(e)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Decode=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],n=i?function replaceTemplate(e,t){try{let r=0,s="";for(;r<e.length;){const i=e.indexOf("{$",r);if(-1===i){s+=e.substring(r);break}const n=e.indexOf("}",i+2);if(-1===n){s+=e.substring(r);break}const a=e.substring(i+2,n),o=t[a];s+=e.substring(r,i)+(null!=o?String(o):`<${a}?>`),r=n+1}return s}catch(t){return e}}(i,r):"Error",a=`${this.serviceName}: ${n} (${s}).`;return new FirebaseError(s,a,r)}}function jsonEval(e){return JSON.parse(e)}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var o,l;!function(e){e.LAZY="LAZY",e.EAGER="EAGER",e.EXPLICIT="EXPLICIT"}(o||(o={})),function(e){e.PUBLIC="PUBLIC",e.PRIVATE="PRIVATE",e.VERSION="VERSION"}(l||(l={}));var h=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};const getRetryDelay=e=>Math.min(1e3*2**e,3e4),c=[520,503],u=["GET","HEAD","OPTIONS"];function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function toPropertyKey(e){var t=function toPrimitive(e,t){if("object"!=_typeof(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=_typeof(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==_typeof(t)?t:t+""}function _defineProperty(e,t,r){return(t=toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function sleep(e,t){return new Promise((r=>{if(null==t?void 0:t.aborted)return void r();const s=setTimeout((()=>{null==t||t.removeEventListener("abort",onAbort),r()}),e);function onAbort(){clearTimeout(s),r()}null==t||t.addEventListener("abort",onAbort)}))}function shouldRetry(e,t,r,s){return!(!s||r>=3)&&(!!u.includes(e)&&!!c.includes(t))}async function fetchWithRetry(e,t,r,s){let i=0;for(;;){const l=_objectSpread2({},r.headers);let h;i>0&&(l["X-Retry-Count"]=String(i));try{h=await e(t,{method:r.method,headers:l,body:r.body,signal:r.signal})}catch(e){var n;if("AbortError"===(null==e?void 0:e.name)||"ABORT_ERR"===(null==e?void 0:e.code)||"TimeoutError"===(null==e?void 0:e.name)&&(null===(n=r.signal)||void 0===n?void 0:n.aborted))throw e;if(!u.includes(r.method))throw e;if(s&&i<3){const e=getRetryDelay(i);i++,await sleep(e,r.signal);continue}throw e}if(!shouldRetry(r.method,h.status,i,s))return h;{var a,o;const e=null!==(a=null===(o=h.headers)||void 0===o?void 0:o.get("Retry-After"))&&void 0!==a?a:null,t=null!==e?1e3*Math.max(0,parseInt(e,10)||0):getRetryDelay(i);await h.text(),i++,await sleep(t,r.signal)}}}var d=class{constructor(e){var t,r,s,i,n;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,this.shouldStripNulls=null!==(s=e.shouldStripNulls)&&void 0!==s&&s,this.urlLengthLimit=null!==(i=e.urlLengthLimit)&&void 0!==i?i:8e3,this.retryEnabled=null===(n=e.retry)||void 0===n||n,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):e&&"application/json"!==e||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{const e={};r.headers.forEach(((t,r)=>{e[r]=t}));const t=await fetchWithRetry(s,r.url.toString(),{method:r.method,headers:e,body:JSON.stringify(r.body,((e,t)=>"bigint"==typeof t?t.toString():t)),signal:r.signal},r.retryEnabled);return await r.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch((e=>{var t;let r="",s="",i="";const n=null==e?void 0:e.cause;if(n){var a,o,l,h;const t=null!==(a=null==n?void 0:n.message)&&void 0!==a?a:"",s=null!==(o=null==n?void 0:n.code)&&void 0!==o?o:"";r=`${null!==(l=null==e?void 0:e.name)&&void 0!==l?l:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(h=null==n?void 0:n.name)&&void 0!==h?h:"Error"}: ${t}`,s&&(r+=` (${s})`),(null==n?void 0:n.stack)&&(r+=`\n${n.stack}`)}else{var c;r=null!==(c=null==e?void 0:e.stack)&&void 0!==c?c:""}const u=this.url.toString().length;return"AbortError"===(null==e?void 0:e.name)||"ABORT_ERR"===(null==e?void 0:e.code)?(i="",s="Request was aborted (timeout or manual cancellation)",u>this.urlLengthLimit&&(s+=`. Note: Your request URL is ${u} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):"HeadersOverflowError"!==(null==n?void 0:n.name)&&"UND_ERR_HEADERS_OVERFLOW"!==(null==n?void 0:n.code)||(i="",s="HTTP headers exceeded server limits (typically 16KB)",u>this.urlLengthLimit&&(s+=`. Your request URL is ${u} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:s,code:i},data:null,count:null,status:0,statusText:""}}))),i.then(e,t)}async processResponse(e){var t=this;let r=null,s=null,i=null,n=e.status,a=e.statusText;if(e.ok){var o,l;if("HEAD"!==t.method){var c;const i=await e.text();if(""===i);else if("text/csv"===t.headers.get("Accept"))s=i;else if(t.headers.get("Accept")&&(null===(c=t.headers.get("Accept"))||void 0===c?void 0:c.includes("application/vnd.pgrst.plan+text")))s=i;else try{s=JSON.parse(i)}catch(e){if(r={message:i},s=null,t.shouldThrowOnError)throw new h({message:i,details:"",hint:"",code:""})}}const d=null===(o=t.headers.get("Prefer"))||void 0===o?void 0:o.match(/count=(exact|planned|estimated)/),p=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");if(d&&p&&p.length>1&&(i=parseInt(p[1])),t.isMaybeSingle&&Array.isArray(s))if(s.length>1){var u;if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,i=null,n=406,a="Not Acceptable",t.shouldThrowOnError)throw new h(_objectSpread2(_objectSpread2({},r),{},{hint:null!==(u=r.hint)&&void 0!==u?u:""}))}else s=1===s.length?s[0]:null}else{const i=await e.text();try{r=JSON.parse(i),Array.isArray(r)&&404===e.status&&(s=[],r=null,n=200,a="OK")}catch(t){404===e.status&&""===i?(n=204,a="No Content"):r={message:i}}if(r&&t.shouldThrowOnError)throw new h(r)}return{success:null===r,error:r,data:s,count:i,status:n,statusText:a}}returns(){return this}overrideTypes(){return this}},p=class extends d{throwOnError(){return super.throwOnError()}select(e){let t=!1;const r=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const g=new RegExp("[,()]");var f=class extends p{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map((e=>"string"==typeof e&&g.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map((e=>"string"==typeof e&&g.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");const n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).forEach((([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)})),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},m=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3,retry:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i,this.retry=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},i=r?"HEAD":"GET";let n=!1;const a=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e))).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new f({method:i,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));i.searchParams.set("columns",e.join(","))}}return new f({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;const{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));a.searchParams.set("columns",e.join(","))}}return new f({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;const{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new f({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new f({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function toOpenApiError(e,t){try{const t=JSON.parse(e);var r,s,i,n;if(t&&"object"==typeof t&&!Array.isArray(t))return new h({message:String(null!==(r=t.message)&&void 0!==r?r:e),details:null!==(s=t.details)&&void 0!==s?s:"",hint:null!==(i=t.hint)&&void 0!==i?i:"",code:null!==(n=t.code)&&void 0!==n?n:""})}catch(e){}return new h({message:e||t,details:"",hint:"",code:""})}function toTransportFailure(e,t,r){var s;const i=e;return{success:!1,error:new h({message:`${null!==(s=null==i?void 0:i.name)&&void 0!==s?s:"FetchError"}: ${null==i?void 0:i.message}`,details:"",hint:"",code:""}),data:null,count:null,status:t,statusText:r}}var E,v=class PostgrestClient{constructor(e,{headers:t={},schema:r,fetch:s,timeout:i,urlLengthLimit:n=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=n;const o=null!=s?s:globalThis.fetch;this.fetch=void 0!==i&&i>0?(e,t)=>{const r=new AbortController,s=setTimeout((()=>r.abort()),i),n=null==t?void 0:t.signal;if(n){if(n.aborted)return clearTimeout(s),o(e,t);const abortHandler=()=>{clearTimeout(s),r.abort()};return n.addEventListener("abort",abortHandler,{once:!0}),o(e,_objectSpread2(_objectSpread2({},t),{},{signal:r.signal})).finally((()=>{clearTimeout(s),n.removeEventListener("abort",abortHandler)}))}return o(e,_objectSpread2(_objectSpread2({},t),{},{signal:r.signal})).finally((()=>clearTimeout(s)))}:o,this.retry=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new m(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new PostgrestClient(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e,t=this;const r=new Headers(t.headers);r.set("Accept","application/openapi+json"),t.schemaName&&r.set("Accept-Profile",t.schemaName);const s={};r.forEach(((e,t)=>{s[t]=e}));const i=null!==(e=t.fetch)&&void 0!==e?e:globalThis.fetch;let n,a;try{var o;n=await fetchWithRetry(i,`${t.url}/`,{method:"GET",headers:s},null===(o=t.retry)||void 0===o||o)}catch(e){return toTransportFailure(e,0,"")}try{a=await n.text()}catch(e){return toTransportFailure(e,n.status,n.statusText)}if(n.ok)try{return{success:!0,error:null,data:JSON.parse(a),count:null,status:n.status,statusText:n.statusText}}catch(e){}return{success:!1,error:toOpenApiError(a,n.statusText),data:null,count:null,status:n.status,statusText:n.statusText}}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a;const o=new URL(`${this.url}/rpc/${e}`);let l;const _isObject=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(_isObject)),h=r&&Object.values(t).some(_isObject);h?(a="POST",l=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter((([e,t])=>void 0!==t)).map((([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`])).forEach((([e,t])=>{o.searchParams.append(e,t)}))):(a="POST",l=t);const c=new Headers(this.headers);return h?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new f({method:a,url:o,headers:c,schema:this.schemaName,body:l,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};!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"}(E||(E={}));const b={debug:E.DEBUG,verbose:E.VERBOSE,info:E.INFO,warn:E.WARN,error:E.ERROR,silent:E.SILENT},y=E.INFO,_={[E.DEBUG]:"log",[E.VERBOSE]:"log",[E.INFO]:"info",[E.WARN]:"warn",[E.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),i=_[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${s}] ${e.name}:`,...r)};const T="@firebase/sql",S="0.0.1-eap-sql.b903ef716",L=Object.freeze({OTHER:"other",ALREADY_INITIALIZED:"already-initialized",NOT_INITIALIZED:"not-initialized",NOT_SUPPORTED:"not-supported",INVALID_ARGUMENT:"invalid-argument",PARTIAL_ERROR:"partial-error",UNAUTHORIZED:"unauthorized"}),A=Object.freeze({SQL_POSTGREST:"sql-postgrest",SQL_PLATFORM:"sql-platform",SQL_CLIENT:"sql-client"});class FirebaseSqlError extends FirebaseError{constructor(e,t,r,s,i,n){super(e,t),this.name="FirebaseSqlError",this.code=e,this.category=r,this.details=s,this.hint=i,this.status=n,Object.setPrototypeOf(this,FirebaseSqlError.prototype)}toJSON(){const e={name:this.name,code:this.code,message:this.message,category:this.category};return void 0!==this.details&&(e.details=this.details),void 0!==this.hint&&(e.hint=this.hint),void 0!==this.status&&(e.status=this.status),e}toString(){const e=this.details?` (details: ${this.details})`:"",t=this.hint?` (hint: ${this.hint})`:"";return`${this.name}[code=${this.code}]: ${this.message}${e}${t}`.trim()}}function isPlainRecord(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function normalizeNonEmptyString(e){return"string"==typeof e&&e.length>0?e:void 0}function normalizeDetails(e){const t=normalizeNonEmptyString(e);return void 0!==t?t:"object"==typeof e&&null!==e?JSON.stringify(e):void 0}function normalizeHint(e){return normalizeNonEmptyString(e)}function mapPlatformStatusToCode(e,t){return 401===e||403===e||"UNAUTHENTICATED"===t||"PERMISSION_DENIED"===t?L.UNAUTHORIZED:400===e||"INVALID_ARGUMENT"===t?L.INVALID_ARGUMENT:501===e||"UNIMPLEMENTED"===t?L.NOT_SUPPORTED:L.OTHER}const mapPostgrestFailureToFirebaseSqlError=(e,t,r)=>{if(e instanceof FirebaseSqlError)return e;const s=t>0?t:void 0;if(0===t){const t=isPlainRecord(e)&&"string"==typeof e.message&&e.message.length>0||e instanceof Error&&e.message.length>0?e.message:"string"==typeof e&&e.length>0?e:"Network request failed.",r=isPlainRecord(e)?normalizeDetails(e.details):e instanceof Error?normalizeDetails(e.stack):void 0,s=isPlainRecord(e)?normalizeHint(e.hint):void 0;return new FirebaseSqlError(L.OTHER,t,A.SQL_CLIENT,r,s)}const i=Array.isArray(e)&&1===e.length?e[0]:e;if(isPlainRecord(i)&&isPlainRecord(i.error)){const e=i.error,n=mapPlatformStatusToCode(t,e.status),a="string"==typeof e.message&&e.message.length>0?e.message:r||`HTTP Error ${t}`;return new FirebaseSqlError(n,a,A.SQL_PLATFORM,normalizeDetails(e.details),normalizeHint(e.hint),s)}if(isPlainRecord(e)&&"string"==typeof e.error&&e.error.length>0){const r="string"==typeof e.error_description&&e.error_description.length>0?e.error_description:"string"==typeof e.message&&e.message.length>0?e.message:e.error;return new FirebaseSqlError(mapPlatformStatusToCode(t,e.status),r,A.SQL_PLATFORM,normalizeDetails(e.details),normalizeHint(e.hint),s)}if(isPlainRecord(e)&&"string"==typeof e.code&&e.code.length>0&&"string"!=typeof e.status){const t="string"==typeof e.message&&e.message.length>0?e.message:r||e.code;return new FirebaseSqlError(e.code,t,A.SQL_POSTGREST,normalizeDetails(e.details),normalizeHint(e.hint),s)}const n=isPlainRecord(e)&&"string"==typeof e.message&&e.message.length>0?e.message:"string"==typeof e&&e.length>0?e:r||`HTTP Error ${t}`,a=isPlainRecord(e)?normalizeDetails(e.details):Array.isArray(e)?normalizeDetails(e):void 0,o=isPlainRecord(e)?normalizeHint(e.hint):void 0;return new FirebaseSqlError(mapPlatformStatusToCode(t,isPlainRecord(e)?e.status:void 0),n,A.SQL_PLATFORM,a,o,s)};let I="";const w=Object.freeze({GOOG_API_CLIENT:"x-goog-api-client",CLIENT_VERSION:"x-client-version",FIREBASE_GMPID:"x-firebase-gmpid",FIREBASE_AUTH_TOKEN:"x-firebase-auth-token",FIREBASE_APPCHECK:"x-firebase-appcheck"}),P=["x-firebase-sqlconnect-affinity","x-goog-request-params","x-firebase-client","x-firebase-client-log-type","authorization"],O=new Set([...Object.values(w),...P]);function validateHeaderName(e){const t=String(e);if(O.has(t.trim().toLowerCase()))throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Cannot set protected header ${t}.`,A.SQL_CLIENT);return t}function resolveRequestHeaders(e,t,r,s){const i=new Headers;!function mergeHeadersInit(e,t){return t&&new Headers(t).forEach(((t,r)=>{e.set(r,t)})),e}(i,r?.headers);for(const e of P)i.delete(e);e?.accessToken?i.set(w.FIREBASE_AUTH_TOKEN,e.accessToken):i.delete(w.FIREBASE_AUTH_TOKEN),t?.token?i.set(w.FIREBASE_APPCHECK,t.token):i.delete(w.FIREBASE_APPCHECK),i.set(w.GOOG_API_CLIENT,function getGoogApiClientValue(){return"gl-js/ fire/"+I}()),i.set(w.CLIENT_VERSION,"web/"+I),void 0!==s?i.set(w.FIREBASE_GMPID,s):i.delete(w.FIREBASE_GMPID);const n={};return i.forEach(((e,t)=>{n[t]=e})),n}function copySqlServiceSettings(e){const t=Object.assign({},e);return void 0!==e.headers&&(t.headers=Object.assign({},e.headers)),t}function validateSqlServiceSettings(e){if(!e)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"SqlServiceSettings must be provided.",A.SQL_CLIENT);if(!e.serviceId)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"serviceId is required.",A.SQL_CLIENT);if(!e.location)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"location is required.",A.SQL_CLIENT);return function validatePort(e){if(void 0!==e&&("number"!=typeof e||!Number.isInteger(e)||e<1||e>65535))throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Port must be a valid integer between 1 and 65535 if provided. Received: ${String(e)}.`,A.SQL_CLIENT)}(e.port),function validateHeaders(e){if(e)for(const t of Object.keys(e))validateHeaderName(t)}(e.headers),function freezeSqlServiceSettings(e){const t=copySqlServiceSettings(e);return void 0!==t.headers&&Object.freeze(t.headers),Object.freeze(t)}(e)}const N="firebase-sql",R=new class Logger{constructor(e){this.name=e,this._logLevel=y,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in E))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?b[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,E.DEBUG,...e),this._logHandler(this,E.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,E.VERBOSE,...e),this._logHandler(this,E.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,E.INFO,...e),this._logHandler(this,E.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,E.WARN,...e),this._logHandler(this,E.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,E.ERROR,...e),this._logHandler(this,E.ERROR,...e)}}("@firebase/sql");function logDebug(e){R.debug(`Firebase SQL (${I}): ${e}`)}function logError(e){R.error(`Firebase SQL (${I}): ${e}`)}class AbstractTokenProvider{constructor(e,t){this.provider=e,this.serverAppToken=t,this.activeGetTokenPromise=void 0,this.activeForceRefreshPromise=void 0,this.resolveActiveGetTokenPromise=void 0,this.onInitUnsubscribe=void 0,this.activeListeners=[],this.queuedListeners=[],this.component=e?.getImmediate({optional:!0})??void 0,this.component||(this.onInitUnsubscribe=e?.onInit((e=>{this.component=e;const t=this.queuedListeners.length;for(let e=0;e<t;e++){const e=this.queuedListeners.shift();e&&this.addTokenChangeListener(e)}this.cancelOnInit()})))}getToken(e={forceRefresh:!1}){if(!this.activeForceRefreshPromise&&e.forceRefresh){const t=this.requestToken(e).then((e=>(this.resolveActiveGetTokenPromise?.(e),e))).finally((()=>{this.activeForceRefreshPromise===t&&(this.activeForceRefreshPromise=void 0)}));this.activeForceRefreshPromise=t}if(this.activeForceRefreshPromise)return this.activeForceRefreshPromise;if(!this.activeGetTokenPromise){const t=new Promise(((t,r)=>{this.resolveActiveGetTokenPromise=t,this.requestToken(e).then(t,r)})).finally((()=>{this.activeGetTokenPromise===t&&(this.activeGetTokenPromise=void 0,this.resolveActiveGetTokenPromise=void 0)}));this.activeGetTokenPromise=t}return this.activeGetTokenPromise}requestToken(e={forceRefresh:!1}){return this.component?this.fetchToken(this.component,e):this.provider?new Promise(((t,r)=>{setTimeout((()=>{this.component?this.requestToken(e).then(t,r):this.serverAppToken&&!e.forceRefresh?t(this.convertServerAppToken(this.serverAppToken)):t(null)}),0)})):this.serverAppToken&&!e.forceRefresh?Promise.resolve(this.convertServerAppToken(this.serverAppToken)):Promise.resolve(null)}addTokenChangeListener(e){if(this.component)try{this.activeListeners.push(e),this.addListener(this.component,e)}catch(e){this.activeListeners.pop(),logError(e instanceof Error?e.message:String(e))}else this.queuedListeners.push(e)}removeTokenChangeListener(e){if(this.component)try{removeFirstOccurrenceFromList(e,this.activeListeners),this.removeListener(this.component,e)}catch(e){logError(e instanceof Error?e.message:String(e))}removeFirstOccurrenceFromList(e,this.queuedListeners)}cancelOnInit(){this.onInitUnsubscribe?.(),this.onInitUnsubscribe=void 0,this.queuedListeners=[]}terminate(){this.cancelOnInit(),[...this.activeListeners].forEach((e=>this.removeTokenChangeListener(e)))}}function removeFirstOccurrenceFromList(e,t){const r=t.indexOf(e);return-1!==r&&t.splice(r,1),-1!==r}class AppCheckProvider extends AbstractTokenProvider{constructor(e,t){super(t,s(e)?e.settings.appCheckToken:void 0)}convertServerAppToken(e){return{token:e}}fetchToken(e,t={forceRefresh:!1}){return e.getToken(t.forceRefresh)}addListener(e,t){e.addTokenListener(t)}removeListener(e,t){e.removeTokenListener(t)}}class FirebaseAuthProvider extends AbstractTokenProvider{constructor(e,t){super(t,s(e)?e.settings.authIdToken:void 0)}getAuth(){return this.component}convertServerAppToken(e){return{accessToken:e}}fetchToken(e,t={forceRefresh:!1}){return e.getToken(t.forceRefresh).catch((e=>{if(e&&"object"==typeof e&&"code"in e&&"auth/token-not-initialized"===e.code)return logDebug("Got auth/token-not-initialized error. Treating as null token."),null;return logError("Error received when attempting to retrieve token: "+(e instanceof Error?e.message:String(e))),Promise.reject(e)}))}addListener(e,t){e.addAuthTokenListener(t)}removeListener(e,t){e.removeAuthTokenListener(t)}}function getAuthUidFromToken(e){if(!e)return null;try{if(3!==e.split(".").length)return null;const t=function(e){let t={},r={},s={},i="";try{const n=e.split(".");t=jsonEval(base64Decode(n[0])||""),r=jsonEval(base64Decode(n[1])||""),i=n[2],s=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:s,signature:i}}(e).claims,r=t?.sub;return"string"==typeof r&&r.length>0?r:null}catch{return null}}function toAbortError(e,t){const r=void 0!==t?t:e.reason;if(r instanceof Error&&("AbortError"===r.name||"TimeoutError"===r.name||r instanceof FirebaseSqlError))return r;const s=r instanceof Error?r.message:"string"==typeof r?r:"This operation was aborted",i=new Error(s);return i.name="AbortError",i}class FirebaseSqlTransport{constructor(e={}){this._isUsingEmulator=!1,this.settings=e.settings,this._appId=e.appId,this.authProvider=e.authTokenProvider,this.appCheckProvider=e.appCheckTokenProvider,this._terminationSignal=e.terminationSignal,this._state=e.state}async invokePostgrestOperation(e,t){if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);const r="string"==typeof e?e:e instanceof URL?e.toString():e.url,s=this._state?.active?.authTokenProvider??this.authProvider,i=this._state?.active?.appCheckTokenProvider??this.appCheckProvider,n=this._state?.active?.appId??this._appId,a=this._state?.terminationSignal??this._terminationSignal;if(a?.aborted)throw toAbortError(a);const o=void 0!==t?.signal?t.signal??void 0:"undefined"!=typeof Request&&e instanceof Request?e.signal:void 0,{signal:l,cleanup:h}=function composeSignals(e,t){if(!e)return{signal:t,cleanup:()=>{}};if(!t)return{signal:e,cleanup:()=>{}};if(e.aborted)return{signal:e,cleanup:()=>{}};if(t.aborted)return{signal:t,cleanup:()=>{}};if("function"==typeof AbortSignal.any)return{signal:AbortSignal.any([e,t]),cleanup:()=>{}};const r=new AbortController,onAbort1=()=>r.abort(e.reason),onAbort2=()=>r.abort(t.reason);return e.addEventListener("abort",onAbort1,{once:!0}),t.addEventListener("abort",onAbort2,{once:!0}),{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",onAbort1),t.removeEventListener("abort",onAbort2)}}}(o,a),c="undefined"!=typeof Request&&e instanceof Request;let u=t?.headers;if(c)if(void 0===t?.headers)u=e.headers;else{const r=new Headers(e.headers);new Headers(t.headers).forEach(((e,t)=>{r.set(t,e)})),u=r}const d={...c?{method:e.method,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity}:void 0,...t,headers:u};try{const a=function getFetch(){const e=globalThis.fetch;if(!e)throw new FirebaseSqlError(L.NOT_SUPPORTED,"No Fetch implementation detected in the current environment.",A.SQL_CLIENT);return e}();let o=null,h=null;try{const[e,t]=await Promise.all([s?s.getToken({forceRefresh:!1}):Promise.resolve(null),i?i.getToken({forceRefresh:!1}).catch((()=>null)):Promise.resolve(null)]);o=e,h=t}catch(e){if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l);const u=resolveRequestHeaders(o,h,d,n),p=this.buildRequestInit(d,u,r,l),g=getAuthUidFromToken(o?.accessToken),f=!("undefined"!=typeof ReadableStream&&(p.body instanceof ReadableStream||c&&void 0===t?.body&&e.bodyUsed));return await a(r,p).then((async e=>{if(this._state&&null===this._state.active)throw"function"==typeof e.body?.cancel&&await e.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);return 401===e.status&&o&&f&&s?this.refreshAuthAndRefetch(a,r,p,u,o,e,g,s):e})).catch((async e=>{if(this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}))}finally{h()}}buildRequestInit(e,t,r,s){const i=Object.assign({},e,{headers:t});return void 0!==s&&(i.signal=s),function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}(r)&&this._isUsingEmulator&&!i.credentials&&(i.credentials="include"),i}async refreshAuthAndRefetch(e,t,r,s,i,n,a,o){if(!o)return n;const l=r.signal;if(l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);let h=null;try{if(h=await o.getToken({forceRefresh:!1}).then((e=>e??null)).catch((()=>null)),l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);h?.accessToken&&h.accessToken!==i.accessToken||(h=await o.getToken({forceRefresh:!0}).then((e=>e??null)).catch((()=>null)))}catch(e){if("function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),this._state&&null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(l?.aborted)throw toAbortError(l,e);throw e}if(l?.aborted)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),toAbortError(l);if(this._state&&null===this._state.active)throw"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{})),new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT);if(h?.accessToken&&h.accessToken!==i.accessToken){const i=getAuthUidFromToken(h.accessToken);if(null!==a&&i!==a)return n;"function"==typeof n.body?.cancel&&await n.body.cancel().catch((()=>{}));const o=Object.assign({},s);o[w.FIREBASE_AUTH_TOKEN]=h.accessToken;return e(t,Object.assign({},r,{headers:o}))}return n}toFetch(e){return async(t,r)=>{try{return await this.invokePostgrestOperation(t,r)}catch(t){const r=this._state&&null===this._state.active?new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT):t instanceof FirebaseSqlError?t:null;if(e&&r){e.clientError=r;const t=new Error(r.message);throw t.name="AbortError",t}throw t}}}}const createBuilderFetch=(e,t)=>new FirebaseSqlTransport({state:e}).toFetch(t);function resolvePostgrestUrl(e,t){const r=!1===e.sslEnabled?"http":"https",s=e.host??"firebasedataconnect.googleapis.com",i=new URL(`${r}://${s}`);void 0!==e.port&&(i.port=String(e.port));const n=encodeURIComponent(t),a=encodeURIComponent(e.location),o=encodeURIComponent(e.serviceId);return i.pathname=`/v1/projects/${n}/locations/${a}/services/${o}/postgrest`,i.toString()}class FilterBuilderImpl{constructor(e,t,r,s){this._shouldThrowOnError=!1,this._delegate=e,this._state=t,this._createFetch=r,this._mapError=s}throwOnError(){return this._shouldThrowOnError=!0,this}stripNulls(){return this._delegate.stripNulls(),this}setHeader(e,t){const r=validateHeaderName(e);return this._delegate.setHeader(r,t),this}retry(e){return this._delegate.retry(e),this}returns(){return this._delegate.returns(),this}overrideTypes(){return this._delegate.overrideTypes(),this}select(e){return this._delegate.select(e),this}order(e,t){return this._delegate.order(e,t),this}limit(e,t){return this._delegate.limit(e,t),this}range(e,t,r){return this._delegate.range(e,t,r),this}abortSignal(e){return this._delegate.abortSignal(e),this}single(){return this._delegate.single(),this}maybeSingle(){return this._delegate.maybeSingle(),this}csv(){return this._delegate.csv(),this}geojson(){return this._delegate.geojson(),this}explain(e){return this._delegate.explain(e),this}rollback(){return this._delegate.rollback(),this}maxAffected(e){return this._delegate.maxAffected(e),this}eq(e,t){return this._delegate.eq(e,t),this}neq(e,t){return this._delegate.neq(e,t),this}gt(e,t){return this._delegate.gt(e,t),this}gte(e,t){return this._delegate.gte(e,t),this}lt(e,t){return this._delegate.lt(e,t),this}lte(e,t){return this._delegate.lte(e,t),this}like(e,t){return this._delegate.like(e,t),this}likeAllOf(e,t){return this._delegate.likeAllOf(e,t),this}likeAnyOf(e,t){return this._delegate.likeAnyOf(e,t),this}ilike(e,t){return this._delegate.ilike(e,t),this}ilikeAllOf(e,t){return this._delegate.ilikeAllOf(e,t),this}ilikeAnyOf(e,t){return this._delegate.ilikeAnyOf(e,t),this}regexMatch(e,t){return this._delegate.regexMatch(e,t),this}regexIMatch(e,t){return this._delegate.regexIMatch(e,t),this}is(e,t){return this._delegate.is(e,t),this}isDistinct(e,t){return this._delegate.isDistinct(e,t),this}in(e,t){return this._delegate.in(e,t),this}notIn(e,t){return this._delegate.notIn(e,t),this}contains(e,t){return this._delegate.contains(e,t),this}containedBy(e,t){return this._delegate.containedBy(e,t),this}rangeGt(e,t){return this._delegate.rangeGt(e,t),this}rangeGte(e,t){return this._delegate.rangeGte(e,t),this}rangeLt(e,t){return this._delegate.rangeLt(e,t),this}rangeLte(e,t){return this._delegate.rangeLte(e,t),this}rangeAdjacent(e,t){return this._delegate.rangeAdjacent(e,t),this}overlaps(e,t){return this._delegate.overlaps(e,t),this}textSearch(e,t,r){return this._delegate.textSearch(e,t,r),this}match(e){return this._delegate.match(e),this}not(e,t,r){return this._delegate.not(e,t,r),this}or(e,t){return this._delegate.or(e,t),this}filter(e,t,r){return this._delegate.filter(e,t,r),this}then(e,t){const r=this._execute();return e||t?r.then(e,t):r}_fail(e,t,r){if(this._shouldThrowOnError)throw e;return{success:!1,error:e,data:null,count:null,status:t,statusText:r}}_execute(){const e={clientError:null};Reflect.set(this._delegate,"fetch",this._createFetch(this._state,e));try{return this._delegate.then((t=>{if(null===this._state.active)return this._fail(new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT),0,"");if(null!==e.clientError)return this._fail(e.clientError,0,"");if(!t.success||null!==t.error||t.status<200||t.status>=300)return this._fail(this._mapError(t.error,t.status,t.statusText),t.status,t.statusText);return{success:!0,error:null,data:t.data,count:t.count,status:t.status,statusText:t.statusText}}))}finally{Reflect.set(this._delegate,"fetch",void 0)}}}class QueryBuilderImpl{constructor(e,t,r,s){this._delegate=e,this._state=t,this._createFetch=r,this._mapError=s}_wrap(e){return new FilterBuilderImpl(e,this._state,this._createFetch,this._mapError)}select(e,t){return this._wrap(this._delegate.select(e,t))}insert(e,t){return this._wrap(this._delegate.insert(e,t))}upsert(e,t){return this._wrap(this._delegate.upsert(e,t))}update(e,t){return this._wrap(this._delegate.update(e,t))}delete(e){return this._wrap(this._delegate.delete(e))}}class FirebaseSql{constructor(e,t,r,s,i){this.app=e,this.settings=t,this._instanceIdentifier=r,this._terminationController=new AbortController,this._postgrestUrl=resolvePostgrestUrl(this.settings,e.options.projectId),this._state={active:{appId:e.options.appId,authTokenProvider:new FirebaseAuthProvider(e,s),appCheckTokenProvider:new AppCheckProvider(e,i)},terminationSignal:this._terminationController.signal},this._postgrestClient=new v(this._postgrestUrl,{headers:this.settings.headers,schema:this.settings.schemaName})}_delete(){if(null!==this._state.active){const e=this._state.active;this._state.active=null,this._terminationController.abort(new FirebaseSqlError(L.NOT_INITIALIZED,"The Firebase SQL client has been terminated.",A.SQL_CLIENT)),e.appCheckTokenProvider.terminate(),e.authTokenProvider.terminate(),r(this.app,N,this._instanceIdentifier)}return Promise.resolve()}_encodeResourceSegment(e,t){if("."===e||".."===e)throw new FirebaseSqlError(L.INVALID_ARGUMENT,`Invalid resource name "${e}".`,A.SQL_CLIENT);return"string"!=typeof e||0===e.length||t&&""===e.trim()?e:encodeURIComponent(e)}from(e){if(null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT);const t=this._postgrestClient.from(this._encodeResourceSegment(e,!0));return new QueryBuilderImpl(t,this._state,createBuilderFetch,mapPostgrestFailureToFirebaseSqlError)}rpc(e,t,r){if(null===this._state.active)throw new FirebaseSqlError(L.NOT_INITIALIZED,"FirebaseSql instance has been terminated.",A.SQL_CLIENT);const s=this._postgrestClient.rpc(this._encodeResourceSegment(e,!1),t,r);return new FilterBuilderImpl(s,this._state,createBuilderFetch,mapPostgrestFailureToFirebaseSqlError)}}function getSql(e,t){let r,s;if(void 0===t)r=i(),s=e;else{if(void 0===e)r=i();else{if(!e||"object"!=typeof e||!("options"in e))throw new FirebaseSqlError(L.INVALID_ARGUMENT,"First argument passed to getSql() must be a FirebaseApp or SqlServiceSettings instance.",A.SQL_CLIENT);r=e}s=t}const n=validateSqlServiceSettings(s);if("string"!=typeof r.options?.projectId||0===r.options.projectId.length)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?",A.SQL_CLIENT);const a=getInstanceIdentifier(n,r.options.projectId),o=_getProvider(r,N);return o.isInitialized(a)?(logDebug("Re-using cached instance (NOTE: custom headers set on the original FSQL client are RE-USED when that client is re-used from the instance cache. Creating multiple FSQL clients with the same settings and app, but different headers, is NOT supported. Instead, use .setHeaders() while building an operation chain to set custom headers for that specific operation.)"),o.getImmediate({identifier:a})):(logDebug("Creating new Firebase SQL instance"),o.initialize({instanceIdentifier:a,options:n}))}function terminate(e){return e._delete()}function getInstanceIdentifier(e,t){const r=resolvePostgrestUrl(e,t);return JSON.stringify({resolvedUrl:r,schemaName:e.schemaName})}!function registerSql(r){!function setSDKVersion(e){I=e}(n),e(new Component(N,((e,{instanceIdentifier:t,options:r})=>{const s=r,i=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),a=e.getProvider("app-check-internal");if("string"!=typeof i.options?.projectId||0===i.options.projectId.length)throw new FirebaseSqlError(L.INVALID_ARGUMENT,"Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?",A.SQL_CLIENT);const o=t??getInstanceIdentifier(s,i.options.projectId);return new FirebaseSql(i,s,o,n,a)}),"PUBLIC").setMultipleInstances(!0)),t(T,S,r),t(T,S,"esm2020")}();export{L as Code,FirebaseSql,FirebaseSqlError,A as FirebaseSqlErrorCategory,copySqlServiceSettings,getSql,terminate};
2
2
 
3
3
  //# sourceMappingURL=firebase-sql.js.map