1var xu={};const el=function(r){const t=[];let e=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128)}return t},wf=function(r){const t=[];let e=0,n=0;for(;e<r.length;){const s=r[e++];if(s<128)t[n++]=String.fromCharCode(s);else if(s>191&&s<224){const i=r[e++];t[n++]=String.fromCharCode((s&31)<<6|i&63)}else if(s>239&&s<365){const i=r[e++],a=r[e++],u=r[e++],c=((s&7)<<18|(i&63)<<12|(a&63)<<6|u&63)-65536;t[n++]=String.fromCharCode(55296+(c>>10)),t[n++]=String.fromCharCode(56320+(c&1023))}else{const i=r[e++],a=r[e++];t[n++]=String.fromCharCode((s&15)<<12|(i&63)<<6|a&63)}}return t.join("")},nl={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:typeof atob=="function",encodeByteArray(r,t){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();const e=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let s=0;s<r.length;s+=3){const i=r[s],a=s+1<r.length,u=a?r[s+1]:0,c=s+2<r.length,h=c?r[s+2]:0,f=i>>2,g=(i&3)<<4|u>>4;let _=(u&15)<<2|h>>6,R=h&63;c||(R=64,a||(_=64)),n.push(e[f],e[g],e[_],e[R])}return n.join("")},encodeString(r,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(r):this.encodeByteArray(el(r),t)},decodeString(r,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(r):wf(this.decodeStringToByteArray(r,t))},decodeStringToByteArray(r,t){this.init_();const e=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let s=0;s<r.length;){const i=e[r.charAt(s++)],u=s<r.length?e[r.charAt(s)]:0;++s;const h=s<r.length?e[r.charAt(s)]:64;++s;const g=s<r.length?e[r.charAt(s)]:64;if(++s,i==null||u==null||h==null||g==null)throw new Af;const _=i<<2|u>>4;if(n.push(_),h!==64){const R=u<<4&240|h>>2;if(n.push(R),g!==64){const C=h<<6&192|g;n.push(C)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let r=0;r<this.ENCODED_VALS.length;r++)this.byteToCharMap_[r]=this.ENCODED_VALS.charAt(r),this.charToByteMap_[this.byteToCharMap_[r]]=r,this.byteToCharMapWebSafe_[r]=this.ENCODED_VALS_WEBSAFE.charAt(r),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[r]]=r,r>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(r)]=r,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(r)]=r)}}};class Af extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const Rf=function(r){const t=el(r);return nl.encodeByteArray(t,!0)},Fs=function(r){return Rf(r).replace(/\./g,"")},bf=function(r){try{return nl.decodeString(r,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function Pf(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}const Sf=()=>Pf().__FIREBASE_DEFAULTS__,Vf=()=>{if(typeof process>"u"||typeof xu>"u")return;const r=xu.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},Cf=()=>{if(typeof document>"u")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const t=r&&bf(r[1]);return t&&JSON.parse(t)},Vo=()=>{try{return Sf()||Vf()||Cf()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},Df=r=>{var t,e;return(e=(t=Vo())===null||t===void 0?void 0:t.emulatorHosts)===null||e===void 0?void 0:e[r]},xf=r=>{const t=Df(r);if(!t)return;const e=t.lastIndexOf(":");if(e<=0||e+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const n=parseInt(t.substring(e+1),10);return t[0]==="["?[t.substring(1,e-1),n]:[t.substring(0,e),n]},rl=()=>{var r;return(r=Vo())===null||r===void 0?void 0:r.config};class Nf{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}wrapCallback(t){return(e,n)=>{e?this.reject(e):this.resolve(n),typeof t=="function"&&(this.promise.catch(()=>{}),t.length===1?t(e):t(e,n))}}}function kf(r,t){if(r.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const e={alg:"none",type:"JWT"},n=t||"demo-project",s=r.iat||0,i=r.sub||r.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const a=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:s,exp:s+3600,auth_time:s,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},r);return[Fs(JSON.stringify(e)),Fs(JSON.stringify(a)),""].join(".")}function Ls(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Mf(){var r;const t=(r=Vo())===null||r===void 0?void 0:r.forceEnvironment;if(t==="node")return!0;
1if(t==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function FI(){const r=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof r=="object"&&r.id!==void 0}function sl(){return!Mf()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function il(){try{return typeof indexedDB=="object"}catch{return!1}}function Of(){return new Promise((r,t)=>{try{let e=!0;const n="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(n);s.onsuccess=()=>{s.result.close(),e||self.indexedDB.deleteDatabase(n),r(!0)},s.onupgradeneeded=()=>{e=!1},s.onerror=()=>{var i;t(((i=s.error)===null||i===void 0?void 0:i.message)||"")}}catch(e){t(e)}})}function LI(){return!(typeof navigator>"u"||!navigator.cookieEnabled)}const Ff="FirebaseError";class Ln extends Error{constructor(t,e,n){super(e),this.code=t,this.customData=n,this.name=Ff,Object.setPrototypeOf(this,Ln.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ol.prototype.create)}}class ol{constructor(t,e,n){this.service=t,this.serviceName=e,this.errors=n}create(t,...e){const n=e[0]||{},s=`${this.service}/${t}`,i=this.errors[t],a=i?Lf(i,n):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new Ln(s,u,n)}}function Lf(r,t){return r.replace(Bf,(e,n)=>{const s=t[n];return s!=null?String(s):`<${n}?>`})}const Bf=/\{\$([^}]+)}/g;function He(r,t){if(r===t)return!0;const e=Object.keys(r),n=Object.keys(t);for(const s of e){if(!n.includes(s))return!1;const i=r[s],a=t[s];if(Nu(i)&&Nu(a)){if(!He(i,a))return!1}else if(i!==a)return!1}for(const s of n)if(!e.includes(s))return!1;return!0}function Nu(r){return r!==null&&typeof r=="object"}const Uf=1e3,qf=2,jf=14400*1e3,zf=.5;function BI(r,t=Uf,e=qf){const n=t*Math.pow(e,r),s=Math.round(zf*n*(Math.random()-.5)*2);return Math.min(jf,n+s)}function vt(r){return r&&r._delegate?r._delegate:r}class Cr{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}const qe="[DEFAULT]";class Gf{constructor(t,e){this.name=t,this.container=e,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(t){const e=this.normalizeInstanceIdentifier(t);if(!this.instancesDeferred.has(e)){const n=new Nf;if(this.instancesDeferred.set(e,n),this.isInitialized(e)||this.shouldAutoInitialize())try{const s=this.getOrInitializeService({instanceIdentifier:e});s&&n.resolve(s)}catch{}}return this.instancesDeferred.get(e).promise}getImmediate(t){var e;const n=this.normalizeInstanceIdentifier(t?.identifier),s=(e=t?.optional)!==null&&e!==void 0?e:!1;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(s)return null;throw i}else{if(s)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,!!this.shouldAutoInitialize()){if($f(t))try{this.getOrInitializeService({instanceIdentifier:qe})}catch{}for(const[e,n]of this.instancesDeferred.entries()){const s=this.normalizeInstanceIdentifier(e);try{const i=this.getOrInitializeService({instanceIdentifier:s});n.resolve(i)}catch{}}}}clearInstance(t=qe){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...t.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return this.component!=null}isInitialized(t=qe){return this.instances.has(t)}getOptions(t=qe){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,n=this.normalizeInstanceIdentifier(t.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:n,options:e});for(const[i,a]of this.instancesDeferred.entries()){const u=this.normalizeInstanceIdentifier(i);n===u&&a.resolve(s)}return s}onInit(t,e){var n;const s=this.normalizeInstanceIdentifier(e),i=(n=this.onInitCallbacks.get(s))!==null&&n!==void 0?n:new Set;i.add(t),this.onInitCallbacks.set(s,i);const a=this.instances.get(s);return a&&t(a,s),()=>{i.delete(t)}}invokeOnInitCallbacks(t,e){const n=this.onInitCallbacks.get(e);if(n)for(const s of n)try{s(t,e)}catch{}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let n=this.instances.get(t);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:Kf(t),options:e}),this.instances.set(t,n),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(n,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,n)}catch{}return n||null}normalizeInstanceIdentifier(t=qe){return this.component?this.component.multipleInstances?t:qe:t}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function Kf(r){return r===qe?void 0:r}function $f(r){return r.instantiationMode==="EAGER"}class Qf{constructor(t){this.name=t,this.providers=new Map}addComponent(t){const e=this.getProvider(t.name);if(e.isComponentSet())throw new Error(`Component ${t.name} has already been registered with ${this.name}`);e.setComponent(t)}addOrOverwriteComponent(t){this.getProvider(t.name).isComponentSet()&&this.providers.delete(t.name),this.addComponent(t)}getProvider(t){if(this.providers.has(t))return this.providers.get(t);const e=new Gf(t,this);return this.providers.set(t,e),e}getProviders(){return Array.from(this.providers.values())}}var Y;(function(r){r[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT"})(Y||(Y={}));const Wf={debug:Y.DEBUG,verbose:Y.VERBOSE,info:Y.INFO,warn:Y.WARN,error:Y.ERROR,silent:Y.SILENT},Hf=Y.INFO,Jf={[Y.DEBUG]:"log",[Y.VERBOSE]:"log",[Y.INFO]:"info",[Y.WARN]:"warn",[Y.ERROR]:"error"},Yf=(r,t,...e)=>{if(t<r.logLevel)return;const n=new Date().toISOString(),s=Jf[t];if(s)console[s](`[${n}] ${r.name}:`,...e);
1else throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`)};class al{constructor(t){this.name=t,this._logLevel=Hf,this._logHandler=Yf,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(t){if(!(t in Y))throw new TypeError(`Invalid value "${t}" assigned to \`logLevel\``);this._logLevel=t}setLogLevel(t){this._logLevel=typeof t=="string"?Wf[t]:t}get logHandler(){return this._logHandler}set logHandler(t){if(typeof t!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t}get userLogHandler(){return this._userLogHandler}set userLogHandler(t){this._userLogHandler=t}debug(...t){this._userLogHandler&&this._userLogHandler(this,Y.DEBUG,...t),this._logHandler(this,Y.DEBUG,...t)}log(...t){this._userLogHandler&&this._userLogHandler(this,Y.VERBOSE,...t),this._logHandler(this,Y.VERBOSE,...t)}info(...t){this._userLogHandler&&this._userLogHandler(this,Y.INFO,...t),this._logHandler(this,Y.INFO,...t)}warn(...t){this._userLogHandler&&this._userLogHandler(this,Y.WARN,...t),this._logHandler(this,Y.WARN,...t)}error(...t){this._userLogHandler&&this._userLogHandler(this,Y.ERROR,...t),this._logHandler(this,Y.ERROR,...t)}}const Xf=(r,t)=>t.some(e=>r instanceof e);let ku,Mu;function Zf(){return ku||(ku=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function tm(){return Mu||(Mu=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const ul=new WeakMap,ro=new WeakMap,cl=new WeakMap,Qi=new WeakMap,Co=new WeakMap;function em(r){const t=new Promise((e,n)=>{const s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",a)},i=()=>{e(ye(r.result)),s()},a=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",a)});return t.then(e=>{e instanceof IDBCursor&&ul.set(e,r)}).catch(()=>{}),Co.set(t,r),t}function nm(r){if(ro.has(r))return;const t=new Promise((e,n)=>{const s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",a),r.removeEventListener("abort",a)},i=()=>{e(),s()},a=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",a),r.addEventListener("abort",a)});ro.set(r,t)}let so={get(r,t,e){if(r instanceof IDBTransaction){if(t==="done")return ro.get(r);if(t==="objectStoreNames")return r.objectStoreNames||cl.get(r);if(t==="store")return e.objectStoreNames[1]?void 0:e.objectStore(e.objectStoreNames[0])}return ye(r[t])},set(r,t,e){return r[t]=e,!0},has(r,t){return r instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in r}};function rm(r){so=r(so)}function sm(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...e){const n=r.call(Wi(this),t,...e);return cl.set(n,t.sort?t.sort():[t]),ye(n)}:tm().includes(r)?function(...t){return r.apply(Wi(this),t),ye(ul.get(this))}:function(...t){return ye(r.apply(Wi(this),t))}}function im(r){return typeof r=="function"?sm(r):(r instanceof IDBTransaction&&nm(r),Xf(r,Zf())?new Proxy(r,so):r)}function ye(r){if(r instanceof IDBRequest)return em(r);if(Qi.has(r))return Qi.get(r);const t=im(r);return t!==r&&(Qi.set(r,t),Co.set(t,r)),t}const Wi=r=>Co.get(r);function om(r,t,{blocked:e,upgrade:n,blocking:s,terminated:i}={}){const a=indexedDB.open(r,t),u=ye(a);return n&&a.addEventListener("upgradeneeded",c=>{n(ye(a.result),c.oldVersion,c.newVersion,ye(a.transaction),c)}),e&&a.addEventListener("blocked",c=>e(c.oldVersion,c.newVersion,c)),u.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",h=>s(h.oldVersion,h.newVersion,h))}).catch(()=>{}),u}const am=["get","getKey","getAll","getAllKeys","count"],um=["put","add","delete","clear"],Hi=new Map;function Ou(r,t){if(!(r instanceof IDBDatabase&&!(t in r)&&typeof t=="string"))return;if(Hi.get(t))return Hi.get(t);const e=t.replace(/FromIndex$/,""),n=t!==e,s=um.includes(e);if(!(e in(n?IDBIndex:IDBObjectStore).prototype)||!(s||am.includes(e)))return;const i=async function(a,...u){const c=this.transaction(a,s?"readwrite":"readonly");let h=c.store;
1return n&&(h=h.index(u.shift())),(await Promise.all([h[e](...u),s&&c.done]))[0]};return Hi.set(t,i),i}rm(r=>({...r,get:(t,e,n)=>Ou(t,e)||r.get(t,e,n),has:(t,e)=>!!Ou(t,e)||r.has(t,e)}));class cm{constructor(t){this.container=t}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(lm(e)){const n=e.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(e=>e).join(" ")}}function lm(r){const t=r.getComponent();return t?.type==="VERSION"}const io="@firebase/app",Fu="0.10.13";const te=new al("@firebase/app"),hm="@firebase/app-compat",dm="@firebase/analytics-compat",fm="@firebase/analytics",mm="@firebase/app-check-compat",gm="@firebase/app-check",pm="@firebase/auth",_m="@firebase/auth-compat",ym="@firebase/database",Im="@firebase/data-connect",Em="@firebase/database-compat",Tm="@firebase/functions",vm="@firebase/functions-compat",wm="@firebase/installations",Am="@firebase/installations-compat",Rm="@firebase/messaging",bm="@firebase/messaging-compat",Pm="@firebase/performance",Sm="@firebase/performance-compat",Vm="@firebase/remote-config",Cm="@firebase/remote-config-compat",Dm="@firebase/storage",xm="@firebase/storage-compat",Nm="@firebase/firestore",km="@firebase/vertexai-preview",Mm="@firebase/firestore-compat",Om="firebase",Fm="10.14.1";const Bs="[DEFAULT]",Lm={[io]:"fire-core",[hm]:"fire-core-compat",[fm]:"fire-analytics",[dm]:"fire-analytics-compat",[gm]:"fire-app-check",[mm]:"fire-app-check-compat",[pm]:"fire-auth",[_m]:"fire-auth-compat",[ym]:"fire-rtdb",[Im]:"fire-data-connect",[Em]:"fire-rtdb-compat",[Tm]:"fire-fn",[vm]:"fire-fn-compat",[wm]:"fire-iid",[Am]:"fire-iid-compat",[Rm]:"fire-fcm",[bm]:"fire-fcm-compat",[Pm]:"fire-perf",[Sm]:"fire-perf-compat",[Vm]:"fire-rc",[Cm]:"fire-rc-compat",[Dm]:"fire-gcs",[xm]:"fire-gcs-compat",[Nm]:"fire-fst",[Mm]:"fire-fst-compat",[km]:"fire-vertex","fire-js":"fire-js",[Om]:"fire-js-all"};const Us=new Map,Bm=new Map,oo=new Map;function Lu(r,t){try{r.container.addComponent(t)}catch(e){te.debug(`Component ${t.name} failed to register with FirebaseApp ${r.name}`,e)}}function qs(r){const t=r.name;if(oo.has(t))return te.debug(`There were multiple attempts to register component ${t}.`),!1;oo.set(t,r);for(const e of Us.values())Lu(e,r);for(const e of Bm.values())Lu(e,r);return!0}function Do(r,t){const e=r.container.getProvider("heartbeat").getImmediate({optional:!0});return e&&e.triggerHeartbeat(),r.container.getProvider(t)}function Um(r,t,e=Bs){Do(r,t).clearInstance(e)}const qm={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invali
1d-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Ie=new ol("app","Firebase",qm);class jm{constructor(t,e,n){this._isDeleted=!1,this._options=Object.assign({},t),this._config=Object.assign({},e),this._name=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new Cr("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(t){this.checkDestroyed(),this._automaticDataCollectionEnabled=t}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(t){this._isDeleted=t}checkDestroyed(){if(this.isDeleted)throw Ie.create("app-deleted",{appName:this._name})}}const zm=Fm;function Gm(r,t={}){let e=r;typeof t!="object"&&(t={name:t});const n=Object.assign({name:Bs,automaticDataCollectionEnabled:!1},t),s=n.name;if(typeof s!="string"||!s)throw Ie.create("bad-app-name",{appName:String(s)});if(e||(e=rl()),!e)throw Ie.create("no-options");const i=Us.get(s);if(i){if(He(e,i.options)&&He(n,i.config))return i;throw Ie.create("duplicate-app",{appName:s})}const a=new Qf(s);for(const c of oo.values())a.addComponent(c);const u=new jm(e,n,a);return Us.set(s,u),u}function Km(r=Bs){const t=Us.get(r);if(!t&&r===Bs&&rl())return Gm();if(!t)throw Ie.create("no-app",{appName:r});return t}function wr(r,t,e){var n;let s=(n=Lm[r])!==null&&n!==void 0?n:r;e&&(s+=`-${e}`);const i=s.match(/\s|\//),a=t.match(/\s|\//);if(i||a){const u=[`Unable to register library "${s}" with version "${t}":`];i&&u.push(`library name "${s}" contains illegal characters (whitespace or "/")`),i&&a&&u.push("and"),a&&u.push(`version name "${t}" contains illegal characters (whitespace or "/")`),te.warn(u.join(" "));return}qs(new Cr(`${s}-version`,()=>({library:s,version:t}),"VERSION"))}const $m="firebase-heartbeat-database",Qm=1,Dr="firebase-heartbeat-store";let Ji=null;function ll(){return Ji||(Ji=om($m,Qm,{upgrade:(r,t)=>{switch(t){case 0:try{r.createObjectStore(Dr)}catch(e){console.warn(e)}}}}).catch(r=>{throw Ie.create("idb-open",{originalErrorMessage:r.message})})),Ji}async function Wm(r){try{const e=(await ll()).transaction(Dr),n=await e.objectStore(Dr).get(hl(r));return await e.done,n}catch(t){if(t instanceof Ln)te.warn(t.message);else{const e=Ie.create("idb-get",{originalErrorMessage:t?.message});te.warn(e.message)}}}async function Bu(r,t){try{const n=(await ll()).transaction(Dr,"readwrite");await n.objectStore(Dr).put(t,hl(r)),await n.done}catch(e){if(e instanceof Ln)te.warn(e.message);else{const n=Ie.create("idb-set",{originalErrorMessage:e?.message});te.warn(n.message)}}}function hl(r){return`${r.name}!${r.options.appId}`}const Hm=1024,Jm=720*60*60*1e3;class Ym{constructor(t){this.container=t,this._heartbeatsCache=null;const e=this.container.getProvider("app").getImmediate();this._storage=new Zm(e),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){var t,e;try{const s=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=Uu();return((t=this._heartbeatsCache)===null||t===void 0?void 0:t.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(a=>a.date===i)?void 0:(this._heartbeatsCache.heartbeats.push({date:i,agent:s}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(a=>{const u=new Date(a.date).valueOf();return Date.now()-u<=Jm}),this._storage.overwrite(this._heartbeatsCache))}catch(n){te.warn(n)}}async getHeartbeatsHeader(){var t;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((t=this._heartbeatsCache)===null||t===void 0?void 0:t.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const e=Uu(),{heartbeatsToSend:n,unsentEntries:s}=Xm(this._heartbeatsCache.heartbeats),i=Fs(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,s.length>0?(this._heartbeatsCache.heartbeats=s,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return te.warn(e),""}}}function Uu(){return new Date().toISOString().substring(0,10)}function Xm(r,t=Hm){const e=[];let n=r.slice();for(const s of r){const i=e.find(a=>a.agent===s.agent);if(i){if(i.dates.push(s.date),qu(e)>t){i.dates.pop();break}}else if(e.push({agent:s.agent,dates:[s.date]}),qu(e)>t){e.pop();break}n=n.slice(1)}return{heartbeatsToSend:e,unsentEntries:n}}class Zm{constructor(t){this.app=t,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return il()?Of().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const e=await Wm(this.app);return e?.heartbeats?e:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(t){var e;if(await this._canUseIndexedDBPromise){const s=await this.read();return Bu(this.app,{lastSentHeartbeatDate:(e=t.lastSentHeartbeatDate)!==null&&e!==void 0?e:s.lastSentHeartbeatDate,heartbeats:t.heartbeats})}else return}async add(t){var e;if(await this._canUseIndexedDBPromise){const s=await this.read();return Bu(this.app,{lastSentHeartbeatDate:(e=t.lastSentHeartbeatDate)!==null&&e!==void 0?e:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...t.heartbeats]})}else return}}function qu(r){return Fs(JSON.stringify({version:2,heartbeats:r})).length}function tg(r){qs(new Cr("platform-logger",t=>new cm(t),"PRIVATE")),qs(new Cr("heartbeat",t=>new Ym(t),"PRIVATE")),wr(io,Fu,r),wr(io,Fu,"esm2017"),wr("fire-js","")}tg("");var ju=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var Qe,dl;(function(){var r;function t(E,p){function I(){}I.prototype=p.prototype,E.D=p.prototype,E.prototype=new I,E.prototype.constructor=E,E.C=function(T,v,b){for(var y=Array(arguments.length-2),Jt=2;Jt<arguments.length;Jt++)y[Jt-2]=arguments[Jt];return p.prototype[v].apply(T,y)}}function e(){this.blockSize=-1}function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}t(n,e),n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(E,p,I){I||(I=0);var T=Array(16);if(typeof p=="string")for(var v=0;16>v;
vendor: 51,867 bytes, lines 1-9
1++v)T[v]=p.charCodeAt(I++)|p.charCodeAt(I++)<<8|p.charCodeAt(I++)<<16|p.charCodeAt(I++)<<24;else for(v=0;16>v;++v)T[v]=p[I++]|p[I++]<<8|p[I++]<<16|p[I++]<<24;p=E.g[0],I=E.g[1],v=E.g[2];var b=E.g[3],y=p+(b^I&(v^b))+T[0]+3614090360&4294967295;p=I+(y<<7&4294967295|y>>>25),y=b+(v^p&(I^v))+T[1]+3905402710&4294967295,b=p+(y<<12&4294967295|y>>>20),y=v+(I^b&(p^I))+T[2]+606105819&4294967295,v=b+(y<<17&4294967295|y>>>15),y=I+(p^v&(b^p))+T[3]+3250441966&4294967295,I=v+(y<<22&4294967295|y>>>10),y=p+(b^I&(v^b))+T[4]+4118548399&4294967295,p=I+(y<<7&4294967295|y>>>25),y=b+(v^p&(I^v))+T[5]+1200080426&4294967295,b=p+(y<<12&4294967295|y>>>20),y=v+(I^b&(p^I))+T[6]+2821735955&4294967295,v=b+(y<<17&4294967295|y>>>15),y=I+(p^v&(b^p))+T[7]+4249261313&4294967295,I=v+(y<<22&4294967295|y>>>10),y=p+(b^I&(v^b))+T[8]+1770035416&4294967295,p=I+(y<<7&4294967295|y>>>25),y=b+(v^p&(I^v))+T[9]+2336552879&4294967295,b=p+(y<<12&4294967295|y>>>20),y=v+(I^b&(p^I))+T[10]+4294925233&4294967295,v=b+(y<<17&4294967295|y>>>15),y=I+(p^v&(b^p))+T[11]+2304563134&4294967295,I=v+(y<<22&4294967295|y>>>10),y=p+(b^I&(v^b))+T[12]+1804603682&4294967295,p=I+(y<<7&4294967295|y>>>25),y=b+(v^p&(I^v))+T[13]+4254626195&4294967295,b=p+(y<<12&4294967295|y>>>20),y=v+(I^b&(p^I))+T[14]+2792965006&4294967295,v=b+(y<<17&4294967295|y>>>15),y=I+(p^v&(b^p))+T[15]+1236535329&4294967295,I=v+(y<<22&4294967295|y>>>10),y=p+(v^b&(I^v))+T[1]+4129170786&4294967295,p=I+(y<<5&4294967295|y>>>27),y=b+(I^v&(p^I))+T[6]+3225465664&4294967295,b=p+(y<<9&4294967295|y>>>23),y=v+(p^I&(b^p))+T[11]+643717713&4294967295,v=b+(y<<14&4294967295|y>>>18),y=I+(b^p&(v^b))+T[0]+3921069994&4294967295,I=v+(y<<20&4294967295|y>>>12),y=p+(v^b&(I^v))+T[5]+3593408605&4294967295,p=I+(y<<5&4294967295|y>>>27),y=b+(I^v&(p^I))+T[10]+38016083&4294967295,b=p+(y<<9&4294967295|y>>>23),y=v+(p^I&(b^p))+T[15]+3634488961&4294967295,v=b+(y<<14&4294967295|y>>>18),y=I+(b^p&(v^b))+T[4]+3889429448&4294967295,I=v+(y<<20&4294967295|y>>>12),y=p+(v^b&(I^v))+T[9]+568446438&4294967295,p=I+(y<<5&4294967295|y>>>27),y=b+(I^v&(p^I))+T[14]+3275163606&4294967295,b=p+(y<<9&4294967295|y>>>23),y=v+(p^I&(b^p))+T[3]+4107603335&4294967295,v=b+(y<<14&4294967295|y>>>18),y=I+(b^p&(v^b))+T[8]+1163531501&4294967295,I=v+(y<<20&4294967295|y>>>12),y=p+(v^b&(I^v))+T[13]+2850285829&4294967295,p=I+(y<<5&4294967295|y>>>27),y=b+(I^v&(p^I))+T[2]+4243563512&4294967295,b=p+(y<<9&4294967295|y>>>23),y=v+(p^I&(b^p))+T[7]+1735328473&4294967295,v=b+(y<<14&4294967295|y>>>18),y=I+(b^p&(v^b))+T[12]+2368359562&4294967295,I=v+(y<<20&4294967295|y>>>12),y=p+(I^v^b)+T[5]+4294588738&4294967295,p=I+(y<<4&4294967295|y>>>28),y=b+(p^I^v)+T[8]+2272392833&4294967295,b=p+(y<<11&4294967295|y>>>21),y=v+(b^p^I)+T[11]+1839030562&4294967295,v=b+(y<<16&4294967295|y>>>16),y=I+(v^b^p)+T[14]+4259657740&4294967295,I=v+(y<<23&4294967295|y>>>9),y=p+(I^v^b)+T[1]+2763975236&4294967295,p=I+(y<<4&4294967295|y>>>28),y=b+(p^I^v)+T[4]+1272893353&4294967295,b=p+(y<<11&4294967295|y>>>21),y=v+(b^p^I)+T[7]+4139469664&4294967295,v=b+(y<<16&4294967295|y>>>16),y=I+(v^b^p)+T[10]+3200236656&4294967295,I=v+(y<<23&4294967295|y>>>9),y=p+(I^v^b)+T[13]+681279174&4294967295,p=I+(y<<4&4294967295|y>>>28),y=b+(p^I^v)+T[0]+3936430074&4294967295,b=p+(y<<11&4294967295|y>>>21),y=v+(b^p^I)+T[3]+3572445317&4294967295,v=b+(y<<16&4294967295|y>>>16),y=I+(v^b^p)+T[6]+76029189&4294967295,I=v+(y<<23&4294967295|y>>>9),y=p+(I^v^b)+T[9]+3654602809&4294967295,p=I+(y<<4&4294967295|y>>>28),y=b+(p^I^v)+T[12]+3873151461&4294967295,b=p+(y<<11&4294967295|y>>>21),y=v+(b^p^I)+T[15]+530742520&4294967295,v=b+(y<<16&4294967295|y>>>16),y=I+(v^b^p)+T[2]+3299628645&4294967295,I=v+(y<<23&4294967295|y>>>9),y=p+(v^(I|~b))+T[0]+4096336452&4294967295,p=I+(y<<6&4294967295|y>>>26),y=b+(I^(p|~v))+T[7]+1126891415&4294967295,b=p+(y<<10&4294967295|y>>>22),y=v+(p^(b|~I))+T[14]+2878612391&4294967295,v=b+(y<<15&4294967295|y>>>17),y=I+(b^(v|~p))+T[5]+4237533241&4294967295,I=v+(y<<21&4294967295|y>>>11),y=p+(v^(I|~b))+T[12]+1700485571&4294967295,p=I+(y<<6&4294967295|y>>>26),y=b+(I^(p|~v))+T[3]+2399980690&4294967295,b=p+(y<<10&4294967295|y>>>22),y=v+(p^(b|~I))+T[10]+4293915773&4294967295,v=b+(y<<15&4294967295|y>>>17),y=I+(b^(v|~p))+T[1]+2240044497&4294967295,I=v+(y<<21&4294967295|y>>>11),y=p+(v^(I|~b))+T[8]+1873313359&4294967295,p=I+(y<<6&4294967295|y>>>26),y=b+(I^(p|~v))+T[15]+4264355552&4294967295,b=p+(y<<10&4294967295|y>>>22),y=v+(p^(b|~I))+T[6]+2734768916&4294967295,v=b+(y<<15&4294967295|y>>>17),y=I+(b^(v|~p))+T[13]+1309151649&4294967295,I=v+(y<<21&4294967295|y>>>11),y=p+(v^(I|~b))+T[4]+4149444226&4294967295,p=I+(y<<6&4294967295|y>>>26),y=b+(I^(p|~v))+T[11]+3174756917&4294967295,b=p+(y<<10&4294967295|y>>>22),y=v+(p^(b|~I))+T[2]+718787259&4294967295,v=b+(y<<15&4294967295|y>>>17),y=I+(b^(v|~p))+T[9]+3951481745&4294967295,E.g[0]=E.g[0]+p&4294967295,E.g[1]=E.g[1]+(v+(y<<21&4294967295|y>>>11))&4294967295,E.g[2]=E.g[2]+v&4294967295,E.g[3]=E.g[3]+b&4294967295}n.prototype.u=function(E,p){p===void 0&&(p=E.length);for(var I=p-this.blockSize,T=this.B,v=this.h,b=0;b<p;){if(v==0)for(;b<=I;)s(this,E,b),b+=this.blockSize;if(typeof E=="string"){for(;b<p;)if(T[v++]=E.charCodeAt(b++),v==this.blockSize){s(this,T),v=0;break}}else for(;b<p;)if(T[v++]=E[b++],v==this.blockSize){s(this,T),v=0;break}}this.h=v,this.o+=p},n.prototype.v=function(){var E=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);E[0]=128;for(var p=1;p<E.length-8;++p)E[p]=0;var I=8*this.o;for(p=E.length-8;p<E.length;++p)E[p]=I&255,I/=256;for(this.u(E),E=Array(16),p=I=0;4>p;++p)for(var T=0;32>T;T+=8)E[I++]=this.g[p]>>>T&255;return E};function i(E,p){var I=u;return Object.prototype.hasOwnProperty.call(I,E)?I[E]:I[E]=p(E)}function a(E,p){this.h=p;for(var I=[],T=!0,v=E.length-1;0<=v;v--){var b=E[v]|0;T&&b==p||(I[v]=b,T=!1)}this.g=I}var u={};function c(E){return-128<=E&&128>E?i(E,function(p){return new a([p|0],0>p?-1:0)}):new a([E|0],0>E?-1:0)}function h(E){if(isNaN(E)||!isFinite(E))return g;if(0>E)return V(h(-E));for(var p=[],I=1,T=0;E>=I;T++)p[T]=E/I|0,I*=4294967296;return new a(p,0)}function f(E,p){if(E.length==0)throw Error("number format error: empty string");if(p=p||10,2>p||36<p)throw Error("radix out of range: "+p);if(E.charAt(0)=="-")return V(f(E.substring(1),p));if(0<=E.indexOf("-"))throw Error('number format error: interior "-" character');for(var I=h(Math.pow(p,8)),T=g,v=0;v<E.length;v+=8){var b=Math.min(8,E.length-v),y=parseInt(E.substring(v,v+b),p);8>b?(b=h(Math.pow(p,b)),T=T.j(b).add(h(y))):(T=T.j(I),T=T.add(h(y)))}return T}var g=c(0),_=c(1),R=c(16777216);r=a.prototype,r.m=function(){if(N(this))return-V(this).m();for(var E=0,p=1,I=0;I<this.g.length;I++){var T=this.i(I);E+=(0<=T?T:4294967296+T)*p,p*=4294967296}return E},r.toString=function(E){if(E=E||10,2>E||36<E)throw Error("radix out of range: "+E);if(C(this))return"0";if(N(this))return"-"+V(this).toString(E);for(var p=h(Math.pow(E,6)),I=this,T="";;){var v=$(I,p).g;I=q(I,v.j(p));var b=((0<I.g.length?I.g[0]:I.h)>>>0).toString(E);if(I=v,C(I))return b+T;for(;6>b.length;)b="0"+b;T=b+T}},r.i=function(E){return 0>E?0:E<this.g.length?this.g[E]:this.h};function C(E){if(E.h!=0)return!1;for(var p=0;p<E.g.length;p++)if(E.g[p]!=0)return!1;return!0}function N(E){return E.h==-1}r.l=function(E){return E=q(this,E),N(E)?-1:C(E)?0:1};function V(E){for(var p=E.g.length,I=[],T=0;T<p;T++)I[T]=~E.g[T];return new a(I,~E.h).add(_)}r.abs=function(){return N(this)?V(this):this},r.add=function(E){for(var p=Math.max(this.g.length,E.g.length),I=[],T=0,v=0;v<=p;v++){var b=T+(this.i(v)&65535)+(E.i(v)&65535),y=(b>>>16)+(this.i(v)>>>16)+(E.i(v)>>>16);T=y>>>16,b&=65535,y&=65535,I[v]=y<<16|b}return new a(I,I[I.length-1]&-2147483648?-1:0)};function q(E,p){return E.add(V(p))}r.j=function(E){if(C(this)||C(E))return g;if(N(this))return N(E)?V(this).j(V(E)):V(V(this).j(E));if(N(E))return V(this.j(V(E)));if(0>this.l(R)&&0>E.l(R))return h(this.m()*E.m());for(var p=this.g.length+E.g.length,I=[],T=0;T<2*p;T++)I[T]=0;for(T=0;T<this.g.length;T++)for(var v=0;v<E.g.length;v++){var b=this.i(T)>>>16,y=this.i(T)&65535,Jt=E.i(v)>>>16,Yn=E.i(v)&65535;I[2*T+2*v]+=y*Yn,j(I,2*T+2*v),I[2*T+2*v+1]+=b*Yn,j(I,2*T+2*v+1),I[2*T+2*v+1]+=y*Jt,j(I,2*T+2*v+1),I[2*T+2*v+2]+=b*Jt,j(I,2*T+2*v+2)}for(T=0;T<p;T++)I[T]=I[2*T+1]<<16|I[2*T];for(T=p;T<2*p;T++)I[T]=0;return new a(I,0)};function j(E,p){for(;(E[p]&65535)!=E[p];)E[p+1]+=E[p]>>>16,E[p]&=65535,p++}function B(E,p){this.g=E,this.h=p}function $(E,p){if(C(p))throw Error("division by zero");if(C(E))return new B(g,g);if(N(E))return p=$(V(E),p),new B(V(p.g),V(p.h));if(N(p))return p=$(E,V(p)),new B(V(p.g),p.h);if(30<E.g.length){if(N(E)||N(p))throw Error("slowDivide_ only works with positive integers.");for(var I=_,T=p;0>=T.l(E);)I=Z(I),T=Z(T);var v=K(I,1),b=K(T,1);for(T=K(T,2),I=K(I,2);!C(T);){var y=b.add(T);0>=y.l(E)&&(v=v.add(I),b=y),T=K(T,1),I=K(I,1)}return p=q(E,v.j(p)),new B(v,p)}for(v=g;0<=E.l(p);){for(I=Math.max(1,Math.floor(E.m()/p.m())),T=Math.ceil(Math.log(I)/Math.LN2),T=48>=T?1:Math.pow(2,T-48),b=h(I),y=b.j(p);N(y)||0<y.l(E);)I-=T,b=h(I),y=b.j(p);C(b)&&(b=_),v=v.add(b),E=q(E,y)}return new B(v,E)}r.A=function(E){return $(this,E).h},r.and=function(E){for(var p=Math.max(this.g.length,E.g.length),I=[],T=0;T<p;T++)I[T]=this.i(T)&E.i(T);return new a(I,this.h&E.h)},r.or=function(E){for(var p=Math.max(this.g.length,E.g.length),I=[],T=0;T<p;T++)I[T]=this.i(T)|E.i(T);return new a(I,this.h|E.h)},r.xor=function(E){for(var p=Math.max(this.g.length,E.g.length),I=[],T=0;T<p;T++)I[T]=this.i(T)^E.i(T);return new a(I,this.h^E.h)};function Z(E){for(var p=E.g.length+1,I=[],T=0;T<p;T++)I[T]=E.i(T)<<1|E.i(T-1)>>>31;return new a(I,E.h)}function K(E,p){var I=p>>5;p%=32;for(var T=E.g.length-I,v=[],b=0;b<T;b++)v[b]=0<p?E.i(b+I)>>>p|E.i(b+I+1)<<32-p:E.i(b+I);return new a(v,E.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,dl=n,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=h,a.fromString=f,Qe=a}).apply(typeof ju<"u"?ju:typeof self<"u"?self:typeof window<"u"?window:{});var vs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var fl,Ir,ml,Vs,ao,gl,pl,_l;(function(){var r,t=typeof Object.defineProperties=="function"?Object.defineProperty:function(o,l,d){return o==Array.prototype||o==Object.prototype||(o[l]=d.value),o};function e(o){o=[typeof globalThis=="object"&&globalThis,o,typeof window=="object"&&window,typeof self=="object"&&self,typeof vs=="object"&&vs];for(var l=0;l<o.length;++l){var d=o[l];if(d&&d.Math==Math)return d}throw Error("Cannot find global object")}var n=e(this);function s(o,l){if(l)t:{var d=n;o=o.split(".");for(var m=0;m<o.length-1;m++){var A=o[m];if(!(A in d))break t;d=d[A]}o=o[o.length-1],m=d[o],l=l(m),l!=m&&l!=null&&t(d,o,{configurable:!0,writable:!0,value:l})}}function i(o,l){o instanceof String&&(o+="");var d=0,m=!1,A={next:function(){if(!m&&d<o.length){var S=d++;return{value:l(S,o[S]),done:!1}}return m=!0,{done:!0,value:void 0}}};return A[Symbol.iterator]=function(){return A},A}s("Array.prototype.values",function(o){return o||function(){return i(this,function(l,d){return d})}});var a=a||{},u=this||self;function c(o){var l=typeof o;return l=l!="object"?l:o?Array.isArray(o)?"array":l:"null",l=="array"||l=="object"&&typeof o.length=="number"}function h(o){var l=typeof o;return l=="object"&&o!=null||l=="function"}function f(o,l,d){return o.call.apply(o.bind,arguments)}function g(o,l,d){if(!o)throw Error();if(2<arguments.length){var m=Array.prototype.slice.call(arguments,2);return function(){var A=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(A,m),o.apply(l,A)}}return function(){return o.apply(l,arguments)}}function _(o,l,d){return _=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?f:g,_.apply(null,arguments)}function R(o,l){var d=Array.prototype.slice.call(arguments,1);return function(){var m=d.slice();return m.push.apply(m,arguments),o.apply(this,m)}}function C(o,l){function d(){}d.prototype=l.prototype,o.aa=l.prototype,o.prototype=new d,o.prototype.constructor=o,o.Qb=function(m,A,S){for(var M=Array(arguments.length-2),rt=2;rt<arguments.length;rt++)M[rt-2]=arguments[rt];return l.prototype[A].apply(m,M)}}function N(o){const l=o.length;if(0<l){const d=Array(l);for(let m=0;m<l;m++)d[m]=o[m];return d}return[]}function V(o,l){for(let d=1;d<arguments.length;d++){const m=arguments[d];if(c(m)){const A=o.length||0,S=m.length||0;o.length=A+S;for(let M=0;M<S;M++)o[A+M]=m[M]}else o.push(m)}}class q{constructor(l,d){this.i=l,this.j=d,this.h=0,this.g=null}get(){let l;return 0<this.h?(this.h--,l=this.g,this.g=l.next,l.next=null):l=this.i(),l}}function j(o){return/^[\s\xa0]*$/.test(o)}function B(){var o=u.navigator;return o&&(o=o.userAgent)?o:""}function $(o){return $[" "](o),o}$[" "]=function(){};var Z=B().indexOf("Gecko")!=-1&&!(B().toLowerCase().indexOf("webkit")!=-1&&B().indexOf("Edge")==-1)&&!(B().indexOf("Trident")!=-1||B().indexOf("MSIE")!=-1)&&B().indexOf("Edge")==-1;function K(o,l,d){for(const m in o)l.call(d,o[m],m,o)}function E(o,l){for(const d in o)l.call(void 0,o[d],d,o)}function p(o){const l={};for(const d in o)l[d]=o[d];return l}const I="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function T(o,l){let d,m;for(let A=1;A<arguments.length;A++){m=arguments[A];for(d in m)o[d]=m[d];for(let S=0;S<I.length;S++)d=I[S],Object.prototype.hasOwnProperty.call(m,d)&&(o[d]=m[d])}}function v(o){var l=1;o=o.split(":");const d=[];for(;0<l&&o.length;)d.push(o.shift()),l--;return o.length&&d.push(o.join(":")),d}function b(o){u.setTimeout(()=>{throw o},0)}function y(){var o=wi;let l=null;return o.g&&(l=o.g,o.g=o.g.next,o.g||(o.h=null),l.next=null),l}class Jt{constructor(){this.h=this.g=null}add(l,d){const m=Yn.get();m.set(l,d),this.h?this.h.next=m:this.g=m,this.h=m}}var Yn=new q(()=>new qd,o=>o.reset());class qd{constructor(){this.next=this.g=this.h=null}set(l,d){this.h=l,this.g=d,this.next=null}reset(){this.next=this.g=this.h=null}}let Xn,Zn=!1,wi=new Jt,xa=()=>{const o=u.Promise.resolve(void 0);Xn=()=>{o.then(jd)}};var jd=()=>{for(var o;o=y();){try{o.h.call(o.g)}catch(d){b(d)}var l=Yn;l.j(o),100>l.h&&(l.h++,o.next=l.g,l.g=o)}Zn=!1};function ae(){this.s=this.s,this.C=this.C}ae.prototype.s=!1,ae.prototype.ma=function(){this.s||(this.s=!0,this.N())},ae.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Pt(o,l){this.type=o,this.g=this.target=l,this.defaultPrevented=!1}Pt.prototype.h=function(){this.defaultPrevented=!0};var zd=(function(){if(!u.addEventListener||!Object.defineProperty)return!1;var o=!1,l=Object.defineProperty({},"passive",{get:function(){o=!0}});try{const d=()=>{};u.addEventListener("test",d,l),u.removeEventListener("test",d,l)}catch{}return o})();function tr(o,l){if(Pt.call(this,o?o.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,o){var d=this.type=o.type,m=o.changedTouches&&o.changedTouches.length?o.changedTouches[0]:null;if(this.target=o.target||o.srcElement,this.g=l,l=o.relatedTarget){if(Z){t:{try{$(l.nodeName);var A=!0;break t}catch{}A=!1}A||(l=null)}}else d=="mouseover"?l=o.fromElement:d=="mouseout"&&(l=o.toElement);this.relatedTarget=l,m?(this.clientX=m.clientX!==void 0?m.clientX:m.pageX,this.clientY=m.clientY!==void 0?m.clientY:m.pageY,this.screenX=m.screenX||0,this.screenY=m.screenY||0):(this.clientX=o.clientX!==void 0?o.clientX:o.pageX,this.clientY=o.clientY!==void 0?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0),this.button=o.button,this.key=o.key||"",this.ctrlKey=o.ctrlKey,this.altKey=o.altKey,this.shiftKey=o.shiftKey,this.metaKey=o.metaKey,this.pointerId=o.pointerId||0,this.pointerType=typeof o.pointerType=="string"?o.pointerType:Gd[o.pointerType]||"",this.state=o.state,this.i=o,o.defaultPrevented&&tr.aa.h.call(this)}}C(tr,Pt);var Gd={2:"touch",3:"pen",4:"mouse"};tr.prototype.h=function(){tr.aa.h.call(this);var o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var rs="closure_listenable_"+(1e6*Math.random()|0),Kd=0;function $d(o,l,d,m,A){this.listener=o,this.proxy=null,this.src=l,this.type=d,this.capture=!!m,this.ha=A,this.key=++Kd,this.da=this.fa=!1}function ss(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function is(o){this.src=o,this.g={},this.h=0}is.prototype.add=function(o,l,d,m,A){var S=o.toString();o=this.g[S],o||(o=this.g[S]=[],this.h++);var M=Ri(o,l,m,A);return-1<M?(l=o[M],d||(l.fa=!1)):(l=new $d(l,this.src,S,!!m,A),l.fa=d,o.push(l)),l};function Ai(o,l){var d=l.type;if(d in o.g){var m=o.g[d],A=Array.prototype.indexOf.call(m,l,void 0),S;(S=0<=A)&&Array.prototype.splice.call(m,A,1),S&&(ss(l),o.g[d].length==0&&(delete o.g[d],o.h--))}}function Ri(o,l,d,m){for(var A=0;A<o.length;++A){var S=o[A];if(!S.da&&S.listener==l&&S.capture==!!d&&S.ha==m)return A}return-1}var bi="closure_lm_"+(1e6*Math.random()|0),Pi={};function Na(o,l,d,m,A){if(Array.isArray(l)){for(var S=0;S<l.length;S++)Na(o,l[S],d,m,A);return null}return d=Oa(d),o&&o[rs]?o.K(l,d,h(m)?!!m.capture:!1,A):Qd(o,l,d,!1,m,A)}function Qd(o,l,d,m,A,S){if(!l)throw Error("Invalid event type");var M=h(A)?!!A.capture:!!A,rt=Vi(o);if(rt||(o[bi]=rt=new is(o)),d=rt.add(l,d,m,M,S),d.proxy)return d;if(m=Wd(),d.proxy=m,m.src=o,m.listener=d,o.addEventListener)zd||(A=M),A===void 0&&(A=!1),o.addEventListener(l.toString(),m,A);else if(o.attachEvent)o.attachEvent(Ma(l.toString()),m);else if(o.addListener&&o.removeListener)o.addListener(m);else throw Error("addEventListener and attachEvent are unavailable.");return d}function Wd(){function o(d){return l.call(o.src,o.listener,d)}const l=Hd;return o}function ka(o,l,d,m,A){if(Array.isArray(l))for(var S=0;S<l.length;S++)ka(o,l[S],d,m,A);else m=h(m)?!!m.capture:!!m,d=Oa(d),o&&o[rs]?(o=o.i,l=String(l).toString(),l in o.g&&(S=o.g[l],d=Ri(S,d,m,A),-1<d&&(ss(S[d]),Array.prototype.splice.call(S,d,1),S.length==0&&(delete o.g[l],o.h--)))):o&&(o=Vi(o))&&(l=o.g[l.toString()],o=-1,l&&(o=Ri(l,d,m,A)),(d=-1<o?l[o]:null)&&Si(d))}function Si(o){if(typeof o!="number"&&o&&!o.da){var l=o.src;if(l&&l[rs])Ai(l.i,o);else{var d=o.type,m=o.proxy;l.removeEventListener?l.removeEventListener(d,m,o.capture):l.detachEvent?l.detachEvent(Ma(d),m):l.addListener&&l.removeListener&&l.removeListener(m),(d=Vi(l))?(Ai(d,o),d.h==0&&(d.src=null,l[bi]=null)):ss(o)}}}function Ma(o){return o in Pi?Pi[o]:Pi[o]="on"+o}function Hd(o,l){if(o.da)o=!0;else{l=new tr(l,this);var d=o.listener,m=o.ha||o.src;o.fa&&Si(o),o=d.call(m,l)}return o}function Vi(o){return o=o[bi],o instanceof is?o:null}var Ci="__closure_events_fn_"+(1e9*Math.random()>>>0);function Oa(o){return typeof o=="function"?o:(o[Ci]||(o[Ci]=function(l){return o.handleEvent(l)}),o[Ci])}function St(){ae.call(this),this.i=new is(this),this.M=this,this.F=null}C(St,ae),St.prototype[rs]=!0,St.prototype.removeEventListener=function(o,l,d,m){ka(this,o,l,d,m)};function Mt(o,l){var d,m=o.F;if(m)for(d=[];m;m=m.F)d.push(m);if(o=o.M,m=l.type||l,typeof l=="string")l=new Pt(l,o);else if(l instanceof Pt)l.target=l.target||o;else{var A=l;l=new Pt(m,o),T(l,A)}if(A=!0,d)for(var S=d.length-1;0<=S;S--){var M=l.g=d[S];A=os(M,m,!0,l)&&A}if(M=l.g=o,A=os(M,m,!0,l)&&A,A=os(M,m,!1,l)&&A,d)for(S=0;S<d.length;S++)M=l.g=d[S],A=os(M,m,!1,l)&&A}St.prototype.N=function(){if(St.aa.N.call(this),this.i){var o=this.i,l;for(l in o.g){for(var d=o.g[l],m=0;m<d.length;m++)ss(d[m]);delete o.g[l],o.h--}}this.F=null},St.prototype.K=function(o,l,d,m){return this.i.add(String(o),l,!1,d,m)},St.prototype.L=function(o,l,d,m){return this.i.add(String(o),l,!0,d,m)};function os(o,l,d,m){if(l=o.i.g[String(l)],!l)return!0;l=l.concat();for(var A=!0,S=0;S<l.length;++S){var M=l[S];if(M&&!M.da&&M.capture==d){var rt=M.listener,At=M.ha||M.src;M.fa&&Ai(o.i,M),A=rt.call(At,m)!==!1&&A}}return A&&!m.defaultPrevented}function Fa(o,l,d){if(typeof o=="function")d&&(o=_(o,d));else if(o&&typeof o.handleEvent=="function")o=_(o.handleEvent,o);else throw Error("Invalid listener argument");return 2147483647<Number(l)?-1:u.setTimeout(o,l||0)}function La(o){o.g=Fa(()=>{o.g=null,o.i&&(o.i=!1,La(o))},o.l);const l=o.h;o.h=null,o.m.apply(null,l)}class Jd extends ae{constructor(l,d){super(),this.m=l,this.l=d,this.h=null,this.i=!1,this.g=null}j(l){this.h=arguments,this.g?this.i=!0:La(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function er(o){ae.call(this),this.h=o,this.g={}}C(er,ae);var Ba=[];function Ua(o){K(o.g,function(l,d){this.g.hasOwnProperty(d)&&Si(l)},o),o.g={}}er.prototype.N=function(){er.aa.N.call(this),Ua(this)},er.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Di=u.JSON.stringify,Yd=u.JSON.parse,Xd=class{stringify(o){return u.JSON.stringify(o,void 0)}parse(o){return u.JSON.parse(o,void 0)}};function xi(){}xi.prototype.h=null;function qa(o){return o.h||(o.h=o.i())}function ja(){}var nr={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Ni(){Pt.call(this,"d")}C(Ni,Pt);function ki(){Pt.call(this,"c")}C(ki,Pt);var Oe={},za=null;function as(){return za=za||new St}Oe.La="serverreachability";function Ga(o){Pt.call(this,Oe.La,o)}C(Ga,Pt);function rr(o){const l=as();Mt(l,new Ga(l))}Oe.STAT_EVENT="statevent";function Ka(o,l){Pt.call(this,Oe.STAT_EVENT,o),this.stat=l}C(Ka,Pt);function Ot(o){const l=as();Mt(l,new Ka(l,o))}Oe.Ma="timingevent";function $a(o,l){Pt.call(this,Oe.Ma,o),this.size=l}C($a,Pt);function sr(o,l){if(typeof o!="function")throw Error("Fn must not be null and must be a function");return u.setTimeout(function(){o()},l)}function ir(){this.g=!0}ir.prototype.xa=function(){this.g=!1};function Zd(o,l,d,m,A,S){o.info(function(){if(o.g)if(S)for(var M="",rt=S.split("&"),At=0;At<rt.length;At++){var X=rt[At].split("=");if(1<X.length){var Vt=X[0];X=X[1];var Ct=Vt.split("_");M=2<=Ct.length&&Ct[1]=="type"?M+(Vt+"="+X+"&"):M+(Vt+"=redacted&")}}else M=null;else M=S;return"XMLHTTP REQ ("+m+") [attempt "+A+"]: "+l+` 2`+d+` 3`+M})}function tf(o,l,d,m,A,S,M){o.info(function(){return"XMLHTTP RESP ("+m+") [ attempt "+A+"]: "+l+` 4`+d+` 5`+S+" "+M})}function cn(o,l,d,m){o.info(function(){return"XMLHTTP TEXT ("+l+"): "+nf(o,d)+(m?" "+m:"")})}function ef(o,l){o.info(function(){return"TIMEOUT: "+l})}ir.prototype.info=function(){};function nf(o,l){if(!o.g)return l;if(!l)return null;try{var d=JSON.parse(l);if(d){for(o=0;o<d.length;o++)if(Array.isArray(d[o])){var m=d[o];if(!(2>m.length)){var A=m[1];if(Array.isArray(A)&&!(1>A.length)){var S=A[0];if(S!="noop"&&S!="stop"&&S!="close")for(var M=1;M<A.length;M++)A[M]=""}}}}return Di(d)}catch{return l}}var us={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Qa={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"},Mi;function cs(){}C(cs,xi),cs.prototype.g=function(){return new XMLHttpRequest},cs.prototype.i=function(){return{}},Mi=new cs;function ue(o,l,d,m){this.j=o,this.i=l,this.l=d,this.R=m||1,this.U=new er(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Wa}function Wa(){this.i=null,this.g="",this.h=!1}var Ha={},Oi={};function Fi(o,l,d){o.L=1,o.v=fs(Yt(l)),o.m=d,o.P=!0,Ja(o,null)}function Ja(o,l){o.F=Date.now(),ls(o),o.A=Yt(o.v);var d=o.A,m=o.R;Array.isArray(m)||(m=[String(m)]),lu(d.i,"t",m),o.C=0,d=o.j.J,o.h=new Wa,o.g=Su(o.j,d?l:null,!o.m),0<o.O&&(o.M=new Jd(_(o.Y,o,o.g),o.O)),l=o.U,d=o.g,m=o.ca;var A="readystatechange";Array.isArray(A)||(A&&(Ba[0]=A.toString()),A=Ba);for(var S=0;S<A.length;S++){var M=Na(d,A[S],m||l.handleEvent,!1,l.h||l);if(!M)break;l.g[M.key]=M}l=o.H?p(o.H):{},o.m?(o.u||(o.u="POST"),l["Content-Type"]="application/x-www-form-urlencoded",o.g.ea(o.A,o.u,o.m,l)):(o.u="GET",o.g.ea(o.A,o.u,null,l)),rr(),Zd(o.i,o.u,o.A,o.l,o.R,o.m)}ue.prototype.ca=function(o){o=o.target;const l=this.M;l&&Xt(o)==3?l.j():this.Y(o)},ue.prototype.Y=function(o){try{if(o==this.g)t:{const Ct=Xt(this.g);var l=this.g.Ba();const dn=this.g.Z();if(!(3>Ct)&&(Ct!=3||this.g&&(this.h.h||this.g.oa()||_u(this.g)))){this.J||Ct!=4||l==7||(l==8||0>=dn?rr(3):rr(2)),Li(this);var d=this.g.Z();this.X=d;e:if(Ya(this)){var m=_u(this.g);o="";var A=m.length,S=Xt(this.g)==4;if(!this.h.i){if(typeof TextDecoder>"u"){Fe(this),or(this);var M="";break e}this.h.i=new u.TextDecoder}for(l=0;l<A;l++)this.h.h=!0,o+=this.h.i.decode(m[l],{stream:!(S&&l==A-1)});m.length=0,this.h.g+=o,this.C=0,M=this.h.g}else M=this.g.oa();if(this.o=d==200,tf(this.i,this.u,this.A,this.l,this.R,Ct,d),this.o){if(this.T&&!this.K){e:{if(this.g){var rt,At=this.g;if((rt=At.g?At.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!j(rt)){var X=rt;break e}}X=null}if(d=X)cn(this.i,this.l,d,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Bi(this,d);else{this.o=!1,this.s=3,Ot(12),Fe(this),or(this);break t}}if(this.P){d=!0;let zt;for(;!this.J&&this.C<M.length;)if(zt=rf(this,M),zt==Oi){Ct==4&&(this.s=4,Ot(14),d=!1),cn(this.i,this.l,null,"[Incomplete Response]");break}else if(zt==Ha){this.s=4,Ot(15),cn(this.i,this.l,M,"[Invalid Chunk]"),d=!1;break}else cn(this.i,this.l,zt,null),Bi(this,zt);if(Ya(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),Ct!=4||M.length!=0||this.h.h||(this.s=1,Ot(16),d=!1),this.o=this.o&&d,!d)cn(this.i,this.l,M,"[Invalid Chunked Response]"),Fe(this),or(this);else if(0<M.length&&!this.W){this.W=!0;var Vt=this.j;Vt.g==this&&Vt.ba&&!Vt.M&&(Vt.j.info("Great, no buffering proxy detected. Bytes received: "+M.length),Ki(Vt),Vt.M=!0,Ot(11))}}else cn(this.i,this.l,M,null),Bi(this,M);Ct==4&&Fe(this),this.o&&!this.J&&(Ct==4?Au(this.j,this):(this.o=!1,ls(this)))}else Tf(this.g),d==400&&0<M.indexOf("Unknown SID")?(this.s=3,Ot(12)):(this.s=0,Ot(13)),Fe(this),or(this)}}}catch{}};function Ya(o){return o.g?o.u=="GET"&&o.L!=2&&o.j.Ca:!1}function rf(o,l){var d=o.C,m=l.indexOf(` 6`,d);return m==-1?Oi:(d=Number(l.substring(d,m)),isNaN(d)?Ha:(m+=1,m+d>l.length?Oi:(l=l.slice(m,m+d),o.C=m+d,l)))}ue.prototype.cancel=function(){this.J=!0,Fe(this)};function ls(o){o.S=Date.now()+o.I,Xa(o,o.I)}function Xa(o,l){if(o.B!=null)throw Error("WatchDog timer not null");o.B=sr(_(o.ba,o),l)}function Li(o){o.B&&(u.clearTimeout(o.B),o.B=null)}ue.prototype.ba=function(){this.B=null;const o=Date.now();0<=o-this.S?(ef(this.i,this.A),this.L!=2&&(rr(),Ot(17)),Fe(this),this.s=2,or(this)):Xa(this,this.S-o)};function or(o){o.j.G==0||o.J||Au(o.j,o)}function Fe(o){Li(o);var l=o.M;l&&typeof l.ma=="function"&&l.ma(),o.M=null,Ua(o.U),o.g&&(l=o.g,o.g=null,l.abort(),l.ma())}function Bi(o,l){try{var d=o.j;if(d.G!=0&&(d.g==o||Ui(d.h,o))){if(!o.K&&Ui(d.h,o)&&d.G==3){try{var m=d.Da.g.parse(l)}catch{m=null}if(Array.isArray(m)&&m.length==3){var A=m;if(A[0]==0){t:if(!d.u){if(d.g)if(d.g.F+3e3<o.F)Is(d),_s(d);else break t;Gi(d),Ot(18)}}else d.za=A[1],0<d.za-d.T&&37500>A[2]&&d.F&&d.v==0&&!d.C&&(d.C=sr(_(d.Za,d),6e3));if(1>=eu(d.h)&&d.ca){try{d.ca()}catch{}d.ca=void 0}}else Be(d,11)}else if((o.K||d.g==o)&&Is(d),!j(l))for(A=d.Da.g.parse(l),l=0;l<A.length;l++){let X=A[l];if(d.T=X[0],X=X[1],d.G==2)if(X[0]=="c"){d.K=X[1],d.ia=X[2];const Vt=X[3];Vt!=null&&(d.la=Vt,d.j.info("VER="+d.la));const Ct=X[4];Ct!=null&&(d.Aa=Ct,d.j.info("SVER="+d.Aa));const dn=X[5];dn!=null&&typeof dn=="number"&&0<dn&&(m=1.5*dn,d.L=m,d.j.info("backChannelRequestTimeoutMs_="+m)),m=d;const zt=o.g;if(zt){const Ts=zt.g?zt.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Ts){var S=m.h;S.g||Ts.indexOf("spdy")==-1&&Ts.indexOf("quic")==-1&&Ts.indexOf("h2")==-1||(S.j=S.l,S.g=new Set,S.h&&(qi(S,S.h),S.h=null))}if(m.D){const $i=zt.g?zt.g.getResponseHeader("X-HTTP-Session-Id"):null;$i&&(m.ya=$i,it(m.I,m.D,$i))}}d.G=3,d.l&&d.l.ua(),d.ba&&(d.R=Date.now()-o.F,d.j.info("Handshake RTT: "+d.R+"ms")),m=d;var M=o;if(m.qa=Pu(m,m.J?m.ia:null,m.W),M.K){nu(m.h,M);var rt=M,At=m.L;At&&(rt.I=At),rt.B&&(Li(rt),ls(rt)),m.g=M}else vu(m);0<d.i.length&&ys(d)}else X[0]!="stop"&&X[0]!="close"||Be(d,7);else d.G==3&&(X[0]=="stop"||X[0]=="close"?X[0]=="stop"?Be(d,7):zi(d):X[0]!="noop"&&d.l&&d.l.ta(X),d.v=0)}}rr(4)}catch{}}var sf=class{constructor(o,l){this.g=o,this.map=l}};function Za(o){this.l=o||10,u.PerformanceNavigationTiming?(o=u.performance.getEntriesByType("navigation"),o=0<o.length&&(o[0].nextHopProtocol=="hq"||o[0].nextHopProtocol=="h2")):o=!!(u.chrome&&u.chrome.loadTimes&&u.chrome.loadTimes()&&u.chrome.loadTimes().wasFetchedViaSpdy),this.j=o?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function tu(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function eu(o){return o.h?1:o.g?o.g.size:0}function Ui(o,l){return o.h?o.h==l:o.g?o.g.has(l):!1}function qi(o,l){o.g?o.g.add(l):o.h=l}function nu(o,l){o.h&&o.h==l?o.h=null:o.g&&o.g.has(l)&&o.g.delete(l)}Za.prototype.cancel=function(){if(this.i=ru(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(const o of this.g.values())o.cancel();this.g.clear()}};function ru(o){if(o.h!=null)return o.i.concat(o.h.D);if(o.g!=null&&o.g.size!==0){let l=o.i;for(const d of o.g.values())l=l.concat(d.D);return l}return N(o.i)}function of(o){if(o.V&&typeof o.V=="function")return o.V();if(typeof Map<"u"&&o instanceof Map||typeof Set<"u"&&o instanceof Set)return Array.from(o.values());if(typeof o=="string")return o.split("");if(c(o)){for(var l=[],d=o.length,m=0;m<d;m++)l.push(o[m]);return l}l=[],d=0;for(m in o)l[d++]=o[m];return l}function af(o){if(o.na&&typeof o.na=="function")return o.na();if(!o.V||typeof o.V!="function"){if(typeof Map<"u"&&o instanceof Map)return Array.from(o.keys());if(!(typeof Set<"u"&&o instanceof Set)){if(c(o)||typeof o=="string"){var l=[];o=o.length;for(var d=0;d<o;d++)l.push(d);return l}l=[],d=0;for(const m in o)l[d++]=m;return l}}}function su(o,l){if(o.forEach&&typeof o.forEach=="function")o.forEach(l,void 0);else if(c(o)||typeof o=="string")Array.prototype.forEach.call(o,l,void 0);else for(var d=af(o),m=of(o),A=m.length,S=0;S<A;S++)l.call(void 0,m[S],d&&d[S],o)}var iu=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function uf(o,l){if(o){o=o.split("&");for(var d=0;d<o.length;d++){var m=o[d].indexOf("="),A=null;if(0<=m){var S=o[d].substring(0,m);A=o[d].substring(m+1)}else S=o[d];l(S,A?decodeURIComponent(A.replace(/\+/g," ")):"")}}}function Le(o){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,o instanceof Le){this.h=o.h,hs(this,o.j),this.o=o.o,this.g=o.g,ds(this,o.s),this.l=o.l;var l=o.i,d=new cr;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),ou(this,d),this.m=o.m}else o&&(l=String(o).match(iu))?(this.h=!1,hs(this,l[1]||"",!0),this.o=ar(l[2]||""),this.g=ar(l[3]||"",!0),ds(this,l[4]),this.l=ar(l[5]||"",!0),ou(this,l[6]||"",!0),this.m=ar(l[7]||"")):(this.h=!1,this.i=new cr(null,this.h))}Le.prototype.toString=function(){var o=[],l=this.j;l&&o.push(ur(l,au,!0),":");var d=this.g;return(d||l=="file")&&(o.push("//"),(l=this.o)&&o.push(ur(l,au,!0),"@"),o.push(encodeURIComponent(String(d)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),d=this.s,d!=null&&o.push(":",String(d))),(d=this.l)&&(this.g&&d.charAt(0)!="/"&&o.push("/"),o.push(ur(d,d.charAt(0)=="/"?hf:lf,!0))),(d=this.i.toString())&&o.push("?",d),(d=this.m)&&o.push("#",ur(d,ff)),o.join("")};function Yt(o){return new Le(o)}function hs(o,l,d){o.j=d?ar(l,!0):l,o.j&&(o.j=o.j.replace(/:$/,""))}function ds(o,l){if(l){if(l=Number(l),isNaN(l)||0>l)throw Error("Bad port number "+l);o.s=l}else o.s=null}function ou(o,l,d){l instanceof cr?(o.i=l,mf(o.i,o.h)):(d||(l=ur(l,df)),o.i=new cr(l,o.h))}function it(o,l,d){o.i.set(l,d)}function fs(o){return it(o,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),o}function ar(o,l){return o?l?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function ur(o,l,d){return typeof o=="string"?(o=encodeURI(o).replace(l,cf),d&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function cf(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var au=/[#\/\?@]/g,lf=/[#\?:]/g,hf=/[#\?]/g,df=/[#\?@]/g,ff=/#/g;function cr(o,l){this.h=this.g=null,this.i=o||null,this.j=!!l}function ce(o){o.g||(o.g=new Map,o.h=0,o.i&&uf(o.i,function(l,d){o.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=cr.prototype,r.add=function(o,l){ce(this),this.i=null,o=ln(this,o);var d=this.g.get(o);return d||this.g.set(o,d=[]),d.push(l),this.h+=1,this};function uu(o,l){ce(o),l=ln(o,l),o.g.has(l)&&(o.i=null,o.h-=o.g.get(l).length,o.g.delete(l))}function cu(o,l){return ce(o),l=ln(o,l),o.g.has(l)}r.forEach=function(o,l){ce(this),this.g.forEach(function(d,m){d.forEach(function(A){o.call(l,A,m,this)},this)},this)},r.na=function(){ce(this);const o=Array.from(this.g.values()),l=Array.from(this.g.keys()),d=[];for(let m=0;m<l.length;m++){const A=o[m];for(let S=0;S<A.length;S++)d.push(l[m])}return d},r.V=function(o){ce(this);let l=[];if(typeof o=="string")cu(this,o)&&(l=l.concat(this.g.get(ln(this,o))));else{o=Array.from(this.g.values());for(let d=0;d<o.length;d++)l=l.concat(o[d])}return l},r.set=function(o,l){return ce(this),this.i=null,o=ln(this,o),cu(this,o)&&(this.h-=this.g.get(o).length),this.g.set(o,[l]),this.h+=1,this},r.get=function(o,l){return o?(o=this.V(o),0<o.length?String(o[0]):l):l};function lu(o,l,d){uu(o,l),0<d.length&&(o.i=null,o.g.set(ln(o,l),N(d)),o.h+=d.length)}r.toString=function(){if(this.i)return this.i;if(!this.g)return"";const o=[],l=Array.from(this.g.keys());for(var d=0;d<l.length;d++){var m=l[d];const S=encodeURIComponent(String(m)),M=this.V(m);for(m=0;m<M.length;m++){var A=S;M[m]!==""&&(A+="="+encodeURIComponent(String(M[m]))),o.push(A)}}return this.i=o.join("&")};function ln(o,l){return l=String(l),o.j&&(l=l.toLowerCase()),l}function mf(o,l){l&&!o.j&&(ce(o),o.i=null,o.g.forEach(function(d,m){var A=m.toLowerCase();m!=A&&(uu(this,m),lu(this,A,d))},o)),o.j=l}function gf(o,l){const d=new ir;if(u.Image){const m=new Image;m.onload=R(le,d,"TestLoadImage: loaded",!0,l,m),m.onerror=R(le,d,"TestLoadImage: error",!1,l,m),m.onabort=R(le,d,"TestLoadImage: abort",!1,l,m),m.ontimeout=R(le,d,"TestLoadImage: timeout",!1,l,m),u.setTimeout(function(){m.ontimeout&&m.ontimeout()},1e4),m.src=o}else l(!1)}function pf(o,l){const d=new ir,m=new AbortController,A=setTimeout(()=>{m.abort(),le(d,"TestPingServer: timeout",!1,l)},1e4);fetch(o,{signal:m.signal}).then(S=>{clearTimeout(A),S.ok?le(d,"TestPingServer: ok",!0,l):le(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(A),le(d,"TestPingServer: error",!1,l)})}function le(o,l,d,m,A){try{A&&(A.onload=null,A.onerror=null,A.onabort=null,A.ontimeout=null),m(d)}catch{}}function _f(){this.g=new Xd}function yf(o,l,d){const m=d||"";try{su(o,function(A,S){let M=A;h(A)&&(M=Di(A)),l.push(m+S+"="+encodeURIComponent(M))})}catch(A){throw l.push(m+"type="+encodeURIComponent("_badmap")),A}}function ms(o){this.l=o.Ub||null,this.j=o.eb||!1}C(ms,xi),ms.prototype.g=function(){return new gs(this.l,this.j)},ms.prototype.i=(function(o){return function(){return o}})({});function gs(o,l){St.call(this),this.D=o,this.o=l,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}C(gs,St),r=gs.prototype,r.open=function(o,l){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.B=o,this.A=l,this.readyState=1,hr(this)},r.send=function(o){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");this.g=!0;const l={headers:this.u,method:this.B,credentials:this.m,cache:void 0};o&&(l.body=o),(this.D||u).fetch(new Request(this.A,l)).then(this.Sa.bind(this),this.ga.bind(this))},r.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&this.readyState!=4&&(this.g=!1,lr(this)),this.readyState=0},r.Sa=function(o){if(this.g&&(this.l=o,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=o.headers,this.readyState=2,hr(this)),this.g&&(this.readyState=3,hr(this),this.g)))if(this.responseType==="arraybuffer")o.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(typeof u.ReadableStream<"u"&&"body"in o){if(this.j=o.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;hu(this)}else o.text().then(this.Ra.bind(this),this.ga.bind(this))};function hu(o){o.j.read().then(o.Pa.bind(o)).catch(o.ga.bind(o))}r.Pa=function(o){if(this.g){if(this.o&&o.value)this.response.push(o.value);else if(!this.o){var l=o.value?o.value:new Uint8Array(0);(l=this.v.decode(l,{stream:!o.done}))&&(this.response=this.responseText+=l)}o.done?lr(this):hr(this),this.readyState==3&&hu(this)}},r.Ra=function(o){this.g&&(this.response=this.responseText=o,lr(this))},r.Qa=function(o){this.g&&(this.response=o,lr(this))},r.ga=function(){this.g&&lr(this)};function lr(o){o.readyState=4,o.l=null,o.j=null,o.v=null,hr(o)}r.setRequestHeader=function(o,l){this.u.append(o,l)},r.getResponseHeader=function(o){return this.h&&this.h.get(o.toLowerCase())||""},r.getAllResponseHeaders=function(){if(!this.h)return"";const o=[],l=this.h.entries();for(var d=l.next();!d.done;)d=d.value,o.push(d[0]+": "+d[1]),d=l.next();return o.join(`\r 7`)};function hr(o){o.onreadystatechange&&o.onreadystatechange.call(o)}Object.defineProperty(gs.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(o){this.m=o?"include":"same-origin"}});function du(o){let l="";return K(o,function(d,m){l+=m,l+=":",l+=d,l+=`\r 8`}),l}function ji(o,l,d){t:{for(m in d){var m=!1;break t}m=!0}m||(d=du(d),typeof o=="string"?d!=null&&encodeURIComponent(String(d)):it(o,l,d))}function ft(o){St.call(this),this.headers=new Map,this.o=o||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}C(ft,St);var If=/^https?$/i,Ef=["POST","PUT"];r=ft.prototype,r.Ha=function(o){this.J=o},r.ea=function(o,l,d,m){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+o);l=l?l.toUpperCase():"GET",this.D=o,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Mi.g(),this.v=this.o?qa(this.o):qa(Mi),this.g.onreadystatechange=_(this.Ea,this);try{this.B=!0,this.g.open(l,String(o),!0),this.B=!1}catch(S){fu(this,S);return}if(o=d||"",d=new Map(this.headers),m)if(Object.getPrototypeOf(m)===Object.prototype)for(var A in m)d.set(A,m[A]);else if(typeof m.keys=="function"&&typeof m.get=="function")for(const S of m.keys())d.set(S,m.get(S));else throw Error("Unknown input type for opt_headers: "+String(m));m=Array.from(d.keys()).find(S=>S.toLowerCase()=="content-type"),A=u.FormData&&o instanceof u.FormData,!(0<=Array.prototype.indexOf.call(Ef,l,void 0))||m||A||d.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[S,M]of d)this.g.setRequestHeader(S,M);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{pu(this),this.u=!0,this.g.send(o),this.u=!1}catch(S){fu(this,S)}};function fu(o,l){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=l,o.m=5,mu(o),ps(o)}function mu(o){o.A||(o.A=!0,Mt(o,"complete"),Mt(o,"error"))}r.abort=function(o){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=o||7,Mt(this,"complete"),Mt(this,"abort"),ps(this))},r.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),ps(this,!0)),ft.aa.N.call(this)},r.Ea=function(){this.s||(this.B||this.u||this.j?gu(this):this.bb())},r.bb=function(){gu(this)};function gu(o){if(o.h&&typeof a<"u"&&(!o.v[1]||Xt(o)!=4||o.Z()!=2)){if(o.u&&Xt(o)==4)Fa(o.Ea,0,o);else if(Mt(o,"readystatechange"),Xt(o)==4){o.h=!1;try{const M=o.Z();t:switch(M){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var l=!0;break t;default:l=!1}var d;if(!(d=l)){var m;if(m=M===0){var A=String(o.D).match(iu)[1]||null;!A&&u.self&&u.self.location&&(A=u.self.location.protocol.slice(0,-1)),m=!If.test(A?A.toLowerCase():"")}d=m}if(d)Mt(o,"complete"),Mt(o,"success");else{o.m=6;try{var S=2<Xt(o)?o.g.statusText:""}catch{S=""}o.l=S+" ["+o.Z()+"]",mu(o)}}finally{ps(o)}}}}function ps(o,l){if(o.g){pu(o);const d=o.g,m=o.v[0]?()=>{}:null;o.g=null,o.v=null,l||Mt(o,"ready");try{d.onreadystatechange=m}catch{}}}function pu(o){o.I&&(u.clearTimeout(o.I),o.I=null)}r.isActive=function(){return!!this.g};function Xt(o){return o.g?o.g.readyState:0}r.Z=function(){try{return 2<Xt(this)?this.g.status:-1}catch{return-1}},r.oa=function(){try{return this.g?this.g.responseText:""}catch{return""}},r.Oa=function(o){if(this.g){var l=this.g.responseText;return o&&l.indexOf(o)==0&&(l=l.substring(o.length)),Yd(l)}};function _u(o){try{if(!o.g)return null;if("response"in o.g)return o.g.response;switch(o.H){case"":case"text":return o.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in o.g)return o.g.mozResponseArrayBuffer}return null}catch{return null}}function Tf(o){const l={};o=(o.g&&2<=Xt(o)&&o.g.getAllResponseHeaders()||"").split(`\r 9`);for(let m=0;m<o.length;m++){if(j(o[m]))continue;var d=v(o[m]);const A=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();const S=l[A]||[];l[A]=S,S.push(d)}E(l,function(m){return m.join(", ")})}r.Ba=function(){return this.m},r.Ka=function(){return typeof this.l=="string"?this.l:String(this.l)};function dr(o,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[o]||l}function yu(o){this.Aa=0,this.i=[],this.j=new ir,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=dr("failFast",!1,o),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=dr("baseRetryDelayMs",5e3,o),this.cb=dr("retryDelaySeedMs",1e4,o),this.Wa=dr("forwardChannelMaxRetries",2,o),this.wa=dr("forwardChannelRequestTimeoutMs",2e4,o),this.pa=o&&o.xmlHttpFactory||void 0,this.Xa=o&&o.Tb||void 0,this.Ca=o&&o.useFetchStreams||!1,this.L=void 0,this.J=o&&o.supportsCrossDomainXhr||!1,this.K="",this.h=new Za(o&&o.concurrentRequestLimit),this.Da=new _f,this.P=o&&o.fastHandshake||!1,this.O=o&&o.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=o&&o.Rb||!1,o&&o.xa&&this.j.xa(),o&&o.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&o&&o.detectBufferingProxy||!1,this.ja=void 0,o&&o.longPollingTimeout&&0<o.longPollingTimeout&&(this.ja=o.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}r=yu.prototype,r.la=8,r.G=1,r.connect=function(o,l,d,m){Ot(0),this.W=o,this.H=l||{},d&&m!==void 0&&(this.H.OSID=d,this.H.OAID=m),this.F=this.X,this.I=Pu(this,null,this.W),ys(this)};function zi(o){if(Iu(o),o.G==3){var l=o.U++,d=Yt(o.I);if(it(d,"SID",o.K),it(d,"RID",l),it(d,"TYPE","terminate"),fr(o,d),l=new ue(o,o.j,l),l.L=2,l.v=fs(Yt(d)),d=!1,u.navigator&&u.navigator.sendBeacon)try{d=u.navigator.sendBeacon(l.v.toString(),"")}catch{}!d&&u.Image&&(new Image().src=l.v,d=!0),d||(l.g=Su(l.j,null),l.g.ea(l.v)),l.F=Date.now(),ls(l)}bu(o)}function _s(o){o.g&&(Ki(o),o.g.cancel(),o.g=null)}function Iu(o){_s(o),o.u&&(u.clearTimeout(o.u),o.u=null),Is(o),o.h.cancel(),o.s&&(typeof o.s=="number"&&u.clearTimeout(o.s),o.s=null)}function ys(o){if(!tu(o.h)&&!o.s){o.s=!0;var l=o.Ga;Xn||xa(),Zn||(Xn(),Zn=!0),wi.add(l,o),o.B=0}}function vf(o,l){return eu(o.h)>=o.h.j-(o.s?1:0)?!1:o.s?(o.i=l.D.concat(o.i),!0):o.G==1||o.G==2||o.B>=(o.Va?0:o.Wa)?!1:(o.s=sr(_(o.Ga,o,l),Ru(o,o.B)),o.B++,!0)}r.Ga=function(o){if(this.s)if(this.s=null,this.G==1){if(!o){this.U=Math.floor(1e5*Math.random()),o=this.U++;const A=new ue(this,this.j,o);let S=this.o;if(this.S&&(S?(S=p(S),T(S,this.S)):S=this.S),this.m!==null||this.O||(A.H=S,S=null),this.P)t:{for(var l=0,d=0;d<this.i.length;d++){e:{var m=this.i[d];if("__data__"in m.map&&(m=m.map.__data__,typeof m=="string")){m=m.length;break e}m=void 0}if(m===void 0)break;if(l+=m,4096<l){l=d;break t}if(l===4096||d===this.i.length-1){l=d+1;break t}}l=1e3}else l=1e3;l=Tu(this,A,l),d=Yt(this.I),it(d,"RID",o),it(d,"CVER",22),this.D&&it(d,"X-HTTP-Session-Id",this.D),fr(this,d),S&&(this.O?l="headers="+encodeURIComponent(String(du(S)))+"&"+l:this.m&&ji(d,this.m,S)),qi(this.h,A),this.Ua&&it(d,"TYPE","init"),this.P?(it(d,"$req",l),it(d,"SID","null"),A.T=!0,Fi(A,d,null)):Fi(A,d,l),this.G=2}}else this.G==3&&(o?Eu(this,o):this.i.length==0||tu(this.h)||Eu(this))};function Eu(o,l){var d;l?d=l.l:d=o.U++;const m=Yt(o.I);it(m,"SID",o.K),it(m,"RID",d),it(m,"AID",o.T),fr(o,m),o.m&&o.o&&ji(m,o.m,o.o),d=new ue(o,o.j,d,o.B+1),o.m===null&&(d.H=o.o),l&&(o.i=l.D.concat(o.i)),l=Tu(o,d,1e3),d.I=Math.round(.5*o.wa)+Math.round(.5*o.wa*Math.random()),qi(o.h,d),Fi(d,m,l)}function fr(o,l){o.H&&K(o.H,function(d,m){it(l,m,d)}),o.l&&su({},function(d,m){it(l,m,d)})}function Tu(o,l,d){d=Math.min(o.i.length,d);var m=o.l?_(o.l.Na,o.l,o):null;t:{var A=o.i;let S=-1;for(;;){const M=["count="+d];S==-1?0<d?(S=A[0].g,M.push("ofs="+S)):S=0:M.push("ofs="+S);let rt=!0;for(let At=0;At<d;At++){let X=A[At].g;const Vt=A[At].map;if(X-=S,0>X)S=Math.max(0,A[At].g-100),rt=!1;else try{yf(Vt,M,"req"+X+"_")}catch{m&&m(Vt)}}if(rt){m=M.join("&");break t}}}return o=o.i.splice(0,d),l.D=o,m}function vu(o){if(!o.g&&!o.u){o.Y=1;var l=o.Fa;Xn||xa(),Zn||(Xn(),Zn=!0),wi.add(l,o),o.v=0}}function Gi(o){return o.g||o.u||3<=o.v?!1:(o.Y++,o.u=sr(_(o.Fa,o),Ru(o,o.v)),o.v++,!0)}r.Fa=function(){if(this.u=null,wu(this),this.ba&&!(this.M||this.g==null||0>=this.R)){var o=2*this.R;this.j.info("BP detection timer enabled: "+o),this.A=sr(_(this.ab,this),o)}},r.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,Ot(10),_s(this),wu(this))};function Ki(o){o.A!=null&&(u.clearTimeout(o.A),o.A=null)}function wu(o){o.g=new ue(o,o.j,"rpc",o.Y),o.m===null&&(o.g.H=o.o),o.g.O=0;var l=Yt(o.qa);it(l,"RID","rpc"),it(l,"SID",o.K),it(l,"AID",o.T),it(l,"CI",o.F?"0":"1"),!o.F&&o.ja&&it(l,"TO",o.ja),it(l,"TYPE","xmlhttp"),fr(o,l),o.m&&o.o&&ji(l,o.m,o.o),o.L&&(o.g.I=o.L);var d=o.g;o=o.ia,d.L=1,d.v=fs(Yt(l)),d.m=null,d.P=!0,Ja(d,o)}r.Za=function(){this.C!=null&&(this.C=null,_s(this),Gi(this),Ot(19))};function Is(o){o.C!=null&&(u.clearTimeout(o.C),o.C=null)}function Au(o,l){var d=null;if(o.g==l){Is(o),Ki(o),o.g=null;var m=2}else if(Ui(o.h,l))d=l.D,nu(o.h,l),m=1;else return;if(o.G!=0){if(l.o)if(m==1){d=l.m?l.m.length:0,l=Date.now()-l.F;var A=o.B;m=as(),Mt(m,new $a(m,d)),ys(o)}else vu(o);else if(A=l.s,A==3||A==0&&0<l.X||!(m==1&&vf(o,l)||m==2&&Gi(o)))switch(d&&0<d.length&&(l=o.h,l.i=l.i.concat(d)),A){case 1:Be(o,5);break;case 4:Be(o,10);break;case 3:Be(o,6);break;default:Be(o,2)}}}function Ru(o,l){let d=o.Ta+Math.floor(Math.random()*o.cb);return o.isActive()||(d*=2),d*l}function Be(o,l){if(o.j.info("Error code "+l),l==2){var d=_(o.fb,o),m=o.Xa;const A=!m;m=new Le(m||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||hs(m,"https"),fs(m),A?gf(m.toString(),d):pf(m.toString(),d)}else Ot(2);o.G=0,o.l&&o.l.sa(l),bu(o),Iu(o)}r.fb=function(o){o?(this.j.info("Successfully pinged google.com"),Ot(2)):(this.j.info("Failed to ping google.com"),Ot(1))};function bu(o){if(o.G=0,o.ka=[],o.l){const l=ru(o.h);(l.length!=0||o.i.length!=0)&&(V(o.ka,l),V(o.ka,o.i),o.h.i.length=0,N(o.i),o.i.length=0),o.l.ra()}}function Pu(o,l,d){var m=d instanceof Le?Yt(d):new Le(d);if(m.g!="")l&&(m.g=l+"."+m.g),ds(m,m.s);else{var A=u.location;m=A.protocol,l=l?l+"."+A.hostname:A.hostname,A=+A.port;var S=new Le(null);m&&hs(S,m),l&&(S.g=l),A&&ds(S,A),d&&(S.l=d),m=S}return d=o.D,l=o.ya,d&&l&&it(m,d,l),it(m,"VER",o.la),fr(o,m),m}function Su(o,l,d){if(l&&!o.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=o.Ca&&!o.pa?new ft(new ms({eb:d})):new ft(o.pa),l.Ha(o.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Vu(){}r=Vu.prototype,r.ua=function(){},r.ta=function(){},r.sa=function(){},r.ra=function(){},r.isActive=function(){return!0},r.Na=function(){};function Es(){}Es.prototype.g=function(o,l){return new Ut(o,l)};function Ut(o,l){St.call(this),this.g=new yu(l),this.l=o,this.h=l&&l.messageUrlParams||null,o=l&&l.messageHeaders||null,l&&l.clientProtocolHeaderRequired&&(o?o["X-Client-Protocol"]="webchannel":o={"X-Client-Protocol":"webchannel"}),this.g.o=o,o=l&&l.initMessageHeaders||null,l&&l.messageContentType&&(o?o["X-WebChannel-Content-Type"]=l.messageContentType:o={"X-WebChannel-Content-Type":l.messageContentType}),l&&l.va&&(o?o["X-WebChannel-Client-Profile"]=l.va:o={"X-WebChannel-Client-Profile":l.va}),this.g.S=o,(o=l&&l.Sb)&&!j(o)&&(this.g.m=o),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!j(l)&&(this.g.D=l,o=this.h,o!==null&&l in o&&(o=this.h,l in o&&delete o[l])),this.j=new hn(this)}C(Ut,St),Ut.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Ut.prototype.close=function(){zi(this.g)},Ut.prototype.o=function(o){var l=this.g;if(typeof o=="string"){var d={};d.__data__=o,o=d}else this.u&&(d={},d.__data__=Di(o),o=d);l.i.push(new sf(l.Ya++,o)),l.G==3&&ys(l)},Ut.prototype.N=function(){this.g.l=null,delete this.j,zi(this.g),delete this.g,Ut.aa.N.call(this)};function Cu(o){Ni.call(this),o.__headers__&&(this.headers=o.__headers__,this.statusCode=o.__status__,delete o.__headers__,delete o.__status__);var l=o.__sm__;if(l){t:{for(const d in l){o=d;break t}o=void 0}(this.i=o)&&(o=this.i,l=l!==null&&o in l?l[o]:void 0),this.data=l}else this.data=o}C(Cu,Ni);function Du(){ki.call(this),this.status=1}C(Du,ki);function hn(o){this.g=o}C(hn,Vu),hn.prototype.ua=function(){Mt(this.g,"a")},hn.prototype.ta=function(o){Mt(this.g,new Cu(o))},hn.prototype.sa=function(o){Mt(this.g,new Du)},hn.prototype.ra=function(){Mt(this.g,"b")},Es.prototype.createWebChannel=Es.prototype.g,Ut.prototype.send=Ut.prototype.o,Ut.prototype.open=Ut.prototype.m,Ut.prototype.close=Ut.prototype.close,_l=function(){return new Es},pl=function(){return as()},gl=Oe,ao={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},us.NO_ERROR=0,us.TIMEOUT=8,us.HTTP_ERROR=6,Vs=us,Qa.COMPLETE="complete",ml=Qa,ja.EventType=nr,nr.OPEN="a",nr.CLOSE="b",nr.ERROR="c",nr.MESSAGE="d",St.prototype.listen=St.prototype.K,Ir=ja,ft.prototype.listenOnce=ft.prototype.L,ft.prototype.getLastError=ft.prototype.Ka,ft.prototype.getLastErrorCode=ft.prototype.Ba,ft.prototype.getStatus=ft.prototype.Z,ft.prototype.getResponseJson=ft.prototype.Oa,ft.prototype.getResponseText=ft.prototype.oa,ft.prototype.send=ft.prototype.ea,ft.prototype.setWithCredentials=ft.prototype.Ha,fl=ft}).apply(typeof vs<"u"?vs:typeof self<"u"?self:typeof window<"u"?window:{});const zu="@firebase/firestore";class Et{constructor(t){this.uid=t}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(t){return t.uid===this.uid}}Et.UNAUTHENTICATED=new Et(null),Et.GOOGLE_CREDENTIALS=new Et("google-credentials-uid"),Et.FIRST_PARTY=new Et("first-party-uid"),Et.MOCK_USER=new Et("mock-user");let Bn="10.14.0";const Ee=new al("@firebase/firestore");function _n(){return Ee.logLevel}function eg(r){Ee.setLogLevel(r)}function x(r,...t){if(Ee.logLevel<=Y.DEBUG){const e=t.map(xo);Ee.debug(`Firestore (${Bn}): ${r}`,...e)}}
9function gt(r,...t){if(Ee.logLevel<=Y.ERROR){const e=t.map(xo);Ee.error(`Firestore (${Bn}): ${r}`,...e)}}function qt(r,...t){if(Ee.logLevel<=Y.WARN){const e=t.map(xo);Ee.warn(`Firestore (${Bn}): ${r}`,...e)}}function xo(r){if(typeof r=="string")return r;try{return(function(e){return JSON.stringify(e)})(r)}catch{return r}}function F(r="Unexpected state"){const t=`FIRESTORE (${Bn}) INTERNAL ASSERTION FAILED: `+r;throw gt(t),new Error(t)}function L(r,t){r||F()}function ng(r,t){r||F()}function k(r,t){return r}const P={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class D extends Ln{constructor(t,e){super(t,e),this.code=t,this.message=e,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Tt{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}}class yl{constructor(t,e){this.user=e,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${t}`)}}class Il{getToken(){return Promise.resolve(null)}invalidateToken(){}start(t,e){t.enqueueRetryable((()=>e(Et.UNAUTHENTICATED)))}shutdown(){}}class rg{constructor(t){this.token=t,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(t,e){this.changeListener=e,t.enqueueRetryable((()=>e(this.token.user)))}shutdown(){this.changeListener=null}}class sg{constructor(t){this.t=t,this.currentUser=Et.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,e){L(this.o===void 0);let n=this.i;const s=c=>this.i!==n?(n=this.i,e(c)):Promise.resolve();let i=new Tt;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Tt,t.enqueueRetryable((()=>s(this.currentUser)))};const a=()=>{const c=i;t.enqueueRetryable((async()=>{await c.promise,await s(this.currentUser)}))},u=c=>{x("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=c,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit((c=>u(c))),setTimeout((()=>{if(!this.auth){const c=this.t.getImmediate({optional:!0});c?u(c):(x("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Tt)}}),0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then((n=>this.i!==t?(x("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):n?(L(typeof n.accessToken=="string"),new yl(n.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const t=this.auth&&this.auth.getUid();return L(t===null||typeof t=="string"),new Et(t)}}class ig{constructor(t,e,n){this.l=t,this.h=e,this.P=n,this.type="FirstParty",this.user=Et.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const t=this.T();return t&&this.I.set("Authorization",t),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class og{constructor(t,e,n){this.l=t,this.h=e,this.P=n}getToken(){return Promise.resolve(new ig(this.l,this.h,this.P))}start(t,e){t.enqueueRetryable((()=>e(Et.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class El{constructor(t){this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class ag{constructor(t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,e){L(this.o===void 0);const n=i=>{i.error!=null&&x("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);const a=i.token!==this.R;return this.R=i.token,x("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?e(i.token):Promise.resolve()};this.o=i=>{t.enqueueRetryable((()=>
9n(i)))};const s=i=>{x("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit((i=>s(i))),setTimeout((()=>{if(!this.appCheck){const i=this.A.getImmediate({optional:!0});i?s(i):x("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then((e=>e?(L(typeof e.token=="string"),this.R=e.token,new El(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class ug{getToken(){return Promise.resolve(new El(""))}invalidateToken(){}start(t,e){}shutdown(){}}function cg(r){const t=typeof self<"u"&&(self.crypto||self.msCrypto),e=new Uint8Array(r);if(t&&typeof t.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<r;n++)e[n]=Math.floor(256*Math.random());return e}class No{static newId(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=Math.floor(256/t.length)*t.length;let n="";for(;n.length<20;){const s=cg(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<e&&(n+=t.charAt(s[i]%t.length))}return n}}function z(r,t){return r<t?-1:r>t?1:0}function wn(r,t,e){return r.length===t.length&&r.every(((n,s)=>e(n,t[s])))}function Tl(r){return r+"\0"}class lt{constructor(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}static now(){return lt.fromMillis(Date.now())}static fromDate(t){return lt.fromMillis(t.getTime())}static fromMillis(t){const e=Math.floor(t/1e3),n=Math.floor(1e6*(t-1e3*e));return new lt(e,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(t){return this.seconds===t.seconds?z(this.nanoseconds,t.nanoseconds):z(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const t=this.seconds- -62135596800;return String(t).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class U{constructor(t){this.timestamp=t}static fromTimestamp(t){return new U(t)}static min(){return new U(new lt(0,0))}static max(){return new U(new lt(253402300799,999999999))}compareTo(t){return this.timestamp._compareTo(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class xr{constructor(t,e,n){e===void 0?e=0:e>t.length&&F(),n===void 0?n=t.length-e:n>t.length-e&&F(),this.segments=t,this.offset=e,this.len=n}get length(){return this.len}isEqual(t){return xr.comparator(this,t)===0}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof xr?t.forEach((n=>{e.push(n)})):e.push(t),this.construct(e)}limit(){return this.offset+this.length}popFirst(t){return t=t===void 0?1:t,this.construct(this.segments,this.offset+t,this.length-t)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(t){return this.segments[this.offset+t]}isEmpty(){return this.length===0}isPrefixOf(t){if(t.length<this.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}isImmediateParentOf(t){if(this.length+1!==t.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}forEach(t){for(let e=this.offset,n=this.limit();e<n;e++)t(this.segments[e])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(t,e){const n=Math.min(t.length,e.length);for(let s=0;s<n;s++){const i=t.get(s),a=e.get(s);if(i<a)return-1;if(i>a)return 1}return t.length<e.length?-1:t.length>e.length?1:0}}class W extends xr{construct(t,e,n){return new W(t,e,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}
9toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...t){const e=[];for(const n of t){if(n.indexOf("//")>=0)throw new D(P.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);e.push(...n.split("/").filter((s=>s.length>0)))}return new W(e)}static emptyPath(){return new W([])}}const lg=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class at extends xr{construct(t,e,n){return new at(t,e,n)}static isValidIdentifier(t){return lg.test(t)}canonicalString(){return this.toArray().map((t=>(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),at.isValidIdentifier(t)||(t="`"+t+"`"),t))).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)==="__name__"}static keyField(){return new at(["__name__"])}static fromServerFormat(t){const e=[];let n="",s=0;const i=()=>{if(n.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(n),n=""};let a=!1;for(;s<t.length;){const u=t[s];if(u==="\\"){if(s+1===t.length)throw new D(P.INVALID_ARGUMENT,"Path has trailing escape character: "+t);const c=t[s+1];if(c!=="\\"&&c!=="."&&c!=="`")throw new D(P.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);n+=c,s+=2}else u==="`"?(a=!a,s++):u!=="."||a?(n+=u,s++):(i(),s++)}if(i(),a)throw new D(P.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new at(e)}static emptyPath(){return new at([])}}class O{constructor(t){this.path=t}static fromPath(t){return new O(W.fromString(t))}static fromName(t){return new O(W.fromString(t).popFirst(5))}static empty(){return new O(W.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(t){return this.path.length>=2&&this.path.get(this.path.length-2)===t}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(t){return t!==null&&W.comparator(this.path,t.path)===0}toString(){return this.path.toString()}static comparator(t,e){return W.comparator(t.path,e.path)}static isDocumentKey(t){return t.length%2==0}static fromSegments(t){return new O(new W(t.slice()))}}class An{constructor(t,e,n,s){this.indexId=t,this.collectionGroup=e,this.fields=n,this.indexState=s}}function uo(r){return r.fields.find((t=>t.kind===2))}function je(r){return r.fields.filter((t=>t.kind!==2))}function hg(r,t){let e=z(r.collectionGroup,t.collectionGroup);if(e!==0)return e;for(let n=0;n<Math.min(r.fields.length,t.fields.length);++n)if(e=dg(r.fields[n],t.fields[n]),e!==0)return e;return z(r.fields.length,t.fields.length)}An.UNKNOWN_ID=-1;class We{constructor(t,e){this.fieldPath=t,this.kind=e}}function dg(r,t){const e=at.comparator(r.fieldPath,t.fieldPath);return e!==0?e:z(r.kind,t.kind)}class Rn{constructor(t,e){this.sequenceNumber=t,this.offset=e}static empty(){return new Rn(0,jt.min())}}function vl(r,t){const e=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=U.fromTimestamp(n===1e9?new lt(e+1,0):new lt(e,n));return new jt(s,O.empty(),t)}function wl(r){return new jt(r.readTime,r.key,-1)}class jt{constructor(t,e,n){this.readTime=t,this.documentKey=e,this.largestBatchId=n}static min(){return new jt(U.min(),O.empty(),-1)}static max(){return new jt(U.max(),O.empty(),-1)}}function ko(r,t){let e=r.readTime.compareTo(t.readTime);return e!==0?e:(e=O.comparator(r.documentKey,t.documentKey),e!==0?e:z(r.largestBatchId,t.largestBatchId))}const Al="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Rl{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(t){this.onCommittedListeners.push(t)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((t=>t()))}}async function Ve(r){if(r.code!==P.FAILED_PRECONDITION||r.message!==Al)throw r;x("LocalStore","Unexpectedly lost primary lease")}class w{constructor(t){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(t){return this.next(void 0,t)}next(t,e){return this.callbackAttached&&F(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(e,this.error):this.wrapSuccess(t,this.result):new w(((n,s)=>{this.nextCallback=i=>{this.wrapSuccess(t,i).next(n,s)},this.catchCallback=i=>{this.wrapFailure(e,i).next(n,s)}}))}toPromise(){return new Promise(((t,e)=>{this.next(t,e)}))}wrapUserFunction(t){try{const e=t();return e instanceof w?e:w.resolve(e)}catch(e){return w.reject(e)}}wrapSuccess(t,e){return t?this.wrapUserFunction((()=>t(e))):w.resolve(e)}wrapFailure(t,e){return t?this.wrapUserFunction((()=>t(e))):w.reject(e)}static resolve(t){return new w(((e,n)=>{e(t)}))}static reject(t){return new w(((e,n)=>{n(t)}))}static waitFor(t){return new w(((e,n)=>{let s=0,i=0,a=!1;t.forEach((u=>{++s,u.next((()=>{++i,a&&i===s&&e()}),(c=>n(c)))})),a=!0,i===s&&e()}))}static or(t){let e=w.resolve(!1);for(const n of t)e=e.next((s=>s?w.resolve(s):n()));return e}static forEach(t,e){const n=[];return t.forEach(((s,i)=>{n.push(e.call(this,s,i))})),this.waitFor(n)}static mapArray(t,e){return new w(((n,s)=>{const i=t.length,a=new Array(i);let u=0;for(let c=0;c<i;c++){const h=c;e(t[h]).next((f=>{a[h]=f,++u,u===i&&n(a)}),(f=>s(f)))}}))}static doWhile(t,e){return new w(((n,s)=>{const i=()=>{t()===!0?e().next((()=>{i()}),s):n()};i()}))}}class ei{constructor(t,e){this.action=t,this.transaction=e,this.aborted=!1,this.V=new Tt,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{e.error?this.V.reject(new Ar(t,e.error)):this.V.resolve()},this.transaction.onerror=n=>{const s=Mo(n.target.error);this.V.reject(new Ar(t,s))}}static open(t,e,n,s){try{return new ei(e,t.transaction(s,n))}catch(i){throw new Ar(e,i)}}get m(){return this.V.promise}abort(t){t&&this.V.reject(t),this.aborted||(x("SimpleDb","Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const t=this.transaction;this.aborted||typeof t.commit!="function"||t.commit()}store(t){const e=this.transaction.objectStore(t);return new mg(e)}}class Qt{constructor(t,e,n){this.name=t,this.version=e,this.p=n,Qt.S(Ls())===12.2&>("Firestore persistence suffers from a bug in
9iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(t){return x("SimpleDb","Removing database:",t),ze(window.indexedDB.deleteDatabase(t)).toPromise()}static D(){if(!il())return!1;if(Qt.v())return!0;const t=Ls(),e=Qt.S(t),n=0<e&&e<10,s=bl(t),i=0<s&&s<4.5;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0||n||i)}static v(){var t;return typeof process<"u"&&((t=process.__PRIVATE_env)===null||t===void 0?void 0:t.C)==="YES"}static F(t,e){return t.store(e)}static S(t){const e=t.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=e?e[1].split("_").slice(0,2).join("."):"-1";return Number(n)}async M(t){return this.db||(x("SimpleDb","Opening database:",this.name),this.db=await new Promise(((e,n)=>{const s=indexedDB.open(this.name,this.version);s.onsuccess=i=>{const a=i.target.result;e(a)},s.onblocked=()=>{n(new Ar(t,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=i=>{const a=i.target.error;a.name==="VersionError"?n(new D(P.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):a.name==="InvalidStateError"?n(new D(P.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+a)):n(new Ar(t,a))},s.onupgradeneeded=i=>{x("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',i.oldVersion);const a=i.target.result;this.p.O(a,s.transaction,i.oldVersion,this.version).next((()=>{x("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(t){this.N=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(t,e,n,s){const i=e==="readonly";let a=0;for(;;){++a;try{this.db=await this.M(t);const u=ei.open(this.db,t,i?"readonly":"readwrite",n),c=s(u).next((h=>(u.g(),h))).catch((h=>(u.abort(h),w.reject(h)))).toPromise();return c.catch((()=>{})),await u.m,c}catch(u){const c=u,h=c.name!=="FirebaseError"&&a<3;if(x("SimpleDb","Transaction failed with error:",c.message,"Retrying:",h),this.close(),!h)return Promise.reject(c)}}}close(){this.db&&this.db.close(),this.db=void 0}}function bl(r){const t=r.match(/Android ([\d.]+)/i),e=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(e)}class fg{constructor(t){this.B=t,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(t){this.B=t}done(){this.k=!0}$(t){this.q=t}delete(){return ze(this.B.delete())}}class Ar extends D{constructor(t,e){super(P.UNAVAILABLE,`IndexedDB transaction '${t}' failed: ${e}`),this.name="IndexedDbTransactionError"}}function Ce(r){return r.name==="IndexedDbTransactionError"}class mg{constructor(t){this.store=t}put(t,e){let n;return e!==void 0?(x("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(x("SimpleDb","PUT",this.store.name,"<auto-key>",t),n=this.store.put(t)),ze(n)}add(t){return x("SimpleDb","ADD",this.store.name,t,t),ze(this.store.add(t))}get(t){return ze(this.store.get(t)).next((e=>(e===void 0&&(e=null),x("SimpleDb","GET",this.store.name,t,e),e)))}delete(t){return x("SimpleDb","DELETE",this.store.name,t),ze(this.store.delete(t))}count(){return x("SimpleDb","COUNT",this.store.name),ze(this.store.count())}U(t,e){const n=this.options(t,e),s=n.index?this.store.index(n.index):this.store;if(typeof s.getAll=="function"){const i=s.getAll(n.range);return new w(((a,u)=>{i.onerror=c=>{u(c.target.error)},i.onsuccess=c=>{a(c.target.result)}}))}{const i=this.cursor(n),a=[];return this.W(i,((u,c)=>{a.push(c)})).next((()=>a))}}G(t,e){const n=this.store.getAll(t,e===null?void 0:e);return new w(((s,i)=>{n.onerror=a=>{i(a.target.error)},n.onsuccess=a=>{s(a.target.result)}}))}j(t,e){x("SimpleDb","DELETE ALL",this.store.name);const n=this.options(t,e);n.H=!1;const s=this.cursor(n);return this.W(s,((i,a,u)=>u.delete()))}J(t,e){let n;e?n=t:(n={},e=t);const s=this.cursor(n);return this.W(s,e)}Y(t){const e=this.cursor({});return new w(((n,s)=>{e.onerror=i=>{const a=Mo(i.target.error);s(a)},e.onsuccess=i=>{const a=i.target.result;a?t(a.primaryKey,a.value).next((u=>{u?a.continue():n()})):n()}}))}W(t,e){const n=[];return new w(((s,i)=>{t.onerror=a=>{i(a.target.error)},t.onsuccess=a=>{const u=a.target.result;if(!u)return void s();const c=new fg(u),h=e(u.primaryKey,u.value,c);if(h instanceof w){const f=h.catch((g=>(c.done(),w.reject(g))));n.push(f)}c.isDone?s():c.K===null?u.continue():u.continue(c.K)}})).next((()=>w.waitFor(n)))}options(t,e){let n;return t!==void 0&&(typeof t=="string"?n=t:e=t),{index:n,range:e}}cursor(t){let e="next";if(t.reverse&&(e="prev"),t.index){const n=this.store.index(t.index);return t.H?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)}}function ze(r){return new w(((t,e)=>{r.onsuccess=n=>{const s=n.target.result;t(s)},r.onerror=n=>{const s=Mo(n.target.error);e(s)}}))}let Gu=!1;function Mo(r){const t=Qt.S(Ls());if(t>=12.2&&t<13){const e="An internal error was encountered in the Indexed Database server";if(r.message.indexOf(e)>=0){const n=new D("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Gu||(Gu=!0,setTimeout((()=>{throw n}),0)),n}}return r}class gg{constructor(t,e){this.asyncQueue=t,this.Z=e,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return this.task!==null}X(t){x("IndexBackfiller",`Scheduled in ${t}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",t,(async()=>{this.task=null;try{x("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){Ce(e)?x("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await Ve(e)}await this.X(6e4)}))}}class pg{constructor(t,e){this.localStore=t,this.persistence=e}async ee(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(e=>this.te(e,t)))}te(t,e){const n=new Set;let s=e,i=!0;
9return w.doWhile((()=>i===!0&&s>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((a=>{if(a!==null&&!n.has(a))return x("IndexBackfiller",`Processing collection: ${a}`),this.ne(t,a,s).next((u=>{s-=u,n.add(a)}));i=!1})))).next((()=>e-s))}ne(t,e,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t,e).next((s=>this.localStore.localDocuments.getNextDocuments(t,e,s,n).next((i=>{const a=i.changes;return this.localStore.indexManager.updateIndexEntries(t,a).next((()=>this.re(s,i))).next((u=>(x("IndexBackfiller",`Updating offset: ${u}`),this.localStore.indexManager.updateCollectionGroup(t,e,u)))).next((()=>a.size))}))))}re(t,e){let n=t;return e.changes.forEach(((s,i)=>{const a=wl(i);ko(a,n)>0&&(n=a)})),new jt(n.readTime,n.documentKey,Math.max(e.batchId,t.largestBatchId))}}class Ft{constructor(t,e){this.previousValue=t,e&&(e.sequenceNumberHandler=n=>this.ie(n),this.se=n=>e.writeSequenceNumber(n))}ie(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){const t=++this.previousValue;return this.se&&this.se(t),t}}Ft.oe=-1;function jr(r){return r==null}function Nr(r){return r===0&&1/r==-1/0}function Pl(r){return typeof r=="number"&&Number.isInteger(r)&&!Nr(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}function Nt(r){let t="";for(let e=0;e<r.length;e++)t.length>0&&(t=Ku(t)),t=_g(r.get(e),t);return Ku(t)}function _g(r,t){let e=t;const n=r.length;for(let s=0;s<n;s++){const i=r.charAt(s);switch(i){case"\0":e+="��";break;case"�":e+="��";break;default:e+=i}}return e}function Ku(r){return r+"��"}function Kt(r){const t=r.length;if(L(t>=2),t===2)return L(r.charAt(0)==="�"&&r.charAt(1)==="�"),W.emptyPath();const e=t-2,n=[];let s="";for(let i=0;i<t;){const a=r.indexOf("�",i);switch((a<0||a>e)&&F(),r.charAt(a+1)){case"�":const u=r.substring(i,a);let c;s.length===0?c=u:(s+=u,c=s,s=""),n.push(c);break;case"�":s+=r.substring(i,a),s+="\0";break;case"�":s+=r.substring(i,a+1);break;default:F()}i=a+2}return new W(n)}const $u=["userId","batchId"];function Cs(r,t){return[r,Nt(t)]}function Sl(r,t,e){return[r,Nt(t),e]}const yg={},Ig=["prefixPath","collectionGroup","readTime","documentId"],Eg=["prefixPath","collectionGroup","documentId"],Tg=["collectionGroup","readTime","prefixPath","documentId"],vg=["canonicalId","targetId"],wg=["targetId","path"],Ag=["path","targetId"],Rg=["collectionId","parent"],bg=["indexId","uid"],Pg=["uid","sequenceNumber"],Sg=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Vg=["indexId","uid","orderedDocumentKey"],Cg=["userId","collectionPath","documentId"],Dg=["userId","collectionPath","largestBatchId"],xg=["userId","collectionGroup","largestBatchId"],Vl=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],Ng=[...Vl,"documentOverlays"],Cl=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Dl=Cl,Oo=[...Dl,"indexConfiguration","indexState","indexEntries"],kg=Oo,Mg=[...Oo,"globals"];class co extends Rl{constructor(t,e){super(),this._e=t,this.currentSequenceNumber=e}}function yt(r,t){const e=k(r);return Qt.F(e._e,t)}function Qu(r){let t=0;for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&t++;return t}function De(r,t){for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&t(e,r[e])}function xl(r,t){const e=[];for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.push(t(r[n],n,r));return e}function Nl(r){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t))return!1;return!0}class st{constructor(t,e){this.comparator=t,this.root=e||Rt.EMPTY}insert(t,e){return new st(this.comparator,this.root.insert(t,e,this.comparator).copy(null,null,Rt.BLACK,null,null))}remove(t){return new st(this.comparator,this.root.remove(t,this.comparator).copy(null,null,Rt.BLACK,null,null))}get(t){let e=this.root;for(;!e.isEmpty();){const n=this.comparator(t,e.key);if(n===0)return e.value;n<0?e=e.left:n>0&&(e=e.right)}return null}indexOf(t){let e=0,n=this.root;for(;!n.isEmpty();){const s=this.comparator(t,n.key);if(s===0)return e+n.left.size;s<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(t){return this.root.inorderTraversal(t)}forEach(t){this.inorderTraversal(((e,n)=>(t(e,n),!1)))}toString(){const t=[];return this.inorderTraversal(((e,n)=>(t.push(`${e}:${n}`),!1))),`{${t.join(", ")}}`}reverseTraversal(t){return this.root.reverseTraversal(t)}getIterator(){return new ws(this.root,null,this.comparator,!1)}getIteratorFrom(t){return new ws(this.root,t,this.comparator,!1)}getReverseIterator(){return new ws(this.root,null,this.comparator,!0)}getReverseIteratorFrom(t){return new ws(this.root,t,this.comparator,!0)}}class ws{constructor(t,e,n,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!t.isEmpty();)if(i=e?n(t.key,e):1,e&&s&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(i===0){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}getNext(){let t=this.nodeStack.pop();const e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e}hasNext(){return this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;const t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}}}class Rt{constructor(t,e,n,s,i){this.key=t,this.value=e,this.color=n??Rt.RED,this.left=s??Rt.EMPTY,this.right=i??Rt.EMPTY,this.size=this.left.size+1+this.right.size}
9copy(t,e,n,s,i){return new Rt(t??this.key,e??this.value,n??this.color,s??this.left,i??this.right)}isEmpty(){return!1}inorderTraversal(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)}reverseTraversal(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(t,e,n){let s=this;const i=n(t,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(t,e,n),null):i===0?s.copy(null,e,null,null,null):s.copy(null,null,null,null,s.right.insert(t,e,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return Rt.EMPTY;let t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),t=t.copy(null,null,null,t.left.removeMin(),null),t.fixUp()}remove(t,e){let n,s=this;if(e(t,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(t,e),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),e(t,s.key)===0){if(s.right.isEmpty())return Rt.EMPTY;n=s.right.min(),s=s.copy(n.key,n.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(t,e))}return s.fixUp()}isRed(){return this.color}fixUp(){let t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t}moveRedLeft(){let t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t}moveRedRight(){let t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t}rotateLeft(){const t=this.copy(null,null,Rt.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight(){const t=this.copy(null,null,Rt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip(){const t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)}checkMaxDepth(){const t=this.check();return Math.pow(2,t)<=this.size+1}check(){if(this.isRed()&&this.left.isRed()||this.right.isRed())throw F();const t=this.left.check();if(t!==this.right.check())throw F();return t+(this.isRed()?0:1)}}Rt.EMPTY=null,Rt.RED=!0,Rt.BLACK=!1;Rt.EMPTY=new class{constructor(){this.size=0}get key(){throw F()}get value(){throw F()}get color(){throw F()}get left(){throw F()}get right(){throw F()}copy(t,e,n,s,i){return this}insert(t,e,n){return new Rt(t,e)}remove(t,e){return this}isEmpty(){return!0}inorderTraversal(t){return!1}reverseTraversal(t){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class et{constructor(t){this.comparator=t,this.data=new st(this.comparator)}has(t){return this.data.get(t)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(t){return this.data.indexOf(t)}forEach(t){this.data.inorderTraversal(((e,n)=>(t(e),!1)))}forEachInRange(t,e){const n=this.data.getIteratorFrom(t[0]);for(;n.hasNext();){const s=n.getNext();if(this.comparator(s.key,t[1])>=0)return;e(s.key)}}forEachWhile(t,e){let n;for(n=e!==void 0?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return}firstAfterOrEqual(t){const e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null}getIterator(){return new Wu(this.data.getIterator())}getIteratorFrom(t){return new Wu(this.data.getIteratorFrom(t))}add(t){return this.copy(this.data.remove(t).insert(t,!0))}delete(t){return this.has(t)?this.copy(this.data.remove(t)):this}isEmpty(){return this.data.isEmpty()}unionWith(t){let e=this;return e.size<t.size&&(e=t,t=this),t.forEach((n=>{e=e.add(n)})),e}isEqual(t){if(!(t instanceof et)||this.size!==t.size)return!1;const e=this.data.getIterator(),n=t.data.getIterator();for(;e.hasNext();){const s=e.getNext().key,i=n.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){const t=[];return this.forEach((e=>{t.push(e)})),t}toString(){const t=[];return this.forEach((e=>t.push(e))),"SortedSet("+t.toString()+")"}copy(t){const e=new et(this.comparator);return e.data=t,e}}
9class Wu{constructor(t){this.iter=t}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function fn(r){return r.hasNext()?r.getNext():void 0}class Lt{constructor(t){this.fields=t,t.sort(at.comparator)}static empty(){return new Lt([])}unionWith(t){let e=new et(at.comparator);for(const n of this.fields)e=e.add(n);for(const n of t)e=e.add(n);return new Lt(e.toArray())}covers(t){for(const e of this.fields)if(e.isPrefixOf(t))return!0;return!1}isEqual(t){return wn(this.fields,t.fields,((e,n)=>e.isEqual(n)))}}class kl extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}function Og(){return typeof atob<"u"}class dt{constructor(t){this.binaryString=t}static fromBase64String(t){const e=(function(s){try{return atob(s)}catch(i){throw typeof DOMException<"u"&&i instanceof DOMException?new kl("Invalid base64 string: "+i):i}})(t);return new dt(e)}static fromUint8Array(t){const e=(function(s){let i="";for(let a=0;a<s.length;++a)i+=String.fromCharCode(s[a]);return i})(t);return new dt(e)}[Symbol.iterator](){let t=0;return{next:()=>t<this.binaryString.length?{value:this.binaryString.charCodeAt(t++),done:!1}:{value:void 0,done:!0}}}toBase64(){return(function(e){return btoa(e)})(this.binaryString)}toUint8Array(){return(function(e){const n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n})(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(t){return z(this.binaryString,t.binaryString)}isEqual(t){return this.binaryString===t.binaryString}}dt.EMPTY_BYTE_STRING=new dt("");const Fg=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ee(r){if(L(!!r),typeof r=="string"){let t=0;const e=Fg.exec(r);if(L(!!e),e[1]){let s=e[1];s=(s+"000000000").substr(0,9),t=Number(s)}const n=new Date(r);return{seconds:Math.floor(n.getTime()/1e3),nanos:t}}return{seconds:ut(r.seconds),nanos:ut(r.nanos)}}function ut(r){return typeof r=="number"?r:typeof r=="string"?Number(r):0}function ne(r){return typeof r=="string"?dt.fromBase64String(r):dt.fromUint8Array(r)}function ni(r){var t,e;return((e=(((t=r?.mapValue)===null||t===void 0?void 0:t.fields)||{}).__type__)===null||e===void 0?void 0:e.stringValue)==="server_timestamp"}function ri(r){const t=r.mapValue.fields.__previous_value__;return ni(t)?ri(t):t}function kr(r){const t=ee(r.mapValue.fields.__local_write_time__.timestampValue);return new lt(t.seconds,t.nanos)}class Lg{constructor(t,e,n,s,i,a,u,c,h){this.databaseId=t,this.appId=e,this.persistenceKey=n,this.host=s,this.ssl=i,this.forceLongPolling=a,this.autoDetectLongPolling=u,this.longPollingOptions=c,this.useFetchStreams=h}}class Te{constructor(t,e){this.projectId=t,this.database=e||"(default)"}static empty(){return new Te("","")}get isDefaultDatabase(){return this.database==="(default)"}isEqual(t){return t instanceof Te&&t.projectId===this.projectId&&t.database===this.database}}const pe={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ds={nullValue:"NULL_VALUE"};function ve(r){return"nullValue"in r?0:"booleanValue"in r?1:"integerValue"in r||"doubleValue"in r?2:"timestampValue"in r?3:"stringValue"in r?5:"bytesValue"in r?6:"referenceValue"in r?7:"geoPointValue"in r?8:"arrayValue"in r?9:"mapValue"in r?ni(r)?4:Ml(r)?9007199254740991:si(r)?10:11:F()}function Ht(r,t){if(r===t)return!0;const e=ve(r);if(e!==ve(t))return!1;switch(e){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===t.booleanValue;case 4:return kr(r).isEqual(kr(t));case 3:return(function(s,i){if(typeof s.timestampValue=="string"&&typeof i.timestampValue=="string"&&s.timestampValue.length===i.timestampValue.length)return s.timestampValue===i.timestampValue;const a=ee(s.timestampValue),u=ee(i.timestampValue);return a.seconds===u.seconds&&a.nanos===u.nanos})(r,t);case 5:return r.stringValue===t.stringValue;case 6:return(function(s,i){return ne(s.bytesValue).isEqual(ne(i.bytesValue))})(r,t);case 7:return r.referenceValue===t.referenceValue;case 8:return(function(s,i){return ut(s.geoPointValue.latitude)===ut(i.geoPointValue.latitude)&&ut(s.geoPointValue.longitude)===ut(i.geoPointValue.longitude)})(r,t);
9case 2:return(function(s,i){if("integerValue"in s&&"integerValue"in i)return ut(s.integerValue)===ut(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){const a=ut(s.doubleValue),u=ut(i.doubleValue);return a===u?Nr(a)===Nr(u):isNaN(a)&&isNaN(u)}return!1})(r,t);case 9:return wn(r.arrayValue.values||[],t.arrayValue.values||[],Ht);case 10:case 11:return(function(s,i){const a=s.mapValue.fields||{},u=i.mapValue.fields||{};if(Qu(a)!==Qu(u))return!1;for(const c in a)if(a.hasOwnProperty(c)&&(u[c]===void 0||!Ht(a[c],u[c])))return!1;return!0})(r,t);default:return F()}}function Mr(r,t){return(r.values||[]).find((e=>Ht(e,t)))!==void 0}function we(r,t){if(r===t)return 0;const e=ve(r),n=ve(t);if(e!==n)return z(e,n);switch(e){case 0:case 9007199254740991:return 0;case 1:return z(r.booleanValue,t.booleanValue);case 2:return(function(i,a){const u=ut(i.integerValue||i.doubleValue),c=ut(a.integerValue||a.doubleValue);return u<c?-1:u>c?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1})(r,t);case 3:return Hu(r.timestampValue,t.timestampValue);case 4:return Hu(kr(r),kr(t));case 5:return z(r.stringValue,t.stringValue);
9case 6:return(function(i,a){const u=ne(i),c=ne(a);return u.compareTo(c)})(r.bytesValue,t.bytesValue);case 7:return(function(i,a){const u=i.split("/"),c=a.split("/");for(let h=0;h<u.length&&h<c.length;h++){const f=z(u[h],c[h]);if(f!==0)return f}return z(u.length,c.length)})(r.referenceValue,t.referenceValue);case 8:return(function(i,a){const u=z(ut(i.latitude),ut(a.latitude));return u!==0?u:z(ut(i.longitude),ut(a.longitude))})(r.geoPointValue,t.geoPointValue);case 9:return Ju(r.arrayValue,t.arrayValue);case 10:return(function(i,a){var u,c,h,f;const g=i.fields||{},_=a.fields||{},R=(u=g.value)===null||u===void 0?void 0:u.arrayValue,C=(c=_.value)===null||c===void 0?void 0:c.arrayValue,N=z(((h=R?.values)===null||h===void 0?void 0:h.length)||0,((f=C?.values)===null||f===void 0?void 0:f.length)||0);return N!==0?N:Ju(R,C)})(r.mapValue,t.mapValue);case 11:return(function(i,a){if(i===pe.mapValue&&a===pe.mapValue)return 0;if(i===pe.mapValue)return 1;if(a===pe.mapValue)return-1;const u=i.fields||{},c=Object.keys(u),h=a.fields||{},f=Object.keys(h);c.sort(),f.sort();for(let g=0;g<c.length&&g<f.length;++g){const _=z(c[g],f[g]);if(_!==0)return _;const R=we(u[c[g]],h[f[g]]);if(R!==0)return R}return z(c.length,f.length)})(r.mapValue,t.mapValue);default:throw F()}}function Hu(r,t){if(typeof r=="string"&&typeof t=="string"&&r.length===t.length)return z(r,t);const e=ee(r),n=ee(t),s=z(e.seconds,n.seconds);return s!==0?s:z(e.nanos,n.nanos)}function Ju(r,t){const e=r.values||[],n=t.values||[];for(let s=0;s<e.length&&s<n.length;++s){const i=we(e[s],n[s]);if(i)return i}return z(e.length,n.length)}function bn(r){return lo(r)}function lo(r){return"nullValue"in r?"null":"booleanValue"in r?""+r.booleanValue:"integerValue"in r?""+r.integerValue:"doubleValue"in r?""+r.doubleValue:"timestampValue"in r?(function(e){const n=ee(e);return`time(${n.seconds},${n.nanos})`})(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?(function(e){return ne(e).toBase64()})(r.bytesValue):"referenceValue"in r?(function(e){return O.fromName(e).toString()})(r.referenceValue):"geoPointValue"in r?(function(e){return`geo(${e.latitude},${e.longitude})`})(r.geoPointValue):"arrayValue"in r?(function(e){let n="[",s=!0;for(const i of e.values||[])s?s=!1:n+=",",n+=lo(i);return n+"]"})(r.arrayValue):"mapValue"in r?(function(e){const n=Object.keys(e.fields||{}).sort();let s="{",i=!0;for(const a of n)i?i=!1:s+=",",s+=`${a}:${lo(e.fields[a])}`;return s+"}"})(r.mapValue):F()}function xs(r){switch(ve(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const t=ri(r);return t?16+xs(t):16;case 5:return 2*r.stringValue.length;case 6:return ne(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return(function(n){return(n.values||[]).reduce(((s,i)=>s+xs(i)),0)})(r.arrayValue);case 10:case 11:return(function(n){let s=0;return De(n.fields,((i,a)=>{s+=i.length+xs(a)})),s})(r.mapValue);default:throw F()}}function Je(r,t){return{referenceValue:`projects/${r.projectId}/databases/${r.database}/documents/${t.path.canonicalString()}`}}function ho(r){return!!r&&"integerValue"in r}function Or(r){return!!r&&"arrayValue"in r}function Yu(r){return!!r&&"nullValue"in r}function Xu(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function Ns(r){return!!r&&"mapValue"in r}function si(r){var t,e;return((e=(((t=r?.mapValue)===null||t===void 0?void 0:t.fields)||{}).__type__)===null||e===void 0?void 0:e.stringValue)==="__vector__"}function Rr(r){if(r.geoPointValue)return{geoPointValue:Object.assign({},r.geoPointValue)};if(r.timestampValue&&typeof r.timestampValue=="object")return{timestampValue:Object.assign({},r.timestampValue)};if(r.mapValue){const t={mapValue:{fields:{}}};return De(r.mapValue.fields,((e,n)=>t.mapValue.fields[e]=Rr(n))),t}if(r.arrayValue){const t={arrayValue:{values:[]}};for(let e=0;e<(r.arrayValue.values||[]).length;++e)t.arrayValue.values[e]=Rr(r.arrayValue.values[e]);return t}return Object.assign({},r)}function Ml(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue==="__max__"}const Ol={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Bg(r){return"nullValue"in r?Ds:"booleanValue"in r?{booleanValue:!1}:"integerValue"in r||"doubleValue"in r?{doubleValue:NaN}:"timestampValue"in r?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in r?{stringValue:""}
9:"bytesValue"in r?{bytesValue:""}:"referenceValue"in r?Je(Te.empty(),O.empty()):"geoPointValue"in r?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in r?{arrayValue:{}}:"mapValue"in r?si(r)?Ol:{mapValue:{}}:F()}function Ug(r){return"nullValue"in r?{booleanValue:!1}:"booleanValue"in r?{doubleValue:NaN}:"integerValue"in r||"doubleValue"in r?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in r?{stringValue:""}:"stringValue"in r?{bytesValue:""}:"bytesValue"in r?Je(Te.empty(),O.empty()):"referenceValue"in r?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in r?{arrayValue:{}}:"arrayValue"in r?Ol:"mapValue"in r?si(r)?{mapValue:{}}:pe:F()}function Zu(r,t){const e=we(r.value,t.value);return e!==0?e:r.inclusive&&!t.inclusive?-1:!r.inclusive&&t.inclusive?1:0}function tc(r,t){const e=we(r.value,t.value);return e!==0?e:r.inclusive&&!t.inclusive?1:!r.inclusive&&t.inclusive?-1:0}class bt{constructor(t){this.value=t}static empty(){return new bt({mapValue:{}})}field(t){if(t.isEmpty())return this.value;{let e=this.value;for(let n=0;n<t.length-1;++n)if(e=(e.mapValue.fields||{})[t.get(n)],!Ns(e))return null;return e=(e.mapValue.fields||{})[t.lastSegment()],e||null}}set(t,e){this.getFieldsMap(t.popLast())[t.lastSegment()]=Rr(e)}setAll(t){let e=at.emptyPath(),n={},s=[];t.forEach(((a,u)=>{if(!e.isImmediateParentOf(u)){const c=this.getFieldsMap(e);this.applyChanges(c,n,s),n={},s=[],e=u.popLast()}a?n[u.lastSegment()]=Rr(a):s.push(u.lastSegment())}));const i=this.getFieldsMap(e);this.applyChanges(i,n,s)}delete(t){const e=this.field(t.popLast());Ns(e)&&e.mapValue.fields&&delete e.mapValue.fields[t.lastSegment()]}isEqual(t){return Ht(this.value,t.value)}getFieldsMap(t){let e=this.value;e.mapValue.fields||(e.mapValue={fields:{}});for(let n=0;n<t.length;++n){let s=e.mapValue.fields[t.get(n)];Ns(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},e.mapValue.fields[t.get(n)]=s),e=s}return e.mapValue.fields}applyChanges(t,e,n){De(e,((s,i)=>t[s]=i));for(const s of n)delete t[s]}clone(){return new bt(Rr(this.value))}}function Fl(r){const t=[];return De(r.fields,((e,n)=>{const s=new at([e]);if(Ns(n)){const i=Fl(n.mapValue).fields;if(i.length===0)t.push(s);else for(const a of i)t.push(s.child(a))}else t.push(s)})),new Lt(t)}class ot{constructor(t,e,n,s,i,a,u){this.key=t,this.documentType=e,this.version=n,this.readTime=s,this.createTime=i,this.data=a,this.documentState=u}static newInvalidDocument(t){return new ot(t,0,U.min(),U.min(),U.min(),bt.empty(),0)}static newFoundDocument(t,e,n,s){return new ot(t,1,e,U.min(),n,s,0)}static newNoDocument(t,e){return new ot(t,2,e,U.min(),U.min(),bt.empty(),0)}static newUnknownDocument(t,e){return new ot(t,3,e,U.min(),U.min(),bt.empty(),2)}convertToFoundDocument(t,e){return!this.createTime.isEqual(U.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=t),this.version=t,this.documentType=1,this.data=e,this.documentState=0,this}convertToNoDocument(t){return this.version=t,this.documentType=2,this.data=bt.empty(),this.documentState=0,this}convertToUnknownDocument(t){return this.version=t,this.documentType=3,this.data=bt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=U.min(),this}setReadTime(t){return this.readTime=t,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(t){return t instanceof ot&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}mutableCopy(){return new ot(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}
9class Ae{constructor(t,e){this.position=t,this.inclusive=e}}function ec(r,t,e){let n=0;for(let s=0;s<r.position.length;s++){const i=t[s],a=r.position[s];if(i.field.isKeyField()?n=O.comparator(O.fromName(a.referenceValue),e.key):n=we(a,e.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function nc(r,t){if(r===null)return t===null;if(t===null||r.inclusive!==t.inclusive||r.position.length!==t.position.length)return!1;for(let e=0;e<r.position.length;e++)if(!Ht(r.position[e],t.position[e]))return!1;return!0}class Fr{constructor(t,e="asc"){this.field=t,this.dir=e}}function qg(r,t){return r.dir===t.dir&&r.field.isEqual(t.field)}class Ll{}class H extends Ll{constructor(t,e,n){super(),this.field=t,this.op=e,this.value=n}static create(t,e,n){return t.isKeyField()?e==="in"||e==="not-in"?this.createKeyFieldInFilter(t,e,n):new jg(t,e,n):e==="array-contains"?new Kg(t,n):e==="in"?new Gl(t,n):e==="not-in"?new $g(t,n):e==="array-contains-any"?new Qg(t,n):new H(t,e,n)}static createKeyFieldInFilter(t,e,n){return e==="in"?new zg(t,n):new Gg(t,n)}matches(t){const e=t.data.field(this.field);return this.op==="!="?e!==null&&this.matchesComparison(we(e,this.value)):e!==null&&ve(this.value)===ve(e)&&this.matchesComparison(we(e,this.value))}matchesComparison(t){switch(this.op){case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;case">":return t>0;case">=":return t>=0;default:return F()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tt extends Ll{constructor(t,e){super(),this.filters=t,this.op=e,this.ae=null}static create(t,e){return new tt(t,e)}matches(t){return Pn(this)?this.filters.find((e=>!e.matches(t)))===void 0:this.filters.find((e=>e.matches(t)))!==void 0}getFlattenedFilters(){return this.ae!==null||(this.ae=this.filters.reduce(((t,e)=>t.concat(e.getFlattenedFilters())),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function Pn(r){return r.op==="and"}function fo(r){return r.op==="or"}function Fo(r){return Bl(r)&&Pn(r)}function Bl(r){for(const t of r.filters)if(t instanceof tt)return!1;return!0}function mo(r){if(r instanceof H)return r.field.canonicalString()+r.op.toString()+bn(r.value);if(Fo(r))return r.filters.map((t=>mo(t))).join(",");{const t=r.filters.map((e=>mo(e))).join(",");return`${r.op}(${t})`}}function Ul(r,t){return r instanceof H?(function(n,s){return s instanceof H&&n.op===s.op&&n.field.isEqual(s.field)&&Ht(n.value,s.value)})(r,t):r instanceof tt?(function(n,s){return s instanceof tt&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce(((i,a,u)=>i&&Ul(a,s.filters[u])),!0):!1})(r,t):void F()}function ql(r,t){const e=r.filters.concat(t);return tt.create(e,r.op)}function jl(r){return r instanceof H?(function(e){return`${e.field.canonicalString()} ${e.op} ${bn(e.value)}`})(r):r instanceof tt?(function(e){return e.op.toString()+" {"+e.getFilters().map(jl).join(" ,")+"}"})(r):"Filter"}class jg extends H{constructor(t,e,n){super(t,e,n),this.key=O.fromName(n.referenceValue)}matches(t){const e=O.comparator(t.key,this.key);return this.matchesComparison(e)}}class zg extends H{constructor(t,e){super(t,"in",e),this.keys=zl("in",e)}matches(t){return this.keys.some((e=>e.isEqual(t.key)))}}class Gg extends H{constructor(t,e){super(t,"not-in",e),this.keys=zl("not-in",e)}matches(t){return!this.keys.some((e=>e.isEqual(t.key)))}}function zl(r,t){var e;return(((e=t.arrayValue)===null||e===void 0?void 0:e.values)||[]).map((n=>O.fromName(n.referenceValue)))}class Kg extends H{constructor(t,e){super(t,"array-contains",e)}matches(t){const e=t.data.field(this.field);return Or(e)&&Mr(e.arrayValue,this.value)}}class Gl extends H{constructor(t,e){super(t,"in",e)}matches(t){const e=t.data.field(this.field);return e!==null&&Mr(this.value.arrayValue,e)}}class $g extends H{constructor(t,e){super(t,"not-in",e)}matches(t){if(Mr(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const e=t.data.field(this.field);return e!==null&&!Mr(this.value.arrayValue,e)}}class Qg extends H{constructor(t,e){super(t,"array-contains-any",e)}matches(t){const e=t.data.field(this.field);return!(!Or(e)||!e.arrayValue.values)&&e.arrayValue.values.some((n=>Mr(this.value.arrayValue,n)))}}class Wg{constructor(t,e=null,n=[],s=[],i=null,a=null,u=null){this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=s,this.limit=i,this.startAt=a,this.endAt=u,this.ue=null}}function go(r,t=null,e=[],n=[],s=null,i=null,a=null){return new Wg(r,t,e,n,s,i,a)}function Ye(r){const t=k(r);if(t.ue===null){let e=t.path.canonicalString();t.collectionGroup!==null&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((n=>
9mo(n))).join(","),e+="|ob:",e+=t.orderBy.map((n=>(function(i){return i.field.canonicalString()+i.dir})(n))).join(","),jr(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((n=>bn(n))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((n=>bn(n))).join(",")),t.ue=e}return t.ue}function zr(r,t){if(r.limit!==t.limit||r.orderBy.length!==t.orderBy.length)return!1;for(let e=0;e<r.orderBy.length;e++)if(!qg(r.orderBy[e],t.orderBy[e]))return!1;if(r.filters.length!==t.filters.length)return!1;for(let e=0;e<r.filters.length;e++)if(!Ul(r.filters[e],t.filters[e]))return!1;return r.collectionGroup===t.collectionGroup&&!!r.path.isEqual(t.path)&&!!nc(r.startAt,t.startAt)&&nc(r.endAt,t.endAt)}function js(r){return O.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}function zs(r,t){return r.filters.filter((e=>e instanceof H&&e.field.isEqual(t)))}function rc(r,t,e){let n=Ds,s=!0;for(const i of zs(r,t)){let a=Ds,u=!0;switch(i.op){case"<":case"<=":a=Bg(i.value);break;case"==":case"in":case">=":a=i.value;break;case">":a=i.value,u=!1;break;case"!=":case"not-in":a=Ds}Zu({value:n,inclusive:s},{value:a,inclusive:u})<0&&(n=a,s=u)}if(e!==null){for(let i=0;i<r.orderBy.length;++i)if(r.orderBy[i].field.isEqual(t)){const a=e.position[i];Zu({value:n,inclusive:s},{value:a,inclusive:e.inclusive})<0&&(n=a,s=e.inclusive);break}}return{value:n,inclusive:s}}function sc(r,t,e){let n=pe,s=!0;for(const i of zs(r,t)){let a=pe,u=!0;switch(i.op){case">=":case">":a=Ug(i.value),u=!1;break;case"==":case"in":case"<=":a=i.value;break;case"<":a=i.value,u=!1;break;case"!=":case"not-in":a=pe}tc({value:n,inclusive:s},{value:a,inclusive:u})>0&&(n=a,s=u)}if(e!==null){for(let i=0;i<r.orderBy.length;++i)if(r.orderBy[i].field.isEqual(t)){const a=e.position[i];tc({value:n,inclusive:s},{value:a,inclusive:e.inclusive})>0&&(n=a,s=e.inclusive);break}}return{value:n,inclusive:s}}class re{constructor(t,e=null,n=[],s=[],i=null,a="F",u=null,c=null){this.path=t,this.collectionGroup=e,this.explicitOrderBy=n,this.filters=s,this.limit=i,this.limitType=a,this.startAt=u,this.endAt=c,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function Kl(r,t,e,n,s,i,a,u){return new re(r,t,e,n,s,i,a,u)}function Un(r){return new re(r)}function ic(r){return r.filters.length===0&&r.limit===null&&r.startAt==null&&r.endAt==null&&(r.explicitOrderBy.length===0||r.explicitOrderBy.length===1&&r.explicitOrderBy[0].field.isKeyField())}function Lo(r){return r.collectionGroup!==null}function Tn(r){const t=k(r);if(t.ce===null){t.ce=[];const e=new Set;for(const i of t.explicitOrderBy)t.ce.push(i),e.add(i.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";(function(a){let u=new et(at.comparator);return a.filters.forEach((c=>{c.getFlattenedFilters().forEach((h=>{h.isInequality()&&(u=u.add(h.field))}))})),u})(t).forEach((i=>{e.has(i.canonicalString())||i.isKeyField()||t.ce.push(new Fr(i,n))})),e.has(at.keyField().canonicalString())||t.ce.push(new Fr(at.keyField(),n))}return t.ce}function kt(r){const t=k(r);return t.le||(t.le=Ql(t,Tn(r))),t.le}function $l(r){const t=k(r);return t.he||(t.he=Ql(t,r.explicitOrderBy)),t.he}function Ql(r,t){if(r.limitType==="F")return go(r.path,r.collectionGroup,t,r.filters,r.limit,r.startAt,r.endAt);{t=t.map((s=>{const i=s.dir==="desc"?"asc":"desc";return new Fr(s.field,i)}));const e=r.endAt?new Ae(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new Ae(r.startAt.position,r.startAt.inclusive):null;return go(r.path,r.collectionGroup,t,r.filters,r.limit,e,n)}}function po(r,t){const e=r.filters.concat([t]);return new re(r.path,r.collectionGroup,r.explicitOrderBy.slice(),e,r.limit,r.limitType,r.startAt,r.endAt)}function Gs(r,t,e){return new re(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),t,e,r.startAt,r.endAt)}function Gr(r,t){return zr(kt(r),kt(t))&&r.limitType===t.limitType}function Wl(r){return`${Ye(kt(r))}|lt:${r.limitType}`}function yn(r){return`Query(target=${(function(e){let n=e.path.canonicalString();return e.collectionGroup!==null&&(n+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(n+=`, filters: [${e.filters.map((s=>jl(s))).join(", ")}]`),jr(e.limit)||(n+=", limit: "+e.limit),e.orderBy.length>0&&(n+=`, orderBy: [${e.orderBy.map((s=>(function(a){return`${a.field.canonicalString()} (${a.dir})`})(s))).join(", ")}]`),e.startAt&&(n+=", startAt: ",n+=e.startAt.inclusive?"b:":"a:",n+=e.startAt.position.map((s=>bn(s))).join(",")),e.endAt&&(n+=", endAt: ",n+=e.endAt.inclusive?"a:":"b:",n+=e.endAt.position.map((s=>bn(s))).join(",")),`Target(${n})`})(kt(r))}; limitType=${r.limitType})`}
9function Kr(r,t){return t.isFoundDocument()&&(function(n,s){const i=s.key.path;return n.collectionGroup!==null?s.key.hasCollectionId(n.collectionGroup)&&n.path.isPrefixOf(i):O.isDocumentKey(n.path)?n.path.isEqual(i):n.path.isImmediateParentOf(i)})(r,t)&&(function(n,s){for(const i of Tn(n))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0})(r,t)&&(function(n,s){for(const i of n.filters)if(!i.matches(s))return!1;return!0})(r,t)&&(function(n,s){return!(n.startAt&&!(function(a,u,c){const h=ec(a,u,c);return a.inclusive?h<=0:h<0})(n.startAt,Tn(n),s)||n.endAt&&!(function(a,u,c){const h=ec(a,u,c);return a.inclusive?h>=0:h>0})(n.endAt,Tn(n),s))})(r,t)}function Hl(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function Jl(r){return(t,e)=>{let n=!1;for(const s of Tn(r)){const i=Hg(s,t,e);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function Hg(r,t,e){const n=r.field.isKeyField()?O.comparator(t.key,e.key):(function(i,a,u){const c=a.data.field(i),h=u.data.field(i);return c!==null&&h!==null?we(c,h):F()})(r.field,t,e);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return F()}}class se{constructor(t,e){this.mapKeyFn=t,this.equalsFn=e,this.inner={},this.innerSize=0}get(t){const e=this.mapKeyFn(t),n=this.inner[e];if(n!==void 0){for(const[s,i]of n)if(this.equalsFn(s,t))return i}}has(t){return this.get(t)!==void 0}set(t,e){const n=this.mapKeyFn(t),s=this.inner[n];if(s===void 0)return this.inner[n]=[[t,e]],void this.innerSize++;for(let i=0;i<s.length;i++)if(this.equalsFn(s[i][0],t))return void(s[i]=[t,e]);s.push([t,e]),this.innerSize++}delete(t){const e=this.mapKeyFn(t),n=this.inner[e];if(n===void 0)return!1;for(let s=0;s<n.length;s++)if(this.equalsFn(n[s][0],t))return n.length===1?delete this.inner[e]:n.splice(s,1),this.innerSize--,!0;return!1}forEach(t){De(this.inner,((e,n)=>{for(const[s,i]of n)t(s,i)}))}isEmpty(){return Nl(this.inner)}size(){return this.innerSize}}const Jg=new st(O.comparator);function Bt(){return Jg}const Yl=new st(O.comparator);function Er(...r){let t=Yl;for(const e of r)t=t.insert(e.key,e);return t}function Xl(r){let t=Yl;return r.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function $t(){return br()}function Zl(){return br()}function br(){return new se((r=>r.toString()),((r,t)=>r.isEqual(t)))}const Yg=new st(O.comparator),Xg=new et(O.comparator);function G(...r){let t=Xg;for(const e of r)t=t.add(e);return t}const Zg=new et(z);function Bo(){return Zg}function Uo(r,t){if(r.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Nr(t)?"-0":t}}function th(r){return{integerValue:""+r}}function eh(r,t){return Pl(t)?th(t):Uo(r,t)}class ii{constructor(){this._=void 0}}function tp(r,t,e){return r instanceof Sn?(function(s,i){const a={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&ni(i)&&(i=ri(i)),i&&(a.fields.__previous_value__=i),{mapValue:a}})(e,t):r instanceof Xe?rh(r,t):r instanceof Ze?sh(r,t):(function(s,i){const a=nh(s,i),u=oc(a)+oc(s.Pe);return ho(a)&&ho(s.Pe)?th(u):Uo(s.serializer,u)})(r,t)}function ep(r,t,e){return r instanceof Xe?rh(r,t):r instanceof Ze?sh(r,t):e}function nh(r,t){return r instanceof Vn?(function(n){return ho(n)||(function(i){return!!i&&"doubleValue"in i})(n)})(t)?t:{integerValue:0}:null}class Sn extends ii{}class Xe extends ii{constructor(t){super(),this.elements=t}}function rh(r,t){const e=ih(t);for(const n of r.elements)e.some((s=>Ht(s,n)))||e.push(n);return{arrayValue:{values:e}}}class Ze extends ii{constructor(t){super(),this.elements=t}}function sh(r,t){let e=ih(t);for(const n of r.elements)e=e.filter((s=>!Ht(s,n)));return{arrayValue:{values:e}}}class Vn extends ii{constructor(t,e){super(),this.serializer=t,this.Pe=e}}function oc(r){return ut(r.integerValue||r.doubleValue)}function ih(r){return Or(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}class $r{constructor(t,e){this.field=t,this.transform=e}}function np(r,t){return r.field.isEqual(t.field)&&(function(n,s){return n instanceof Xe&&s instanceof Xe||n instanceof Ze&&s instanceof Ze?wn(n.elements,s.elements,Ht):n instanceof Vn&&s instanceof Vn?Ht(n.Pe,s.Pe):n instanceof Sn&&s instanceof Sn})(r.transform,t.transform)}class rp{constructor(t,e){this.version=t,this.transformResults=e}}class ct{constructor(t,e){this.updateTime=t,this.exists=e}static none(){return new ct}static exists(t){return new ct(void 0,t)}static updateTime(t){return new ct(t)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(t){return this.exists===t.exists&&(this.updateTime?!!t.updateTime&&this.updateTime.isEqual(t.updateTime):!t.updateTime)}}function ks(r,t){return r.updateTime!==void 0?t.isFoundDocument()&&t.version.isEqual(r.updateTime):r.exists===void 0||r.exists===t.isFoundDocument()}class oi{}function oh(r,t){if(!r.hasLocalMutations||t&&t.fields.length===0)return null;if(t===null)return r.isNoDocument()?new jn(r.key,ct.none()):new qn(r.key,r.data,ct.none());{const e=r.data,n=bt.empty();let s=new et(at.comparator);for(let i of t.fields)if(!s.has(i)){let a=e.field(i);a===null&&i.length>1&&(i=i.popLast(),a=e.field(i)),a===null?n.delete(i):n.set(i,a),s=s.add(i)}return new ie(r.key,n,new Lt(s.toArray()),ct.none())}}function sp(r,t,e){r instanceof qn?(function(s,i,a){const u=s.value.clone(),c=uc(s.fieldTransforms,i,a.transformResults);u.setAll(c),i.convertToFoundDocument(a.version,u).setHasCommittedMutations()})(r,t,e):r instanceof ie?(function(s,i,a){if(!ks(s.precondition,i))return void i.convertToUnknownDocument(a.version);const u=uc(s.fieldTransforms,i,a.transformResults),c=i.data;c.setAll(ah(s)),c.setAll(u),i.convertToFoundDocument(a.version,c).setHasCommittedMutations()})(r,t,e):(function(s,i,a){i.convertToNoDocument(a.version).setHasCommittedMutations()})(0,t,e)}function Pr(r,t,e,n){return r instanceof qn?(function(i,a,u,c){if(!ks(i.precondition,a))return u;const h=i.value.clone(),f=cc(i.fieldTransforms,c,a);return h.setAll(f),a.convertToFoundDocument(a.version,h).setHasLocalMutations(),null})(r,t,e,n):r instanceof ie?(function(i,a,u,c){if(!ks(i.precondition,a))return u;const h=cc(i.fieldTransforms,c,a),f=a.data;return f.setAll(ah(i)),f.setAll(h),a.convertToFoundDocument(a.version,f).setHasLocalMutations(),u===null?null:u.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map((g=>g.field)))})(r,t,e,n):(function(i,a,u){return ks(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u})(r,t,e)}function ip(r,t){let e=null;for(const n of r.fieldTransforms){const s=t.data.field(n.field),i=nh(n.transform,s||null);i!=null&&(e===null&&(e=bt.empty()),e.set(n.field,i))}return e||null}function ac(r,t){return r.type===t.type&&!!r.key.isEqual(t.key)&&!!r.precondition.isEqual(t.precondition)&&!!(function(n,s){return n===void 0&&s===void 0||!(!n||!s)&&wn(n,s,((i,a)=>np(i,a)))})(r.fieldTransforms,t.fieldTransforms)&&(r.type===0?r.value.isEqual(t.value):r.type!==1||r.data.isEqual(t.data)&&r.fieldMask.isEqual(t.fieldMask))}class qn extends oi{constructor(t,e,n,s=[]){super(),this.key=t,this.value=e,this.prec
9ondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class ie extends oi{constructor(t,e,n,s,i=[]){super(),this.key=t,this.data=e,this.fieldMask=n,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function ah(r){const t=new Map;return r.fieldMask.fields.forEach((e=>{if(!e.isEmpty()){const n=r.data.field(e);t.set(e,n)}})),t}function uc(r,t,e){const n=new Map;L(r.length===e.length);for(let s=0;s<e.length;s++){const i=r[s],a=i.transform,u=t.data.field(i.field);n.set(i.field,ep(a,u,e[s]))}return n}function cc(r,t,e){const n=new Map;for(const s of r){const i=s.transform,a=e.data.field(s.field);n.set(s.field,tp(i,a,t))}return n}class jn extends oi{constructor(t,e){super(),this.key=t,this.precondition=e,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class qo extends oi{constructor(t,e){super(),this.key=t,this.precondition=e,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class jo{constructor(t,e,n,s){this.batchId=t,this.localWriteTime=e,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(t,e){const n=e.mutationResults;for(let s=0;s<this.mutations.length;s++){const i=this.mutations[s];i.key.isEqual(t.key)&&sp(i,t,n[s])}}applyToLocalView(t,e){for(const n of this.baseMutations)n.key.isEqual(t.key)&&(e=Pr(n,t,e,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(t.key)&&(e=Pr(n,t,e,this.localWriteTime));return e}applyToLocalDocumentSet(t,e){const n=Zl();return this.mutations.forEach((s=>{const i=t.get(s.key),a=i.overlayedDocument;let u=this.applyToLocalView(a,i.mutatedFields);u=e.has(s.key)?null:u;const c=oh(a,u);c!==null&&n.set(s.key,c),a.isValidDocument()||a.convertToNoDocument(U.min())})),n}keys(){return this.mutations.reduce(((t,e)=>t.add(e.key)),G())}isEqual(t){return this.batchId===t.batchId&&wn(this.mutations,t.mutations,((e,n)=>ac(e,n)))&&wn(this.baseMutations,t.baseMutations,((e,n)=>ac(e,n)))}}class zo{constructor(t,e,n,s){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.docVersions=s}static from(t,e,n){L(t.mutations.length===n.length);let s=(function(){return Yg})();const i=t.mutations;for(let a=0;a<i.length;a++)s=s.insert(i[a].key,n[a].version);return new zo(t,e,n,s)}}class Go{constructor(t,e){this.largestBatchId=t,this.mutation=e}getKey(){return this.mutation.key}isEqual(t){return t!==null&&this.mutation===t.mutation}toString(){return`Overlay{ 10 largestBatchId: ${this.largestBatchId}, 11 mutation: ${this.mutation.toString()} 12 }`}}class uh{constructor(t,e,n){this.alias=t,this.aggregateType=e,this.fieldPath=n}}class op{constructor(t,e){this.count=t,this.unchangedNames=e}}var _t,J;function ch(r){switch(r){default:return F();case P.CANCELLED:case P.UNKNOWN:case P.DEADLINE_EXCEEDED:case P.RESOURCE_EXHAUSTED:case P.INTERNAL:case P.UNAVAILABLE:case P.UNAUTHENTICATED:return!1;case P.INVALID_ARGUMENT:case P.NOT_FOUND:case P.ALREADY_EXISTS:case P.PERMISSION_DENIED:case P.FAILED_PRECONDITION:case P.ABORTED:case P.OUT_OF_RANGE:case P.UNIMPLEMENTED:case P.DATA_LOSS:return!0}}function lh(r){if(r===void 0)return gt("GRPC error has no .code"),P.UNKNOWN;switch(r){case _t.OK:return P.OK;case _t.CANCELLED:return P.CANCELLED;case _t.UNKNOWN:return P.UNKNOWN;case _t.DEADLINE_EXCEEDED:return P.DEADLINE_EXCEEDED;case _t.RESOURCE_EXHAUSTED:return P.RESOURCE_EXHAUSTED;case _t.INTERNAL:return P.INTERNAL;case _t.UNAVAILABLE:return P.UNAVAILABLE;case _t.UNAUTHENTICATED:return P.UNAUTHENTICATED;case _t.INVALID_ARGUMENT:return P.INVALID_ARGUMENT;case _t.NOT_FOUND:return P.NOT_FOUND;case _t.ALREADY_EXISTS:return P.ALREADY_EXISTS;case _t.PERMISSION_DENIED:return P.PERMISSION_DENIED;case _t.FAILED_PRECONDITION:return P.FAILED_PRECONDITION;case _t.ABORTED:return P.ABORTED;case _t.OUT_OF_RANGE:return P.OUT_OF_RANGE;case _t.UNIMPLEMENTED:return P.UNIMPLEMENTED;case _t.DATA_LOSS:return P.DATA_LOSS;default:return F()}}(J=_t||(_t={}))[J.OK=0]="OK",J[J.CANCELLED=1]="CANCELLED",J[J.UNKNOWN=2]="UNKNOWN",J[J.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",J[J.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",J[J.NOT_FOUND=5]="NOT_FOUND",J[J.ALREADY_EXISTS=6]="ALREADY_EXISTS",J[J.PERMISSION_DENIED=7]="PERMISSION_DENIED",J[J.UNAUTHENTICATED=16]="UNAUTHENTICATED",J[J.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",J[J.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",J[J.ABORTED=10]="ABORTED",J[J.OUT_OF_RANGE=11]="OUT_OF_RANGE",J[J.UNIMPLEMENT
12ED=12]="UNIMPLEMENTED",J[J.INTERNAL=13]="INTERNAL",J[J.UNAVAILABLE=14]="UNAVAILABLE",J[J.DATA_LOSS=15]="DATA_LOSS";let Ks=null;function hh(){return new TextEncoder}const ap=new Qe([4294967295,4294967295],0);function lc(r){const t=hh().encode(r),e=new dl;return e.update(t),new Uint8Array(e.digest())}function hc(r){const t=new DataView(r.buffer),e=t.getUint32(0,!0),n=t.getUint32(4,!0),s=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new Qe([e,n],0),new Qe([s,i],0)]}class Ko{constructor(t,e,n){if(this.bitmap=t,this.padding=e,this.hashCount=n,e<0||e>=8)throw new Tr(`Invalid padding: ${e}`);if(n<0)throw new Tr(`Invalid hash count: ${n}`);if(t.length>0&&this.hashCount===0)throw new Tr(`Invalid hash count: ${n}`);if(t.length===0&&e!==0)throw new Tr(`Invalid padding when bitmap length is 0: ${e}`);this.Ie=8*t.length-e,this.Te=Qe.fromNumber(this.Ie)}Ee(t,e,n){let s=t.add(e.multiply(Qe.fromNumber(n)));return s.compare(ap)===1&&(s=new Qe([s.getBits(0),s.getBits(1)],0)),s.modulo(this.Te).toNumber()}de(t){return(this.bitmap[Math.floor(t/8)]&1<<t%8)!=0}mightContain(t){if(this.Ie===0)return!1;const e=lc(t),[n,s]=hc(e);for(let i=0;i<this.hashCount;i++){const a=this.Ee(n,s,i);if(!this.de(a))return!1}return!0}static create(t,e,n){const s=t%8==0?0:8-t%8,i=new Uint8Array(Math.ceil(t/8)),a=new Ko(i,s,e);return n.forEach((u=>a.insert(u))),a}insert(t){if(this.Ie===0)return;const e=lc(t),[n,s]=hc(e);for(let i=0;i<this.hashCount;i++){const a=this.Ee(n,s,i);this.Ae(a)}}Ae(t){const e=Math.floor(t/8),n=t%8;this.bitmap[e]|=1<<n}}class Tr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Qr{constructor(t,e,n,s,i){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(t,e,n){const s=new Map;return s.set(t,Wr.createSynthesizedTargetChangeForCurrentChange(t,e,n)),new Qr(U.min(),s,new st(z),Bt(),G())}}class Wr{constructor(t,e,n,s,i){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(t,e,n){return new Wr(n,e,G(),G(),G())}}class Ms{constructor(t,e,n,s){this.Re=t,this.removedTargetIds=e,this.key=n,this.Ve=s}}class dh{constructor(t,e){this.targetId=t,this.me=e}}class fh{constructor(t,e,n=dt.EMPTY_BYTE_STRING,s=null){this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=s}}class dc{constructor(){this.fe=0,this.ge=mc(),this.pe=dt.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return this.fe!==0}get be(){return this.we}De(t){t.approximateByteSize()>0&&(this.we=!0,this.pe=t)}ve(){let t=G(),e=G(),n=G();return this.ge.forEach(((s,i)=>{switch(i){case 0:t=t.add(s);break;case 2:e=e.add(s);break;case 1:n=n.add(s);break;default:F()}})),new Wr(this.pe,this.ye,t,e,n)}Ce(){this.we=!1,this.ge=mc()}Fe(t,e){this.we=!0,this.ge=this.ge.insert(t,e)}Me(t){this.we=!0,this.ge=this.ge.remove(t)}xe(){this.fe+=1}Oe(){this.fe-=1,L(this.fe>=0)}Ne(){this.we=!0,this.ye=!0}}class up{constructor(t){this.Le=t,this.Be=new Map,this.ke=Bt(),this.qe=fc(),this.Qe=new st(z)}Ke(t){for(const e of t.Re)t.Ve&&t.Ve.isFoundDocument()?this.$e(e,t.Ve):this.Ue(e,t.key,t.Ve);for(const e of t.removedTargetIds)this.Ue(e,t.key,t.Ve)}We(t){this.forEachTarget(t,(e=>{const n=this.Ge(e);switch(t.state){case 0:this.ze(e)&&n.De(t.resumeToken);break;case 1:n.Oe(),n.Se||n.Ce(),n.De(t.resumeToken);break;case 2:n.Oe(),n.Se||this.removeTarget(e);break;case 3:this.ze(e)&&(n.Ne(),n.De(t.resumeToken));break;case 4:this.ze(e)&&(this.je(e),n.De(t.resumeToken));break;default:F()}}))}forEachTarget(t,e){t.targetIds.length>0?t.targetIds.forEach(e):this.Be.forEach(((n,s)=>{this.ze(s)&&e(s)}))}He(t){const e=t.targetId,n=t.me.count,s=this.Je(e);if(s){const i=s.target;if(js(i))if(n===0){const a=new O(i.path);this.Ue(e,a,ot.newNoDocument(a,U.min()))}else L(n===1);else{const a=this.Ye(e);if(a!==n){const u=this.Ze(t),c=u?this.Xe(u,t,a):1;if(c!==0){this.je(e);const h=c===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(e,h)}Ks?.et((function(f,g,_,R,C){var N,V,q,j,B,$;const Z={localCacheCount:f,existenceFilterCount:g.count,databaseId:_.database,projectId:_.projectId},K=g.unchangedNames;return K&&(Z.bloomFilter={applied:C===0,hashCount:(N=K?.hashCount)!==null&&N!==void 0?N:0,bitmapLength:(j=(q=(V=K?.bits)===null||V===void 0?void 0:V.bitmap)===null||q===void 0?void 0:q.length)!==null&&j!==void 0?j:0,padding:($=(B=K?.bits)===null||B===void 0?void 0:B.padding)!==null&&$!==void 0?$:0,mightContain:E=>{var p;return(p=R?.mightContain(E))!==null&&p!==void 0&&p}}),Z})(a,t.me,this.Le.tt(),u,c))}}}}Ze(t){const e=t.me.unchangedNames;if(!e||!e.bits)return null;const{bits:{bitmap:n="",padding:s=0},hashCount:i=0}=e;let a,u;try{a=ne(n).toUint8Array()}catch(c){if(c instanceof kl)return qt("Decoding the base64 bloom filter in existence filter failed ("+c.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw c}try{u=new Ko(a,s,i)}catch(c){return qt(c instanceof Tr?"BloomFilter error: ":"Applying bloom filter failed: ",c),null}return u.Ie===0?null:u}Xe(t,e,n){return e.me.count===n-this.nt(t,e.targetId)?0:2}nt(t,e){const n=this.Le.getRemoteKeysForTarget(e);let s=0;
12return n.forEach((i=>{const a=this.Le.tt(),u=`projects/${a.projectId}/databases/${a.database}/documents/${i.path.canonicalString()}`;t.mightContain(u)||(this.Ue(e,i,null),s++)})),s}rt(t){const e=new Map;this.Be.forEach(((i,a)=>{const u=this.Je(a);if(u){if(i.current&&js(u.target)){const c=new O(u.target.path);this.ke.get(c)!==null||this.it(a,c)||this.Ue(a,c,ot.newNoDocument(c,t))}i.be&&(e.set(a,i.ve()),i.Ce())}}));let n=G();this.qe.forEach(((i,a)=>{let u=!0;a.forEachWhile((c=>{const h=this.Je(c);return!h||h.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)})),u&&(n=n.add(i))})),this.ke.forEach(((i,a)=>a.setReadTime(t)));const s=new Qr(t,e,this.Qe,this.ke,n);return this.ke=Bt(),this.qe=fc(),this.Qe=new st(z),s}$e(t,e){if(!this.ze(t))return;const n=this.it(t,e.key)?2:0;this.Ge(t).Fe(e.key,n),this.ke=this.ke.insert(e.key,e),this.qe=this.qe.insert(e.key,this.st(e.key).add(t))}Ue(t,e,n){if(!this.ze(t))return;const s=this.Ge(t);this.it(t,e)?s.Fe(e,1):s.Me(e),this.qe=this.qe.insert(e,this.st(e).delete(t)),n&&(this.ke=this.ke.insert(e,n))}removeTarget(t){this.Be.delete(t)}Ye(t){const e=this.Ge(t).ve();return this.Le.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size}xe(t){this.Ge(t).xe()}Ge(t){let e=this.Be.get(t);return e||(e=new dc,this.Be.set(t,e)),e}st(t){let e=this.qe.get(t);return e||(e=new et(z),this.qe=this.qe.insert(t,e)),e}ze(t){const e=this.Je(t)!==null;return e||x("WatchChangeAggregator","Detected inactive target",t),e}Je(t){const e=this.Be.get(t);return e&&e.Se?null:this.Le.ot(t)}je(t){this.Be.set(t,new dc),this.Le.getRemoteKeysForTarget(t).forEach((e=>{this.Ue(t,e,null)}))}it(t,e){return this.Le.getRemoteKeysForTarget(t).has(e)}}function fc(){return new st(O.comparator)}function mc(){return new st(O.comparator)}const cp={asc:"ASCENDING",desc:"DESCENDING"},lp={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},hp={and:"AND",or:"OR"};class dp{constructor(t,e){this.databaseId=t,this.useProto3Json=e}}function _o(r,t){return r.useProto3Json||jr(t)?t:{value:t}}function Cn(r,t){return r.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function mh(r,t){return r.useProto3Json?t.toBase64():t.toUint8Array()}function fp(r,t){return Cn(r,t.toTimestamp())}function pt(r){return L(!!r),U.fromTimestamp((function(e){const n=ee(e);return new lt(n.seconds,n.nanos)})(r))}function $o(r,t){return yo(r,t).canonicalString()}function yo(r,t){const e=(function(s){return new W(["projects",s.projectId,"databases",s.database])})(r).child("documents");return t===void 0?e:e.child(t)}function gh(r){const t=W.fromString(r);return L(Rh(t)),t}function Lr(r,t){return $o(r.databaseId,t.path)}function Wt(r,t){const e=gh(t);if(e.get(1)!==r.databaseId.projectId)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+e.get(1)+" vs "+r.databaseId.projectId);if(e.get(3)!==r.databaseId.database)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+e.get(3)+" vs "+r.databaseId.database);return new O(yh(e))}function ph(r,t){return $o(r.databaseId,t)}function _h(r){const t=gh(r);return t.length===4?W.emptyPath():yh(t)}function Io(r){return new W(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function yh(r){return L(r.length>4&&r.get(4)==="documents"),r.popFirst(5)}function gc(r,t,e){return{name:Lr(r,t),fields:e.value.mapValue.fields}}function Ih(r,t,e){const n=Wt(r,t.name),s=pt(t.updateTime),i=t.createTime?pt(t.createTime):U.min(),a=new bt({mapValue:{fields:t.fields}}),u=ot.newFoundDocument(n,s,i,a);return e&&u.setHasCommittedMutations(),e?u.setHasCommittedMutations():u}function mp(r,t){return"found"in t?(function(n,s){L(!!s.found),s.found.name,s.found.updateTime;const i=Wt(n,s.found.name),a=pt(s.found.updateTime),u=s.found.createTime?pt(s.found.createTime):U.min(),c=new bt({mapValue:{fields:s.found.fields}});return ot.newFoundDocument(i,a,u,c)})(r,t):"missing"in t?(function(n,s){L(!!s.missing),L(!!s.readTime);const i=Wt(n,s.missing),a=pt(s.readTime);return ot.newNoDocument(i,a)})(r,t):F()}function gp(r,t){let e;if("targetChange"in t){t.targetChange;const n=(function(h){return h==="NO_CHANGE"?0:h==="ADD"?1:h==="REMOVE"?2:h==="CURRENT"?3:h==="RESET"?4:F()})(t.targetChange.targetChangeType||"NO_CHANGE"),s=t.targetChange.targetIds||[],i=(function(h,f){return h.useProto3Json?(L(f===void 0||typeof f=="string"),dt.fromBase64String(f||"")):(L(f===void 0||f instanceof Buffer||f instanceof Uint8Array),dt.fromUint8Array(f||new Uint8Array))})(r,t.targetChange.resumeToken),a=t.targetChange.cause,u=a&&(function(h){const f=h.code===void 0?P.UNKNOWN:lh(h.code);return new D(f,h.message||"")})(a);e=new fh(n,s,i,u||null)}else if("documentChange"in t){t.documentChange;const n=t.documentChange;n.document,n.document.name,n.document.updateTime;const s=Wt(r,n.document.name),i=pt(n.document.updateTime),a=n.document.createTime?pt(n.document.createTime):U.min(),u=new bt({mapValue:{fields:n.document.fields}}),c=ot.newFoundDocument(s,i,a,u),h=n.targetIds||[],f=n.removedTargetIds||[];
12e=new Ms(h,f,c.key,c)}else if("documentDelete"in t){t.documentDelete;const n=t.documentDelete;n.document;const s=Wt(r,n.document),i=n.readTime?pt(n.readTime):U.min(),a=ot.newNoDocument(s,i),u=n.removedTargetIds||[];e=new Ms([],u,a.key,a)}else if("documentRemove"in t){t.documentRemove;const n=t.documentRemove;n.document;const s=Wt(r,n.document),i=n.removedTargetIds||[];e=new Ms([],i,s,null)}else{if(!("filter"in t))return F();{t.filter;const n=t.filter;n.targetId;const{count:s=0,unchangedNames:i}=n,a=new op(s,i),u=n.targetId;e=new dh(u,a)}}return e}function Br(r,t){let e;if(t instanceof qn)e={update:gc(r,t.key,t.value)};else if(t instanceof jn)e={delete:Lr(r,t.key)};else if(t instanceof ie)e={update:gc(r,t.key,t.data),updateMask:Tp(t.fieldMask)};else{if(!(t instanceof qo))return F();e={verify:Lr(r,t.key)}}return t.fieldTransforms.length>0&&(e.updateTransforms=t.fieldTransforms.map((n=>(function(i,a){const u=a.transform;if(u instanceof Sn)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof Xe)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof Ze)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof Vn)return{fieldPath:a.field.canonicalString(),increment:u.Pe};throw F()})(0,n)))),t.precondition.isNone||(e.currentDocument=(function(s,i){return i.updateTime!==void 0?{updateTime:fp(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:F()})(r,t.precondition)),e}function Eo(r,t){const e=t.currentDocument?(function(i){return i.updateTime!==void 0?ct.updateTime(pt(i.updateTime)):i.exists!==void 0?ct.exists(i.exists):ct.none()})(t.currentDocument):ct.none(),n=t.updateTransforms?t.updateTransforms.map((s=>(function(a,u){let c=null;if("setToServerValue"in u)L(u.setToServerValue==="REQUEST_TIME"),c=new Sn;else if("appendMissingElements"in u){const f=u.appendMissingElements.values||[];c=new Xe(f)}else if("removeAllFromArray"in u){const f=u.removeAllFromArray.values||[];c=new Ze(f)}else"increment"in u?c=new Vn(a,u.increment):F();const h=at.fromServerFormat(u.fieldPath);return new $r(h,c)})(r,s))):[];if(t.update){t.update.name;const s=Wt(r,t.update.name),i=new bt({mapValue:{fields:t.update.fields}});if(t.updateMask){const a=(function(c){const h=c.fieldPaths||[];return new Lt(h.map((f=>at.fromServerFormat(f))))})(t.updateMask);return new ie(s,i,a,e,n)}return new qn(s,i,e,n)}if(t.delete){const s=Wt(r,t.delete);return new jn(s,e)}if(t.verify){const s=Wt(r,t.verify);return new qo(s,e)}return F()}function pp(r,t){return r&&r.length>0?(L(t!==void 0),r.map((e=>(function(s,i){let a=s.updateTime?pt(s.updateTime):pt(i);return a.isEqual(U.min())&&(a=pt(i)),new rp(a,s.transformResults||[])})(e,t)))):[]}function Eh(r,t){return{documents:[ph(r,t.path)]}}function ai(r,t){const e={structuredQuery:{}},n=t.path;let s;t.collectionGroup!==null?(s=n,e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(s=n.popLast(),e.structuredQuery.from=[{collectionId:n.lastSegment()}]),e.parent=ph(r,s);const i=(function(h){if(h.length!==0)return Ah(tt.create(h,"and"))})(t.filters);i&&(e.structuredQuery.where=i);const a=(function(h){if(h.length!==0)return h.map((f=>(function(_){return{field:fe(_.field),direction:yp(_.dir)}})(f)))})(t.orderBy);a&&(e.structuredQuery.orderBy=a);const u=_o(r,t.limit);return u!==null&&(e.structuredQuery.limit=u),t.startAt&&(e.structuredQuery.startAt=(function(h){return{before:h.inclusive,values:h.position}})(t.startAt)),t.endAt&&(e.structuredQuery.endAt=(function(h){return{before:!h.inclusive,values:h.position}})(t.endAt)),{_t:e,parent:s}}function Th(r,t,e,n){const{_t:s,parent:i}=ai(r,t),a={},u=[];let c=0;return e.forEach((h=>{const f=n?h.alias:"aggregate_"+c++;a[f]=h.alias,h.aggregateType==="count"?u.push({alias:f,count:{}}):h.aggregateType==="avg"?u.push({alias:f,avg:{field:fe(h.fieldPath)}}):h.aggregateType==="sum"&&u.push({alias:f,sum:{field:fe(h.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:u,structuredQuery:s.structuredQuery},parent:s.parent},ut:a,parent:i}}function vh(r){let t=_h(r.parent);const e=r.structuredQuery,n=e.from?e.from.length:0;let s=null;if(n>0){L(n===1);const f=e.from[0];f.allDescendants?s=f.collectionId:t=t.child(f.collectionId)}let i=[];e.where&&(i=(function(g){const _=wh(g);return _ instanceof tt&&Fo(_)?_.getFilters():[_]})(e.where));let a=[];e.orderBy&&(a=(function(g){return g.map((_=>(function(C){return new Fr(In(C.field),(function(V){switch(V){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(C.direction))})(_)))})(e.orderBy));let u=null;e.limit&&(u=(function(g){let _;return _=typeof g=="object"?g.value:g,jr(_)?null:_})(e.limit));let c=null;e.startAt&&(c=(function(g){const _=!!g.before,R=g.values||[];return new Ae(R,_)})(e.startAt));let h=null;return e.endAt&&(h=(function(g){const _=!g.before,R=g.values||[];return new Ae(R,_)})(e.endAt)),Kl(t,s,a,i,u,"F",c,h)}function _p(r,t){const e=(function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return F()}})(t.purpose);return e==null?null:{"goog-listen-tags":e}}function wh(r){return r.unaryFilter!==void 0?(function(e){switch(e.unaryFilter.op){case"IS_NAN":const n=In(e.unaryFilter.field);return H.create(n,"==",{doubleValue:NaN});case"IS_NULL":const s=In(e.unaryFilter.field);return H.create(s,"==",{nullValue:"NULL_VALUE"});
12case"IS_NOT_NAN":const i=In(e.unaryFilter.field);return H.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const a=In(e.unaryFilter.field);return H.create(a,"!=",{nullValue:"NULL_VALUE"});default:return F()}})(r):r.fieldFilter!==void 0?(function(e){return H.create(In(e.fieldFilter.field),(function(s){switch(s){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return F()}})(e.fieldFilter.op),e.fieldFilter.value)})(r):r.compositeFilter!==void 0?(function(e){return tt.create(e.compositeFilter.filters.map((n=>wh(n))),(function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return F()}})(e.compositeFilter.op))})(r):F()}function yp(r){return cp[r]}function Ip(r){return lp[r]}function Ep(r){return hp[r]}function fe(r){return{fieldPath:r.canonicalString()}}function In(r){return at.fromServerFormat(r.fieldPath)}function Ah(r){return r instanceof H?(function(e){if(e.op==="=="){if(Xu(e.value))return{unaryFilter:{field:fe(e.field),op:"IS_NAN"}};if(Yu(e.value))return{unaryFilter:{field:fe(e.field),op:"IS_NULL"}}}else if(e.op==="!="){if(Xu(e.value))return{unaryFilter:{field:fe(e.field),op:"IS_NOT_NAN"}};if(Yu(e.value))return{unaryFilter:{field:fe(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:fe(e.field),op:Ip(e.op),value:e.value}}})(r):r instanceof tt?(function(e){const n=e.getFilters().map((s=>Ah(s)));return n.length===1?n[0]:{compositeFilter:{op:Ep(e.op),filters:n}}})(r):F()}function Tp(r){const t=[];return r.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Rh(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}class Zt{constructor(t,e,n,s,i=U.min(),a=U.min(),u=dt.EMPTY_BYTE_STRING,c=null){this.target=t,this.targetId=e,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=u,this.expectedCount=c}withSequenceNumber(t){return new Zt(this.target,this.targetId,this.purpose,t,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(t,e){return new Zt(this.target,this.targetId,this.purpose,this.sequenceNumber,e,this.lastLimboFreeSnapshotVersion,t,null)}withExpectedCount(t){return new Zt(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,t)}withLastLimboFreeSnapshotVersion(t){return new Zt(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,t,this.resumeToken,this.expectedCount)}}class bh{constructor(t){this.ct=t}}function vp(r,t){let e;if(t.document)e=Ih(r.ct,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const n=O.fromSegments(t.noDocument.path),s=en(t.noDocument.readTime);e=ot.newNoDocument(n,s),t.hasCommittedMutations&&e.setHasCommittedMutations()}else{if(!t.unknownDocument)return F();{const n=O.fromSegments(t.unknownDocument.path),s=en(t.unknownDocument.version);e=ot.newUnknownDocument(n,s)}}return t.readTime&&e.setReadTime((function(s){const i=new lt(s[0],s[1]);return U.fromTimestamp(i)})(t.readTime)),e}function pc(r,t){const e=t.key,n={prefixPath:e.getCollectionPath().popLast().toArray(),collectionGroup:e.collectionGroup,documentId:e.path.lastSegment(),readTime:$s(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())n.document=(function(i,a){return{name:Lr(i,a.key),fields:a.data.value.mapValue.fields,updateTime:Cn(i,a.version.toTimestamp()),createTime:Cn(i,a.createTime.toTimestamp())}})(r.ct,t);else if(t.isNoDocument())n.noDocument={path:e.path.toArray(),readTime:tn(t.version)};else{if(!t.isUnknownDocument())return F();n.unknownDocument={path:e.path.toArray(),version:tn(t.version)}}return n}function $s(r){const t=r.toTimestamp();return[t.seconds,t.nanoseconds]}function tn(r){const t=r.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function en(r){const t=new lt(r.seconds,r.nanoseconds);return U.fromTimestamp(t)}function Ge(r,t){const e=(t.baseMutations||[]).map((i=>Eo(r.ct,i)));for(let i=0;i<t.mutations.length-1;++i){const a=t.mutations[i];if(i+1<t.mutations.length&&t.mutations[i+1].transform!==void 0){const u=t.mutations[i+1];a.updateTransforms=u.transform.fieldTransforms,t.mutations.splice(i+1,1),++i}}const n=t.mutations.map((i=>Eo(r.ct,i))),s=lt.fromMillis(t.localWriteTimeMs);return new jo(t.batchId,s,e,n)}function vr(r){const t=en(r.readTime),e=r.lastLimboFreeSnapshotVersion!==void 0?en(r.lastLimboFreeSnapshotVersion):U.min();let n;return n=(function(i){return i.documents!==void 0})(r.query)?(function(i){return L(i.documents.length===1),kt(Un(_h(i.documents[0])))})(r.query):(function(i){return kt(vh(i))})(r.query),new Zt(n,r.targetId,"TargetPurposeListen",r.lastListenSequenceNumber,t,e,dt.fromBase64String(r.resumeToken))}function Ph(r,t){const e=tn(t.snapshotVersion),n=tn(t.lastLimboFreeSnapshotVersion);let s;s=js(t.target)?Eh(r.ct,t.target):ai(r.ct,t.target)._t;const i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Ye(t.target),readTime:e,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:n,query:s}}function Qo(r){const t=vh({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?Gs(t,t.limit,"L"):t}function Yi(r,t){return new Go(t.largestBatchId,Eo(r.ct,t.overlayMutation))}function _c(r,t){const e=t.path.lastSegment();return[r,Nt(t.path.popLast()),e]}function yc(r,t,e,n){return{indexId:r,uid:t,sequenceNumber:e,readTime:tn(n.readTime),documentKey:Nt(n.documentKey.path),largestBatchId:n.largestBatchId}}class wp{getBundleMetadata(t,e){return Ic(t).get(e).next((n=>{if(n)return(function(i){return{id:i.bundleId,createTime:en(i.createTime),version:i.version}})(n)}))}saveBundleMetadata(t,e){return Ic(t).put((function(s){return{bundleId:s.id,createTime:tn(pt(s.createTime)),version:s.version}})(e))}getNamedQuery(t,e){return Ec(t).get(e).next((n=>{if(n)return(function(i){return{name:i.name,query:Qo(i.bundledQuery),readTime:en(i.readTime)}})(n)}))}saveNamedQuery(t,e){return Ec(t).put((function(s){return{name:s.name,readTime:tn(pt(s.readTime)),bundledQuery:s.bundledQuery}})(e))}}function Ic(r){return yt(r,"bundles")}function Ec(r){return yt(r,"namedQueries")}
12class ui{constructor(t,e){this.serializer=t,this.userId=e}static lt(t,e){const n=e.uid||"";return new ui(t,n)}getOverlay(t,e){return mr(t).get(_c(this.userId,e)).next((n=>n?Yi(this.serializer,n):null))}getOverlays(t,e){const n=$t();return w.forEach(e,(s=>this.getOverlay(t,s).next((i=>{i!==null&&n.set(s,i)})))).next((()=>n))}saveOverlays(t,e,n){const s=[];return n.forEach(((i,a)=>{const u=new Go(e,a);s.push(this.ht(t,u))})),w.waitFor(s)}removeOverlaysForBatchId(t,e,n){const s=new Set;e.forEach((a=>s.add(Nt(a.getCollectionPath()))));const i=[];return s.forEach((a=>{const u=IDBKeyRange.bound([this.userId,a,n],[this.userId,a,n+1],!1,!0);i.push(mr(t).j("collectionPathOverlayIndex",u))})),w.waitFor(i)}getOverlaysForCollection(t,e,n){const s=$t(),i=Nt(e),a=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return mr(t).U("collectionPathOverlayIndex",a).next((u=>{for(const c of u){const h=Yi(this.serializer,c);s.set(h.getKey(),h)}return s}))}getOverlaysForCollectionGroup(t,e,n,s){const i=$t();let a;const u=IDBKeyRange.bound([this.userId,e,n],[this.userId,e,Number.POSITIVE_INFINITY],!0);return mr(t).J({index:"collectionGroupOverlayIndex",range:u},((c,h,f)=>{const g=Yi(this.serializer,h);i.size()<s||g.largestBatchId===a?(i.set(g.getKey(),g),a=g.largestBatchId):f.done()})).next((()=>i))}ht(t,e){return mr(t).put((function(s,i,a){const[u,c,h]=_c(i,a.mutation.key);return{userId:i,collectionPath:c,documentId:h,collectionGroup:a.mutation.key.getCollectionGroup(),largestBatchId:a.largestBatchId,overlayMutation:Br(s.ct,a.mutation)}})(this.serializer,this.userId,e))}}function mr(r){return yt(r,"documentOverlays")}class Ap{Pt(t){return yt(t,"globals")}getSessionToken(t){return this.Pt(t).get("sessionToken").next((e=>{const n=e?.value;return n?dt.fromUint8Array(n):dt.EMPTY_BYTE_STRING}))}setSessionToken(t,e){return this.Pt(t).put({name:"sessionToken",value:e.toUint8Array()})}}class Ke{constructor(){}It(t,e){this.Tt(t,e),e.Et()}Tt(t,e){if("nullValue"in t)this.dt(e,5);else if("booleanValue"in t)this.dt(e,10),e.At(t.booleanValue?1:0);else if("integerValue"in t)this.dt(e,15),e.At(ut(t.integerValue));else if("doubleValue"in t){const n=ut(t.doubleValue);isNaN(n)?this.dt(e,13):(this.dt(e,15),Nr(n)?e.At(0):e.At(n))}else if("timestampValue"in t){let n=t.timestampValue;this.dt(e,20),typeof n=="string"&&(n=ee(n)),e.Rt(`${n.seconds||""}`),e.At(n.nanos||0)}else if("stringValue"in t)this.Vt(t.stringValue,e),this.ft(e);else if("bytesValue"in t)this.dt(e,30),e.gt(ne(t.bytesValue)),this.ft(e);else if("referenceValue"in t)this.yt(t.referenceValue,e);else if("geoPointValue"in t){const n=t.geoPointValue;this.dt(e,45),e.At(n.latitude||0),e.At(n.longitude||0)}else"mapValue"in t?Ml(t)?this.dt(e,Number.MAX_SAFE_INTEGER):si(t)?this.wt(t.mapValue,e):(this.St(t.mapValue,e),this.ft(e)):"arrayValue"in t?(this.bt(t.arrayValue,e),this.ft(e)):F()}Vt(t,e){this.dt(e,25),this.Dt(t,e)}Dt(t,e){e.Rt(t)}St(t,e){const n=t.fields||{};this.dt(e,55);for(const s of Object.keys(n))this.Vt(s,e),this.Tt(n[s],e)}wt(t,e){var n,s;const i=t.fields||{};this.dt(e,53);const a="value",u=((s=(n=i[a].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.length)||0;this.dt(e,15),e.At(ut(u)),this.Vt(a,e),this.Tt(i[a],e)}bt(t,e){const n=t.values||[];this.dt(e,50);for(const s of n)this.Tt(s,e)}yt(t,e){this.dt(e,37),O.fromName(t).path.forEach((n=>{this.dt(e,60),this.Dt(n,e)}))}dt(t,e){t.At(e)}ft(t){t.At(2)}}Ke.vt=new Ke;function Rp(r){if(r===0)return 8;let t=0;return r>>4==0&&(t+=4,r<<=4),r>>6==0&&(t+=2,r<<=2),r>>7==0&&(t+=1),t}function Tc(r){const t=64-(function(n){let s=0;for(let i=0;i<8;++i){const a=Rp(255&n[i]);if(s+=a,a!==8)break}return s})(r);return Math.ceil(t/8)}class bp{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ct(t){const e=t[Symbol.iterator]();let n=e.next();for(;!n.done;)this.Ft(n.value),n=e.next();this.Mt()}xt(t){const e=t[Symbol.iterator]();let n=e.next();for(;!n.done;)this.Ot(n.value),n=e.next();this.Nt()}Lt(t){for(const e of t){const n=e.charCodeAt(0);if(n<128)this.Ft(n);else if(n<2048)this.Ft(960|n>>>6),this.Ft(128|63&n);else if(e<"\uD800"||"\uDBFF"<e)this.Ft(480|n>>>12),this.Ft(128|63&n>>>6),this.Ft(128|63&n);else{const s=e.codePointAt(0);this.Ft(240|s>>>18),this.Ft(128|63&s>>>12),this.Ft(128|63&s>>>6),this.Ft(128|63&s)}}this.Mt()}Bt(t){for(const e of t){const n=e.charCodeAt(0);if(n<128)this.Ot(n);else if(n<2048)this.Ot(960|n>>>6),this.Ot(128|63&n);else if(e<"\uD800"||"\uDBFF"<e)this.Ot(480|n>>>12),this.Ot(128|63&n>>>6),this.Ot(128|63&n);else{const s=e.codePointAt(0);this.Ot(240|s>>>18),this.Ot(128|63&s>>>12),this.Ot(128|63&s>>>6),this.Ot(128|63&s)}}this.Nt()}kt(t){const e=this.qt(t),n=Tc(e);this.Qt(1+n),this.buffer[this.position++]=255&n;for(let s=e.length-n;s<e.length;++s)this.buffer[this.position++]=255&e[s]}Kt(t){const e=this.qt(t),n=Tc(e);this.Qt(1+n),this.buffer[this.position++]=~(255&n);for(let s=e.length-n;s<e.length;++s)this.buffer[this.position++]=~(255&e[s])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(t){this.Qt(t.length),this.buffer.set(t,this.position),this.position+=t.length}zt(){return this.buffer.slice(0,this.position)}qt(t){const e=(function(i){const a=new DataView(new ArrayBuffer(8));return a.setFloat64(0,i,!1),new Uint8Array(a.buffer)})(t),n=(128&e[0])!=0;e[0]^=n?255:128;for(let s=1;s<e.length;++s)e[s]^=n?255:0;return e}Ft(t){const e=255&t;e===0?(this.Ut(0),this.Ut(255)):e===255?(this.Ut(255),this.Ut(0)):this.Ut(e)}Ot(t){const e=255&t;e===0?(this.Gt(0),this.Gt(255)):e===255?(this.Gt(255),this.Gt(0)):this.Gt(t)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(t){this.Qt(1),this.buffer[this.position++]=t}Gt(t){this.Qt(1),this.buffer[this.position++]=~t}Qt(t){const e=t+this.position;if(e<=this.buffer.length)return;let n=2*this.buffer.length;n<e&&(n=e);const s=new Uint8Array(n);s.set(this.buffer),this.buffer=s}}class Pp{constructor(t){this.jt=t}gt(t){this.jt.Ct(t)}Rt(t){this.jt.Lt(t)}At(t){this.jt.kt(t)}Et(){this.jt.$t()}}class Sp{constructor(t){this.jt=t}gt(t){this.jt.xt(t)}Rt(t){this.jt.Bt(t)}At(t){this.jt.Kt(t)}Et(){this.jt.Wt()}}
12class gr{constructor(){this.jt=new bp,this.Ht=new Pp(this.jt),this.Jt=new Sp(this.jt)}seed(t){this.jt.seed(t)}Yt(t){return t===0?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class $e{constructor(t,e,n,s){this.indexId=t,this.documentKey=e,this.arrayValue=n,this.directionalValue=s}Zt(){const t=this.directionalValue.length,e=t===0||this.directionalValue[t-1]===255?t+1:t,n=new Uint8Array(e);return n.set(this.directionalValue,0),e!==t?n.set([0],this.directionalValue.length):++n[n.length-1],new $e(this.indexId,this.documentKey,this.arrayValue,n)}}function he(r,t){let e=r.indexId-t.indexId;return e!==0?e:(e=vc(r.arrayValue,t.arrayValue),e!==0?e:(e=vc(r.directionalValue,t.directionalValue),e!==0?e:O.comparator(r.documentKey,t.documentKey)))}function vc(r,t){for(let e=0;e<r.length&&e<t.length;++e){const n=r[e]-t[e];if(n!==0)return n}return r.length-t.length}class wc{constructor(t){this.Xt=new et(((e,n)=>at.comparator(e.field,n.field))),this.collectionId=t.collectionGroup!=null?t.collectionGroup:t.path.lastSegment(),this.en=t.orderBy,this.tn=[];for(const e of t.filters){const n=e;
12n.isInequality()?this.Xt=this.Xt.add(n):this.tn.push(n)}}get nn(){return this.Xt.size>1}rn(t){if(L(t.collectionGroup===this.collectionId),this.nn)return!1;const e=uo(t);if(e!==void 0&&!this.sn(e))return!1;const n=je(t);let s=new Set,i=0,a=0;for(;i<n.length&&this.sn(n[i]);++i)s=s.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.Xt.size>0){const u=this.Xt.getIterator().getNext();if(!s.has(u.field.canonicalString())){const c=n[i];if(!this.on(u,c)||!this._n(this.en[a++],c))return!1}++i}for(;i<n.length;++i){const u=n[i];if(a>=this.en.length||!this._n(this.en[a++],u))return!1}return!0}an(){if(this.nn)return null;let t=new et(at.comparator);const e=[];for(const n of this.tn)if(!n.field.isKeyField())if(n.op==="array-contains"||n.op==="array-contains-any")e.push(new We(n.field,2));else{if(t.has(n.field))continue;t=t.add(n.field),e.push(new We(n.field,0))}for(const n of this.en)n.field.isKeyField()||t.has(n.field)||(t=t.add(n.field),e.push(new We(n.field,n.dir==="asc"?0:1)));return new An(An.UNKNOWN_ID,this.collectionId,e,Rn.empty())}sn(t){for(const e of this.tn)if(this.on(e,t))return!0;return!1}on(t,e){if(t===void 0||!t.field.isEqual(e.fieldPath))return!1;const n=t.op==="array-contains"||t.op==="array-contains-any";return e.kind===2===n}_n(t,e){return!!t.field.isEqual(e.fieldPath)&&(e.kind===0&&t.dir==="asc"||e.kind===1&&t.dir==="desc")}}function Sh(r){var t,e;if(L(r instanceof H||r instanceof tt),r instanceof H){if(r instanceof Gl){const s=((e=(t=r.value.arrayValue)===null||t===void 0?void 0:t.values)===null||e===void 0?void 0:e.map((i=>H.create(r.field,"==",i))))||[];return tt.create(s,"or")}return r}const n=r.filters.map((s=>Sh(s)));return tt.create(n,r.op)}function Vp(r){if(r.getFilters().length===0)return[];const t=wo(Sh(r));return L(Vh(t)),To(t)||vo(t)?[t]:t.getFilters()}function To(r){return r instanceof H}function vo(r){return r instanceof tt&&Fo(r)}function Vh(r){return To(r)||vo(r)||(function(e){if(e instanceof tt&&fo(e)){for(const n of e.getFilters())if(!To(n)&&!vo(n))return!1;return!0}return!1})(r)}function wo(r){if(L(r instanceof H||r instanceof tt),r instanceof H)return r;if(r.filters.length===1)return wo(r.filters[0]);const t=r.filters.map((n=>wo(n)));let e=tt.create(t,r.op);return e=Qs(e),Vh(e)?e:(L(e instanceof tt),L(Pn(e)),L(e.filters.length>1),e.filters.reduce(((n,s)=>Wo(n,s))))}function Wo(r,t){let e;return L(r instanceof H||r instanceof tt),L(t instanceof H||t instanceof tt),e=r instanceof H?t instanceof H?(function(s,i){return tt.create([s,i],"and")})(r,t):Ac(r,t):t instanceof H?Ac(t,r):(function(s,i){if(L(s.filters.length>0&&i.filters.length>0),Pn(s)&&Pn(i))return ql(s,i.getFilters());const a=fo(s)?s:i,u=fo(s)?i:s,c=a.filters.map((h=>Wo(h,u)));return tt.create(c,"or")})(r,t),Qs(e)}function Ac(r,t){if(Pn(t))return ql(t,r.getFilters());{const e=t.filters.map((n=>Wo(r,n)));return tt.create(e,"or")}}function Qs(r){if(L(r instanceof H||r instanceof tt),r instanceof H)return r;const t=r.getFilters();if(t.length===1)return Qs(t[0]);if(Bl(r))return r;const e=t.map((s=>Qs(s))),n=[];return e.forEach((s=>{s instanceof H?n.push(s):s instanceof tt&&(s.op===r.op?n.push(...s.filters):n.push(s))})),n.length===1?n[0]:tt.create(n,r.op)}class Cp{constructor(){this.un=new Ho}
vendor: 1,526 bytes, line 12
12addToCollectionParentIndex(t,e){return this.un.add(e),w.resolve()}getCollectionParents(t,e){return w.resolve(this.un.getEntries(e))}addFieldIndex(t,e){return w.resolve()}deleteFieldIndex(t,e){return w.resolve()}deleteAllFieldIndexes(t){return w.resolve()}createTargetIndexes(t,e){return w.resolve()}getDocumentsMatchingTarget(t,e){return w.resolve(null)}getIndexType(t,e){return w.resolve(0)}getFieldIndexes(t,e){return w.resolve([])}getNextCollectionGroupToUpdate(t){return w.resolve(null)}getMinOffset(t,e){return w.resolve(jt.min())}getMinOffsetFromCollectionGroup(t,e){return w.resolve(jt.min())}updateCollectionGroup(t,e,n){return w.resolve()}updateIndexEntries(t,e){return w.resolve()}}class Ho{constructor(){this.index={}}add(t){const e=t.lastSegment(),n=t.popLast(),s=this.index[e]||new et(W.comparator),i=!s.has(n);return this.index[e]=s.add(n),i}has(t){const e=t.lastSegment(),n=t.popLast(),s=this.index[e];return s&&s.has(n)}getEntries(t){return(this.index[t]||new et(W.comparator)).toArray()}}const As=new Uint8Array(0);class Dp{constructor(t,e){this.databaseId=e,this.cn=new Ho,this.ln=new se((n=>Ye(n)),((n,s)=>zr(n,s))),this.uid=t.uid||""}addToCollectionParentIndex(t,e){if(!this.cn.has(e)){const n=e.lastSegment(),s=e.popLast();t.addOnCommittedListener((()=>{this.cn.add(e)}));const i={collectionId:n,parent:Nt(s)};return Rc(t).put(i)}return w.resolve()}getCollectionParents(t,e){const n=[],s=IDBKeyRange.bound([e,""],[Tl(e),""],!1,!0);return Rc(t).U(s).next((i=>{for(const a of i){if(a.collectionId!==e)break;
12n.push(Kt(a.parent))}return n}))}addFieldIndex(t,e){const n=pr(t),s=(function(u){return{indexId:u.indexId,collectionGroup:u.collectionGroup,fields:u.fields.map((c=>[c.fieldPath.canonicalString(),c.kind]))}})(e);delete s.indexId;const i=n.add(s);if(e.indexState){const a=gn(t);return i.next((u=>{a.put(yc(u,this.uid,e.indexState.sequenceNumber,e.indexState.offset))}))}return i.next()}deleteFieldIndex(t,e){const n=pr(t),s=gn(t),i=mn(t);return n.delete(e.indexId).next((()=>s.delete(IDBKeyRange.bound([e.indexId],[e.indexId+1],!1,!0)))).next((()=>i.delete(IDBKeyRange.bound([e.indexId],[e.indexId+1],!1,!0))))}deleteAllFieldIndexes(t){const e=pr(t),n=mn(t),s=gn(t);return e.j().next((()=>n.j())).next((()=>s.j()))}createTargetIndexes(t,e){return w.forEach(this.hn(e),(n=>this.getIndexType(t,n).next((s=>{if(s===0||s===1){const i=new wc(n).an();if(i!=null)return this.addFieldIndex(t,i)}}))))}getDocumentsMatchingTarget(t,e){const n=mn(t);let s=!0;const i=new Map;return w.forEach(this.hn(e),(a=>this.Pn(t,a).next((u=>{s&&(s=!!u),i.set(a,u)})))).next((()=>{if(s){let a=G();const u=[];return w.forEach(i,((c,h)=>{x("IndexedDbIndexManager",`Using index ${(function(B){return`id=${B.indexId}|cg=${B.collectionGroup}|f=${B.fields.map(($=>`${$.fieldPath}:${$.kind}`)).join(",")}`})(c)} to execute ${Ye(e)}`);const f=(function(B,$){const Z=uo($);if(Z===void 0)return null;for(const K of zs(B,Z.fieldPath))switch(K.op){case"array-contains-any":return K.value.arrayValue.values||[];case"array-contains":return[K.value]}return null})(h,c),g=(function(B,$){const Z=new Map;for(const K of je($))for(const E of zs(B,K.fieldPath))switch(E.op){case"==":case"in":Z.set(K.fieldPath.canonicalString(),E.value);break;case"not-in":case"!=":return Z.set(K.fieldPath.canonicalString(),E.value),Array.from(Z.values())}return null})(h,c),_=(function(B,$){const Z=[];let K=!0;for(const E of je($)){const p=E.kind===0?rc(B,E.fieldPath,B.startAt):sc(B,E.fieldPath,B.startAt);Z.push(p.value),K&&(K=p.inclusive)}return new Ae(Z,K)})(h,c),R=(function(B,$){const Z=[];let K=!0;for(const E of je($)){const p=E.kind===0?sc(B,E.fieldPath,B.endAt):rc(B,E.fieldPath,B.endAt);Z.push(p.value),K&&(K=p.inclusive)}return new Ae(Z,K)})(h,c),C=this.In(c,h,_),N=this.In(c,h,R),V=this.Tn(c,h,g),q=this.En(c.indexId,f,C,_.inclusive,N,R.inclusive,V);return w.forEach(q,(j=>n.G(j,e.limit).next((B=>{B.forEach(($=>{const Z=O.fromSegments($.documentKey);a.has(Z)||(a=a.add(Z),u.push(Z))}))}))))})).next((()=>u))}return w.resolve(null)}))}hn(t){let e=this.ln.get(t);return e||(t.filters.length===0?e=[t]:e=Vp(tt.create(t.filters,"and")).map((n=>go(t.path,t.collectionGroup,t.orderBy,n.getFilters(),t.limit,t.startAt,t.endAt))),this.ln.set(t,e),e)}En(t,e,n,s,i,a,u){const c=(e!=null?e.length:1)*Math.max(n.length,i.length),h=c/(e!=null?e.length:1),f=[];for(let g=0;g<c;++g){const _=e?this.dn(e[g/h]):As,R=this.An(t,_,n[g%h],s),C=this.Rn(t,_,i[g%h],a),N=u.map((V=>this.An(t,_,V,!0)));f.push(...this.createRange(R,C,N))}return f}An(t,e,n,s){const i=new $e(t,O.empty(),e,n);return s?i:i.Zt()}Rn(t,e,n,s){const i=new $e(t,O.empty(),e,n);return s?i.Zt():i}Pn(t,e){const n=new wc(e),s=e.collectionGroup!=null?e.collectionGroup:e.path.lastSegment();return this.getFieldIndexes(t,s).next((i=>{let a=null;for(const u of i)n.rn(u)&&(!a||u.fields.length>a.fields.length)&&(a=u);return a}))}getIndexType(t,e){let n=2;const s=this.hn(e);return w.forEach(s,(i=>this.Pn(t,i).next((a=>{a?n!==0&&a.fields.length<(function(c){let h=new et(at.comparator),f=!1;for(const g of c.filters)for(const _ of g.getFlattenedFilters())_.field.isKeyField()||(_.op==="array-contains"||_.op==="array-contains-any"?f=!0:h=h.add(_.field));for(const g of c.orderBy)g.field.isKeyField()||(h=h.add(g.field));return h.size+(f?1:0)})(i)&&(n=1):n=0})))).next((()=>(function(a){return a.limit!==null})(e)&&s.length>1&&n===2?1:n))}Vn(t,e){const n=new gr;for(const s of je(t)){const i=e.data.field(s.fieldPath);if(i==null)return null;const a=n.Yt(s.kind);Ke.vt.It(i,a)}return n.zt()}dn(t){const e=new gr;return Ke.vt.It(t,e.Yt(0)),e.zt()}mn(t,e){const n=new gr;return Ke.vt.It(Je(this.databaseId,e),n.Yt((function(i){const a=je(i);return a.length===0?0:a[a.length-1].kind})(t))),n.zt()}Tn(t,e,n){if(n===null)return[];let s=[];s.push(new gr);let i=0;for(const a of je(t)){const u=n[i++];for(const c of s)if(this.fn(e,a.fieldPath)&&Or(u))s=this.gn(s,a,u);else{const h=c.Yt(a.kind);Ke.vt.It(u,h)}}return this.pn(s)}In(t,e,n){return this.Tn(t,e,n.position)}pn(t){const e=[];for(let n=0;n<t.length;++n)e[n]=t[n].zt();return e}gn(t,e,n){const s=[...t],i=[];for(const a of n.arrayValue.values||[])for(const u of s){const c=new gr;
12c.seed(u.zt()),Ke.vt.It(a,c.Yt(e.kind)),i.push(c)}return i}fn(t,e){return!!t.filters.find((n=>n instanceof H&&n.field.isEqual(e)&&(n.op==="in"||n.op==="not-in")))}getFieldIndexes(t,e){const n=pr(t),s=gn(t);return(e?n.U("collectionGroupIndex",IDBKeyRange.bound(e,e)):n.U()).next((i=>{const a=[];return w.forEach(i,(u=>s.get([u.indexId,this.uid]).next((c=>{a.push((function(f,g){const _=g?new Rn(g.sequenceNumber,new jt(en(g.readTime),new O(Kt(g.documentKey)),g.largestBatchId)):Rn.empty(),R=f.fields.map((([C,N])=>new We(at.fromServerFormat(C),N)));return new An(f.indexId,f.collectionGroup,R,_)})(u,c))})))).next((()=>a))}))}getNextCollectionGroupToUpdate(t){return this.getFieldIndexes(t).next((e=>e.length===0?null:(e.sort(((n,s)=>{const i=n.indexState.sequenceNumber-s.indexState.sequenceNumber;return i!==0?i:z(n.collectionGroup,s.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(t,e,n){const s=pr(t),i=gn(t);return this.yn(t).next((a=>s.U("collectionGroupIndex",IDBKeyRange.bound(e,e)).next((u=>w.forEach(u,(c=>i.put(yc(c.indexId,this.uid,a,n))))))))}updateIndexEntries(t,e){const n=new Map;return w.forEach(e,((s,i)=>{const a=n.get(s.collectionGroup);return(a?w.resolve(a):this.getFieldIndexes(t,s.collectionGroup)).next((u=>(n.set(s.collectionGroup,u),w.forEach(u,(c=>this.wn(t,s,c).next((h=>{const f=this.Sn(i,c);return h.isEqual(f)?w.resolve():this.bn(t,i,c,h,f)})))))))}))}Dn(t,e,n,s){return mn(t).put({indexId:s.indexId,uid:this.uid,arrayValue:s.arrayValue,directionalValue:s.directionalValue,orderedDocumentKey:this.mn(n,e.key),documentKey:e.key.path.toArray()})}vn(t,e,n,s){return mn(t).delete([s.indexId,this.uid,s.arrayValue,s.directionalValue,this.mn(n,e.key),e.key.path.toArray()])}wn(t,e,n){const s=mn(t);let i=new et(he);return s.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.mn(n,e)])},((a,u)=>{i=i.add(new $e(n.indexId,e,u.arrayValue,u.directionalValue))})).next((()=>i))}Sn(t,e){let n=new et(he);const s=this.Vn(e,t);if(s==null)return n;const i=uo(e);if(i!=null){const a=t.data.field(i.fieldPath);if(Or(a))for(const u of a.arrayValue.values||[])n=n.add(new $e(e.indexId,t.key,this.dn(u),s))}else n=n.add(new $e(e.indexId,t.key,As,s));return n}bn(t,e,n,s,i){x("IndexedDbIndexManager","Updating index entries for document '%s'",e.key);const a=[];return(function(c,h,f,g,_){const R=c.getIterator(),C=h.getIterator();let N=fn(R),V=fn(C);for(;N||V;){let q=!1,j=!1;if(N&&V){const B=f(N,V);B<0?j=!0:B>0&&(q=!0)}else N!=null?j=!0:q=!0;q?(g(V),V=fn(C)):j?(_(N),N=fn(R)):(N=fn(R),V=fn(C))}})(s,i,he,(u=>{a.push(this.Dn(t,e,n,u))}),(u=>{a.push(this.vn(t,e,n,u))})),w.waitFor(a)}yn(t){let e=1;return gn(t).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((n,s,i)=>{i.done(),e=s.sequenceNumber+1})).next((()=>e))}createRange(t,e,n){n=n.sort(((a,u)=>he(a,u))).filter(((a,u,c)=>!u||he(a,c[u-1])!==0));const s=[];
12s.push(t);for(const a of n){const u=he(a,t),c=he(a,e);if(u===0)s[0]=t.Zt();else if(u>0&&c<0)s.push(a),s.push(a.Zt());else if(c>0)break}s.push(e);const i=[];for(let a=0;a<s.length;a+=2){if(this.Cn(s[a],s[a+1]))return[];const u=[s[a].indexId,this.uid,s[a].arrayValue,s[a].directionalValue,As,[]],c=[s[a+1].indexId,this.uid,s[a+1].arrayValue,s[a+1].directionalValue,As,[]];i.push(IDBKeyRange.bound(u,c))}return i}Cn(t,e){return he(t,e)>0}getMinOffsetFromCollectionGroup(t,e){return this.getFieldIndexes(t,e).next(bc)}getMinOffset(t,e){return w.mapArray(this.hn(e),(n=>this.Pn(t,n).next((s=>s||F())))).next(bc)}}function Rc(r){return yt(r,"collectionParents")}function mn(r){return yt(r,"indexEntries")}function pr(r){return yt(r,"indexConfiguration")}function gn(r){return yt(r,"indexState")}function bc(r){L(r.length!==0);let t=r[0].indexState.offset,e=t.largestBatchId;for(let n=1;n<r.length;n++){const s=r[n].indexState.offset;ko(s,t)<0&&(t=s),e<s.largestBatchId&&(e=s.largestBatchId)}return new jt(t.readTime,t.documentKey,e)}const Pc={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class xt{constructor(t,e,n){this.cacheSizeCollectionThreshold=t,this.percentileToCollect=e,this.maximumSequenceNumbersToCollect=n}static withCacheSize(t){return new xt(t,xt.DEFAULT_COLLECTION_PERCENTILE,xt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Ch(r,t,e){const n=r.store("mutations"),s=r.store("documentMutations"),i=[],a=IDBKeyRange.only(e.batchId);let u=0;const c=n.J({range:a},((f,g,_)=>(u++,_.delete())));i.push(c.next((()=>{L(u===1)})));const h=[];for(const f of e.mutations){const g=Sl(t,f.key.path,e.batchId);i.push(s.delete(g)),h.push(f.key)}return w.waitFor(i).next((()=>h))}function Ws(r){if(!r)return 0;let t;if(r.document)t=r.document;else if(r.unknownDocument)t=r.unknownDocument;else{if(!r.noDocument)throw F();t=r.noDocument}return JSON.stringify(t).length}xt.DEFAULT_COLLECTION_PERCENTILE=10,xt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,xt.DEFAULT=new xt(41943040,xt.DEFAULT_COLLECTION_PERCENTILE,xt.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),xt.DISABLED=new xt(-1,0,0);class ci{constructor(t,e,n,s){this.userId=t,this.serializer=e,this.indexManager=n,this.referenceDelegate=s,this.Fn={}}static lt(t,e,n,s){L(t.uid!=="");const i=t.isAuthenticated()?t.uid:"";return new ci(i,e,n,s)}checkEmpty(t){let e=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return de(t).J({index:"userMutationsIndex",range:n},((s,i,a)=>{e=!1,a.done()})).next((()=>e))}addMutationBatch(t,e,n,s){const i=En(t),a=de(t);return a.add({}).next((u=>{L(typeof u=="number");const c=new jo(u,e,n,s),h=(function(R,C,N){const V=N.baseMutations.map((j=>Br(R.ct,j))),q=N.mutations.map((j=>Br(R.ct,j)));return{userId:C,batchId:N.batchId,localWriteTimeMs:N.localWriteTime.toMillis(),baseMutations:V,mutations:q}})(this.serializer,this.userId,c),f=[];let g=new et(((_,R)=>z(_.canonicalString(),R.canonicalString())));for(const _ of s){const R=Sl(this.userId,_.key.path,u);g=g.add(_.key.path.popLast()),f.push(a.put(h)),f.push(i.put(R,yg))}return g.forEach((_=>{f.push(this.indexManager.addToCollectionParentIndex(t,_))})),t.addOnCommittedListener((()=>{this.Fn[u]=c.keys()})),w.waitFor(f).next((()=>c))}))}lookupMutationBatch(t,e){return de(t).get(e).next((n=>n?(L(n.userId===this.userId),Ge(this.serializer,n)):null))}Mn(t,e){return this.Fn[e]?w.resolve(this.Fn[e]):this.lookupMutationBatch(t,e).next((n=>{if(n){const s=n.keys();return this.Fn[e]=s,s}return null}))}getNextMutationBatchAfterBatchId(t,e){const n=e+1,s=IDBKeyRange.lowerBound([this.userId,n]);let i=null;return de(t).J({index:"userMutationsIndex",range:s},((a,u,c)=>{u.userId===this.userId&&(L(u.batchId>=n),i=Ge(this.serializer,u)),c.done()})).next((()=>i))}getHighestUnacknowledgedBatchId(t){const e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return de(t).J({index:"userMutationsIndex",range:e,reverse:!0},((s,i,a)=>{n=i.batchId,a.done()})).next((()=>n))}getAllMutationBatches(t){const e=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return de(t).U("userMutationsIndex",e).next((n=>n.map((s=>Ge(this.serializer,s)))))}getAllMutationBatchesAffectingDocumentKey(t,e){const n=Cs(this.userId,e.path),s=IDBKeyRange.lowerBound(n),i=[];return En(t).J({range:s},((a,u,c)=>{const[h,f,g]=a,_=Kt(f);if(h===this.userId&&e.path.isEqual(_))return de(t).get(g).next((R=>{if(!R)throw F();L(R.userId===this.userId),i.push(Ge(this.serializer,R))}));c.done()})).next((()=>i))}getAllMutationBatchesAffectingDocumentKeys(t,e){let n=new et(z);const s=[];return e.forEach((i=>{const a=Cs(this.userId,i.path),u=IDBKeyRange.lowerBound(a),c=En(t).J({range:u},((h,f,g)=>{const[_,R,C]=h,N=Kt(R);_===this.userId&&i.path.isEqual(N)?n=n.add(C):g.done()}));s.push(c)})),w.waitFor(s).next((()=>this.xn(t,n)))}getAllMutationBatchesAffectingQuery(t,e){const n=e.path,s=n.length+1,i=Cs(this.userId,n),a=IDBKeyRange.lowerBound(i);let u=new et(z);return En(t).J({range:a},((c,h,f)=>{const[g,_,R]=c,C=Kt(_);g===this.userId&&n.isPrefixOf(C)?C.length===s&&(u=u.add(R)):f.done()})).next((()=>this.xn(t,u)))}xn(t,e){const n=[],s=[];return e.forEach((i=>{s.push(de(t).get(i).next((a=>{if(a===null)throw F();L(a.userId===this.userId),n.push(Ge(this.serializer,a))})))})),w.waitFor(s).next((()=>n))}removeMutationBatch(t,e){return Ch(t._e,this.userId,e).next((n=>(t.addOnCommittedListener((()=>{this.On(e.batchId)}
12)),w.forEach(n,(s=>this.referenceDelegate.markPotentiallyOrphaned(t,s))))))}On(t){delete this.Fn[t]}performConsistencyCheck(t){return this.checkEmpty(t).next((e=>{if(!e)return w.resolve();const n=IDBKeyRange.lowerBound((function(a){return[a]})(this.userId)),s=[];return En(t).J({range:n},((i,a,u)=>{if(i[0]===this.userId){const c=Kt(i[1]);s.push(c)}else u.done()})).next((()=>{L(s.length===0)}))}))}containsKey(t,e){return Dh(t,this.userId,e)}Nn(t){return xh(t).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Dh(r,t,e){const n=Cs(t,e.path),s=n[1],i=IDBKeyRange.lowerBound(n);let a=!1;return En(r).J({range:i,H:!0},((u,c,h)=>{const[f,g,_]=u;f===t&&g===s&&(a=!0),h.done()})).next((()=>a))}function de(r){return yt(r,"mutations")}function En(r){return yt(r,"documentMutations")}function xh(r){return yt(r,"mutationQueues")}class nn{constructor(t){this.Ln=t}next(){return this.Ln+=2,this.Ln}static Bn(){return new nn(0)}static kn(){return new nn(-1)}}class xp{constructor(t,e){this.referenceDelegate=t,this.serializer=e}allocateTargetId(t){return this.qn(t).next((e=>{const n=new nn(e.highestTargetId);return e.highestTargetId=n.next(),this.Qn(t,e).next((()=>e.highestTargetId))}))}getLastRemoteSnapshotVersion(t){return this.qn(t).next((e=>U.fromTimestamp(new lt(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(t){return this.qn(t).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(t,e,n){return this.qn(t).next((s=>(s.highestListenSequenceNumber=e,n&&(s.lastRemoteSnapshotVersion=n.toTimestamp()),e>s.highestListenSequenceNumber&&(s.highestListenSequenceNumber=e),this.Qn(t,s))))}addTargetData(t,e){return this.Kn(t,e).next((()=>this.qn(t).next((n=>(n.targetCount+=1,this.$n(e,n),this.Qn(t,n))))))}updateTargetData(t,e){return this.Kn(t,e)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next((()=>pn(t).delete(e.targetId))).next((()=>this.qn(t))).next((n=>(L(n.targetCount>0),n.targetCount-=1,this.Qn(t,n))))}removeTargets(t,e,n){let s=0;const i=[];return pn(t).J(((a,u)=>{const c=vr(u);c.sequenceNumber<=e&&n.get(c.targetId)===null&&(s++,i.push(this.removeTargetData(t,c)))})).next((()=>w.waitFor(i))).next((()=>s))}forEachTarget(t,e){return pn(t).J(((n,s)=>{const i=vr(s);e(i)}))}qn(t){return Sc(t).get("targetGlobalKey").next((e=>(L(e!==null),e)))}Qn(t,e){return Sc(t).put("targetGlobalKey",e)}Kn(t,e){return pn(t).put(Ph(this.serializer,e))}$n(t,e){let n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n}getTargetCount(t){return this.qn(t).next((e=>e.targetCount))}getTargetData(t,e){const n=Ye(e),s=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let i=null;return pn(t).J({range:s,index:"queryTargetsIndex"},((a,u,c)=>{const h=vr(u);zr(e,h.target)&&(i=h,c.done())})).next((()=>i))}addMatchingKeys(t,e,n){const s=[],i=me(t);return e.forEach((a=>{const u=Nt(a.path);s.push(i.put({targetId:n,path:u})),s.push(this.referenceDelegate.addReference(t,n,a))})),w.waitFor(s)}removeMatchingKeys(t,e,n){const s=me(t);return w.forEach(e,(i=>{const a=Nt(i.path);return w.waitFor([s.delete([n,a]),this.referenceDelegate.removeReference(t,n,i)])}))}removeMatchingKeysForTargetId(t,e){const n=me(t),s=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(s)}getMatchingKeysForTargetId(t,e){const n=IDBKeyRange.bound([e],[e+1],!1,!0),s=me(t);let i=G();return s.J({range:n,H:!0},((a,u,c)=>{const h=Kt(a[1]),f=new O(h);i=i.add(f)})).next((()=>i))}containsKey(t,e){const n=Nt(e.path),s=IDBKeyRange.bound([n],[Tl(n)],!1,!0);let i=0;return me(t).J({index:"documentTargetsIndex",H:!0,range:s},(([a,u],c,h)=>{a!==0&&(i++,h.done())})).next((()=>i>0))}ot(t,e){return pn(t).get(e).next((n=>n?vr(n):null))}}function pn(r){return yt(r,"targets")}function Sc(r){return yt(r,"targetGlobal")}function me(r){return yt(r,"targetDocuments")}function Vc([r,t],[e,n]){const s=z(r,e);return s===0?z(t,n):s}class Np{constructor(t){this.Un=t,this.buffer=new et(Vc),this.Wn=0}Gn(){return++this.Wn}zn(t){const e=[t,this.Gn()];if(this.buffer.size<this.Un)this.buffer=this.buffer.add(e);else{const n=this.buffer.last();Vc(e,n)<0&&(this.buffer=this.buffer.delete(n).add(e))}}get maxValue(){return this.buffer.last()[0]}}class Nh{constructor(t,e,n){this.garbageCollector=t,this.asyncQueue=e,this.localStore=n,this.jn=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Hn(6e4)}stop(){this.jn&&(this.jn.cancel(),this.jn=null)}get started(){return this.jn!==null}Hn(t){x("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,(async()=>{this.jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Ce(e)?x("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Ve(e)}await this.Hn(3e5)}))}}class kp{constructor(t,e){this.Jn=t,this.params=e}calculateTargetCount(t,e){return this.Jn.Yn(t).next((n=>Math.floor(e/100*n)))}nthSequenceNumber(t,e){if(e===0)return w.resolve(Ft.oe);const n=new Np(e);
12return this.Jn.forEachTarget(t,(s=>n.zn(s.sequenceNumber))).next((()=>this.Jn.Zn(t,(s=>n.zn(s))))).next((()=>n.maxValue))}removeTargets(t,e,n){return this.Jn.removeTargets(t,e,n)}removeOrphanedDocuments(t,e){return this.Jn.removeOrphanedDocuments(t,e)}collect(t,e){return this.params.cacheSizeCollectionThreshold===-1?(x("LruGarbageCollector","Garbage collection skipped; disabled"),w.resolve(Pc)):this.getCacheSize(t).next((n=>n<this.params.cacheSizeCollectionThreshold?(x("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Pc):this.Xn(t,e)))}getCacheSize(t){return this.Jn.getCacheSize(t)}Xn(t,e){let n,s,i,a,u,c,h;const f=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next((g=>(g>this.params.maximumSequenceNumbersToCollect?(x("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${g}`),s=this.params.maximumSequenceNumbersToCollect):s=g,a=Date.now(),this.nthSequenceNumber(t,s)))).next((g=>(n=g,u=Date.now(),this.removeTargets(t,n,e)))).next((g=>(i=g,c=Date.now(),this.removeOrphanedDocuments(t,n)))).next((g=>(h=Date.now(),_n()<=Y.DEBUG&&x("LruGarbageCollector",`LRU Garbage Collection 13 Counted targets in ${a-f}ms 14 Determined least recently used ${s} in `+(u-a)+`ms 15 Removed ${i} targets in `+(c-u)+`ms 16 Removed ${g} documents in `+(h-c)+`ms 17Total Duration: ${h-f}ms`),w.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:g}))))}}function kh(r,t){return new kp(r,t)}class Mp{constructor(t,e){this.db=t,this.garbageCollector=kh(this,e)}Yn(t){const e=this.er(t);return this.db.getTargetCache().getTargetCount(t).next((n=>e.next((s=>n+s))))}er(t){let e=0;return this.Zn(t,(n=>{e++})).next((()=>e))}forEachTarget(t,e){return this.db.getTargetCache().forEachTarget(t,e)}Zn(t,e){return this.tr(t,((n,s)=>e(s)))}addReference(t,e,n){return Rs(t,n)}removeReference(t,e,n){return Rs(t,n)}removeTargets(t,e,n){return this.db.getTargetCache().removeTargets(t,e,n)}markPotentiallyOrphaned(t,e){return Rs(t,e)}nr(t,e){return(function(s,i){let a=!1;return xh(s).Y((u=>Dh(s,u,i).next((c=>(c&&(a=!0),w.resolve(!c)))))).next((()=>a))})(t,e)}removeOrphanedDocuments(t,e){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let i=0;return this.tr(t,((a,u)=>{if(u<=e){const c=this.nr(t,a).next((h=>{if(!h)return i++,n.getEntry(t,a).next((()=>(n.removeEntry(a,U.min()),me(t).delete((function(g){return[0,Nt(g.path)]})(a)))))}));s.push(c)}})).next((()=>w.waitFor(s))).next((()=>n.apply(t))).next((()=>i))}removeTarget(t,e){const n=e.withSequenceNumber(t.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(t,n)}updateLimboDocument(t,e){return Rs(t,e)}tr(t,e){const n=me(t);let s,i=Ft.oe;return n.J({index:"documentTargetsIndex"},(([a,u],{path:c,sequenceNumber:h})=>{a===0?(i!==Ft.oe&&e(new O(Kt(s)),i),i=h,s=c):i=Ft.oe})).next((()=>{i!==Ft.oe&&e(new O(Kt(s)),i)}))}getCacheSize(t){return this.db.getRemoteDocumentCache().getSize(t)}}function Rs(r,t){return me(r).put((function(n,s){return{targetId:0,path:Nt(n.path),sequenceNumber:s}})(t,r.currentSequenceNumber))}class Mh{constructor(){this.changes=new se((t=>t.toString()),((t,e)=>t.isEqual(e))),this.changesApplied=!1}addEntry(t){this.assertNotApplied(),this.changes.set(t.key,t)}removeEntry(t,e){this.assertNotApplied(),this.changes.set(t,ot.newInvalidDocument(t).setReadTime(e))}getEntry(t,e){this.assertNotApplied();const n=this.changes.get(e);return n!==void 0?w.resolve(n):this.getFromCache(t,e)}getEntries(t,e){return this.getAllFromCache(t,e)}apply(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)}assertNotApplied(){}}class Op{constructor(t){this.serializer=t}setIndexManager(t){this.indexManager=t}addEntry(t,e,n){return Ue(t).put(n)}removeEntry(t,e,n){return Ue(t).delete((function(i,a){const u=i.path.toArray();return[u.slice(0,u.length-2),u[u.length-2],$s(a),u[u.length-1]]})(e,n))}updateMetadata(t,e){return this.getMetadata(t).next((n=>(n.byteSize+=e,this.rr(t,n))))}getEntry(t,e){let n=ot.newInvalidDocument(e);return Ue(t).J({index:"documentKeyIndex",range:IDBKeyRange.only(_r(e))},((s,i)=>{n=this.ir(e,i)})).next((()=>n))}sr(t,e){let n={size:0,document:ot.newInvalidDocument(e)};return Ue(t).J({index:"documentKeyIndex",range:IDBKeyRange.only(_r(e))},((s,i)=>{n={document:this.ir(e,i),size:Ws(i)}})).next((()=>n))}getEntries(t,e){let n=Bt();return this._r(t,e,((s,i)=>{const a=this.ir(s,i);n=n.insert(s,a)})).next((()=>n))}ar(t,e){let n=Bt(),s=new st(O.comparator);return this._r(t,e,((i,a)=>{const u=this.ir(i,a);n=n.insert(i,u),s=s.insert(i,Ws(a))})).next((()=>({documents:n,ur:s})))}_r(t,e,n){if(e.isEmpty())return w.resolve();let s=new et(xc);e.forEach((c=>s=s.add(c)));const i=IDBKeyRange.bound(_r(s.first()),_r(s.last())),a=s.getIterator();let u=a.getNext();return Ue(t).J({index:"documentKeyIndex",range:i},((c,h,f)=>{const g=O.fromSegments([...h.prefixPath,h.collectionGroup,h.documentId]);for(;u&&xc(u,g)<0;)n(u,null),u=a.getNext();u&&u.isEqual(g)&&(n(u,h),u=a.hasNext()?a.getNext():null),u?f.$(_r(u)):f.done()})).next((()=>{for(;u;)n(u,null),u=a.hasNext()?a.getNext():null}))}getDocumentsMatchingQuery(t,e,n,s,i){const a=e.path,u=[a.popLast().toArray(),a.lastSegment(),$s(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],c=[a.popLast().toArray(),a.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Ue(t).U(IDBKeyRange.bound(u,c,!0)).next((h=>{i?.incrementDocumentReadCount(h.length);let f=Bt();for(const g of h){const _=this.ir(O.fromSegments(g.prefixPath.concat(g.collectionGroup,g.documentId)),g);
17_.isFoundDocument()&&(Kr(e,_)||s.has(_.key))&&(f=f.insert(_.key,_))}return f}))}getAllFromCollectionGroup(t,e,n,s){let i=Bt();const a=Dc(e,n),u=Dc(e,jt.max());return Ue(t).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(a,u,!0)},((c,h,f)=>{const g=this.ir(O.fromSegments(h.prefixPath.concat(h.collectionGroup,h.documentId)),h);i=i.insert(g.key,g),i.size===s&&f.done()})).next((()=>i))}newChangeBuffer(t){return new Fp(this,!!t&&t.trackRemovals)}getSize(t){return this.getMetadata(t).next((e=>e.byteSize))}getMetadata(t){return Cc(t).get("remoteDocumentGlobalKey").next((e=>(L(!!e),e)))}rr(t,e){return Cc(t).put("remoteDocumentGlobalKey",e)}ir(t,e){if(e){const n=vp(this.serializer,e);if(!(n.isNoDocument()&&n.version.isEqual(U.min())))return n}return ot.newInvalidDocument(t)}}function Oh(r){return new Op(r)}class Fp extends Mh{constructor(t,e){super(),this.cr=t,this.trackRemovals=e,this.lr=new se((n=>n.toString()),((n,s)=>n.isEqual(s)))}applyChanges(t){const e=[];let n=0,s=new et(((i,a)=>z(i.canonicalString(),a.canonicalString())));
17return this.changes.forEach(((i,a)=>{const u=this.lr.get(i);if(e.push(this.cr.removeEntry(t,i,u.readTime)),a.isValidDocument()){const c=pc(this.cr.serializer,a);s=s.add(i.path.popLast());const h=Ws(c);n+=h-u.size,e.push(this.cr.addEntry(t,i,c))}else if(n-=u.size,this.trackRemovals){const c=pc(this.cr.serializer,a.convertToNoDocument(U.min()));e.push(this.cr.addEntry(t,i,c))}})),s.forEach((i=>{e.push(this.cr.indexManager.addToCollectionParentIndex(t,i))})),e.push(this.cr.updateMetadata(t,n)),w.waitFor(e)}getFromCache(t,e){return this.cr.sr(t,e).next((n=>(this.lr.set(e,{size:n.size,readTime:n.document.readTime}),n.document)))}getAllFromCache(t,e){return this.cr.ar(t,e).next((({documents:n,ur:s})=>(s.forEach(((i,a)=>{this.lr.set(i,{size:a,readTime:n.get(i).readTime})})),n)))}}function Cc(r){return yt(r,"remoteDocumentGlobal")}function Ue(r){return yt(r,"remoteDocumentsV14")}function _r(r){const t=r.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Dc(r,t){const e=t.documentKey.path.toArray();return[r,$s(t.readTime),e.slice(0,e.length-2),e.length>0?e[e.length-1]:""]}function xc(r,t){const e=r.path.toArray(),n=t.path.toArray();let s=0;for(let i=0;i<e.length-2&&i<n.length-2;++i)if(s=z(e[i],n[i]),s)return s;return s=z(e.length,n.length),s||(s=z(e[e.length-2],n[n.length-2]),s||z(e[e.length-1],n[n.length-1]))}class Lp{constructor(t,e){this.overlayedDocument=t,this.mutatedFields=e}}class Fh{constructor(t,e,n,s){this.remoteDocumentCache=t,this.mutationQueue=e,this.documentOverlayCache=n,this.indexManager=s}getDocument(t,e){let n=null;return this.documentOverlayCache.getOverlay(t,e).next((s=>(n=s,this.remoteDocumentCache.getEntry(t,e)))).next((s=>(n!==null&&Pr(n.mutation,s,Lt.empty(),lt.now()),s)))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next((n=>this.getLocalViewOfDocuments(t,n,G()).next((()=>n))))}getLocalViewOfDocuments(t,e,n=G()){const s=$t();return this.populateOverlays(t,s,e).next((()=>this.computeViews(t,e,s,n).next((i=>{let a=Er();return i.forEach(((u,c)=>{a=a.insert(u,c.overlayedDocument)})),a}))))}getOverlayedDocuments(t,e){const n=$t();return this.populateOverlays(t,n,e).next((()=>this.computeViews(t,e,n,G())))}populateOverlays(t,e,n){const s=[];return n.forEach((i=>{e.has(i)||s.push(i)})),this.documentOverlayCache.getOverlays(t,s).next((i=>{i.forEach(((a,u)=>{e.set(a,u)}))}))}computeViews(t,e,n,s){let i=Bt();const a=br(),u=(function(){return br()})();return e.forEach(((c,h)=>{const f=n.get(h.key);s.has(h.key)&&(f===void 0||f.mutation instanceof ie)?i=i.insert(h.key,h):f!==void 0?(a.set(h.key,f.mutation.getFieldMask()),Pr(f.mutation,h,f.mutation.getFieldMask(),lt.now())):a.set(h.key,Lt.empty())})),this.recalculateAndSaveOverlays(t,i).next((c=>(c.forEach(((h,f)=>a.set(h,f))),e.forEach(((h,f)=>{var g;return u.set(h,new Lp(f,(g=a.get(h))!==null&&g!==void 0?g:null))})),u)))}recalculateAndSaveOverlays(t,e){const n=br();let s=new st(((a,u)=>a-u)),i=G();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t,e).next((a=>{for(const u of a)u.keys().forEach((c=>{const h=e.get(c);if(h===null)return;let f=n.get(c)||Lt.empty();f=u.applyToLocalView(h,f),n.set(c,f);const g=(s.get(u.batchId)||G()).add(c);s=s.insert(u.batchId,g)}))})).next((()=>{const a=[],u=s.getReverseIterator();for(;u.hasNext();){const c=u.getNext(),h=c.key,f=c.value,g=Zl();f.forEach((_=>{if(!i.has(_)){const R=oh(e.get(_),n.get(_));R!==null&&g.set(_,R),i=i.add(_)}})),a.push(this.documentOverlayCache.saveOverlays(t,h,g))}return w.waitFor(a)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next((n=>this.recalculateAndSaveOverlays(t,n)))}getDocumentsMatchingQuery(t,e,n,s){return(function(a){return O.isDocumentKey(a.path)&&a.collectionGroup===null&&a.filters.length===0})(e)?this.getDocumentsMatchingDocumentQuery(t,e.path):Lo(e)?this.getDocumentsMatchingCollectionGroupQuery(t,e,n,s):this.getDocumentsMatchingCollectionQuery(t,e,n,s)}getNextDocuments(t,e,n,s){return this.remoteDocumentCache.getAllFromCollectionGroup(t,e,n,s).next((i=>{const a=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(t,e,n.largestBatchId,s-i.size):w.resolve($t());let u=-1,c=i;return a.next((h=>w.forEach(h,((f,g)=>(u<g.largestBatchId&&(u=g.largestBatchId),i.get(f)?w.resolve():this.remoteDocumentCache.getEntry(t,f).next((_=>{c=c.insert(f,_)}))))).next((()=>this.populateOverlays(t,h,i))).next((()=>this.computeViews(t,c,h,G()))).next((f=>({batchId:u,changes:Xl(f)})))))}))}getDocumentsMatchingDocumentQuery(t,e){return this.getDocument(t,new O(e)).next((n=>
17{let s=Er();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s}))}getDocumentsMatchingCollectionGroupQuery(t,e,n,s){const i=e.collectionGroup;let a=Er();return this.indexManager.getCollectionParents(t,i).next((u=>w.forEach(u,(c=>{const h=(function(g,_){return new re(_,null,g.explicitOrderBy.slice(),g.filters.slice(),g.limit,g.limitType,g.startAt,g.endAt)})(e,c.child(i));return this.getDocumentsMatchingCollectionQuery(t,h,n,s).next((f=>{f.forEach(((g,_)=>{a=a.insert(g,_)}))}))})).next((()=>a))))}getDocumentsMatchingCollectionQuery(t,e,n,s){let i;return this.documentOverlayCache.getOverlaysForCollection(t,e.path,n.largestBatchId).next((a=>(i=a,this.remoteDocumentCache.getDocumentsMatchingQuery(t,e,n,i,s)))).next((a=>{i.forEach(((c,h)=>{const f=h.getKey();a.get(f)===null&&(a=a.insert(f,ot.newInvalidDocument(f)))}));let u=Er();return a.forEach(((c,h)=>{const f=i.get(c);f!==void 0&&Pr(f.mutation,h,Lt.empty(),lt.now()),Kr(e,h)&&(u=u.insert(c,h))})),u}))}}class Bp{constructor(t){this.serializer=t,this.hr=new Map,this.Pr=new Map}getBundleMetadata(t,e){return w.resolve(this.hr.get(e))}saveBundleMetadata(t,e){return this.hr.set(e.id,(function(s){return{id:s.id,version:s.version,createTime:pt(s.createTime)}})(e)),w.resolve()}getNamedQuery(t,e){return w.resolve(this.Pr.get(e))}saveNamedQuery(t,e){return this.Pr.set(e.name,(function(s){return{name:s.name,query:Qo(s.bundledQuery),readTime:pt(s.readTime)}})(e)),w.resolve()}}class Up{constructor(){this.overlays=new st(O.comparator),this.Ir=new Map}getOverlay(t,e){return w.resolve(this.overlays.get(e))}getOverlays(t,e){const n=$t();return w.forEach(e,(s=>this.getOverlay(t,s).next((i=>{i!==null&&n.set(s,i)})))).next((()=>n))}saveOverlays(t,e,n){return n.forEach(((s,i)=>{this.ht(t,e,i)})),w.resolve()}removeOverlaysForBatchId(t,e,n){const s=this.Ir.get(n);return s!==void 0&&(s.forEach((i=>this.overlays=this.overlays.remove(i))),this.Ir.delete(n)),w.resolve()}getOverlaysForCollection(t,e,n){const s=$t(),i=e.length+1,a=new O(e.child("")),u=this.overlays.getIteratorFrom(a);for(;u.hasNext();){const c=u.getNext().value,h=c.getKey();if(!e.isPrefixOf(h.path))break;h.path.length===i&&c.largestBatchId>n&&s.set(c.getKey(),c)}return w.resolve(s)}getOverlaysForCollectionGroup(t,e,n,s){let i=new st(((h,f)=>h-f));const a=this.overlays.getIterator();for(;a.hasNext();){const h=a.getNext().value;if(h.getKey().getCollectionGroup()===e&&h.largestBatchId>n){let f=i.get(h.largestBatchId);f===null&&(f=$t(),i=i.insert(h.largestBatchId,f)),f.set(h.getKey(),h)}}const u=$t(),c=i.getIterator();for(;c.hasNext()&&(c.getNext().value.forEach(((h,f)=>u.set(h,f))),!(u.size()>=s)););return w.resolve(u)}ht(t,e,n){const s=this.overlays.get(n.key);if(s!==null){const a=this.Ir.get(s.largestBatchId).delete(n.key);this.Ir.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(n.key,new Go(e,n));let i=this.Ir.get(e);i===void 0&&(i=G(),this.Ir.set(e,i)),this.Ir.set(e,i.add(n.key))}}class qp{constructor(){this.sessionToken=dt.EMPTY_BYTE_STRING}getSessionToken(t){return w.resolve(this.sessionToken)}setSessionToken(t,e){return this.sessionToken=e,w.resolve()}}class Jo{constructor(){this.Tr=new et(It.Er),this.dr=new et(It.Ar)}isEmpty(){return this.Tr.isEmpty()}addReference(t,e){const n=new It(t,e);this.Tr=this.Tr.add(n),this.dr=this.dr.add(n)}Rr(t,e){t.forEach((n=>this.addReference(n,e)))}removeReference(t,e){this.Vr(new It(t,e))}mr(t,e){t.forEach((n=>this.removeReference(n,e)))}gr(t){const e=new O(new W([])),n=new It(e,t),s=new It(e,t+1),i=[];return this.dr.forEachInRange([n,s],(a=>{this.Vr(a),i.push(a.key)})),i}pr(){this.Tr.forEach((t=>this.Vr(t)))}Vr(t){this.Tr=this.Tr.delete(t),this.dr=this.dr.delete(t)}yr(t){const e=new O(new W([])),n=new It(e,t),s=new It(e,t+1);let i=G();return this.dr.forEachInRange([n,s],(a=>{i=i.add(a.key)})),i}containsKey(t){const e=new It(t,0),n=this.Tr.firstAfterOrEqual(e);return n!==null&&t.isEqual(n.key)}}class It{constructor(t,e){this.key=t,this.wr=e}static Er(t,e){return O.comparator(t.key,e.key)||z(t.wr,e.wr)}static Ar(t,e){return z(t.wr,e.wr)||O.comparator(t.key,e.key)}}class jp{constructor(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutation
17Queue=[],this.Sr=1,this.br=new et(It.Er)}checkEmpty(t){return w.resolve(this.mutationQueue.length===0)}addMutationBatch(t,e,n,s){const i=this.Sr;this.Sr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const a=new jo(i,e,n,s);this.mutationQueue.push(a);for(const u of s)this.br=this.br.add(new It(u.key,i)),this.indexManager.addToCollectionParentIndex(t,u.key.path.popLast());return w.resolve(a)}lookupMutationBatch(t,e){return w.resolve(this.Dr(e))}getNextMutationBatchAfterBatchId(t,e){const n=e+1,s=this.vr(n),i=s<0?0:s;return w.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return w.resolve(this.mutationQueue.length===0?-1:this.Sr-1)}getAllMutationBatches(t){return w.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(t,e){const n=new It(e,0),s=new It(e,Number.POSITIVE_INFINITY),i=[];return this.br.forEachInRange([n,s],(a=>{const u=this.Dr(a.wr);i.push(u)})),w.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(t,e){let n=new et(z);return e.forEach((s=>{const i=new It(s,0),a=new It(s,Number.POSITIVE_INFINITY);this.br.forEachInRange([i,a],(u=>{n=n.add(u.wr)}))})),w.resolve(this.Cr(n))}getAllMutationBatchesAffectingQuery(t,e){const n=e.path,s=n.length+1;let i=n;O.isDocumentKey(i)||(i=i.child(""));const a=new It(new O(i),0);let u=new et(z);return this.br.forEachWhile((c=>{const h=c.key.path;return!!n.isPrefixOf(h)&&(h.length===s&&(u=u.add(c.wr)),!0)}),a),w.resolve(this.Cr(u))}Cr(t){const e=[];return t.forEach((n=>{const s=this.Dr(n);s!==null&&e.push(s)})),e}removeMutationBatch(t,e){L(this.Fr(e.batchId,"removed")===0),this.mutationQueue.shift();let n=this.br;return w.forEach(e.mutations,(s=>{const i=new It(s.key,e.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(t,s.key)})).next((()=>{this.br=n}))}On(t){}containsKey(t,e){const n=new It(e,0),s=this.br.firstAfterOrEqual(n);return w.resolve(e.isEqual(s&&s.key))}performConsistencyCheck(t){return this.mutationQueue.length,w.resolve()}Fr(t,e){return this.vr(t)}vr(t){return this.mutationQueue.length===0?0:t-this.mutationQueue[0].batchId}Dr(t){const e=this.vr(t);return e<0||e>=this.mutationQueue.length?null:this.mutationQueue[e]}}class zp{constructor(t){this.Mr=t,this.docs=(function(){return new st(O.comparator)})(),this.size=0}setIndexManager(t){this.indexManager=t}addEntry(t,e){const n=e.key,s=this.docs.get(n),i=s?s.size:0,a=this.Mr(e);return this.docs=this.docs.insert(n,{document:e.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(t,n.path.popLast())}removeEntry(t){const e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}getEntry(t,e){const n=this.docs.get(e);return w.resolve(n?n.document.mutableCopy():ot.newInvalidDocument(e))}getEntries(t,e){let n=Bt();return e.forEach((s=>{const i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():ot.newInvalidDocument(s))})),w.resolve(n)}getDocumentsMatchingQuery(t,e,n,s){let i=Bt();const a=e.path,u=new O(a.child("")),c=this.docs.getIteratorFrom(u);for(;c.hasNext();){const{key:h,value:{document:f}}=c.getNext();if(!a.isPrefixOf(h.path))break;h.path.length>a.length+1||ko(wl(f),n)<=0||(s.has(f.key)||Kr(e,f))&&(i=i.insert(f.key,f.mutableCopy()))}return w.resolve(i)}getAllFromCollectionGroup(t,e,n,s){F()}Or(t,e){return w.forEach(this.docs,(n=>e(n)))}newChangeBuffer(t){return new Gp(this)}getSize(t){return w.resolve(this.size)}}class Gp extends Mh{constructor(t){super(),this.cr=t}applyChanges(t){const e=[];
vendor: 4,094 bytes, line 17
17return this.changes.forEach(((n,s)=>{s.isValidDocument()?e.push(this.cr.addEntry(t,s)):this.cr.removeEntry(n)})),w.waitFor(e)}getFromCache(t,e){return this.cr.getEntry(t,e)}getAllFromCache(t,e){return this.cr.getEntries(t,e)}}class Kp{constructor(t){this.persistence=t,this.Nr=new se((e=>Ye(e)),zr),this.lastRemoteSnapshotVersion=U.min(),this.highestTargetId=0,this.Lr=0,this.Br=new Jo,this.targetCount=0,this.kr=nn.Bn()}forEachTarget(t,e){return this.Nr.forEach(((n,s)=>e(s))),w.resolve()}getLastRemoteSnapshotVersion(t){return w.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(t){return w.resolve(this.Lr)}allocateTargetId(t){return this.highestTargetId=this.kr.next(),w.resolve(this.highestTargetId)}setTargetsMetadata(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.Lr&&(this.Lr=e),w.resolve()}Kn(t){this.Nr.set(t.target,t);const e=t.targetId;e>this.highestTargetId&&(this.kr=new nn(e),this.highestTargetId=e),t.sequenceNumber>this.Lr&&(this.Lr=t.sequenceNumber)}addTargetData(t,e){return this.Kn(e),this.targetCount+=1,w.resolve()}updateTargetData(t,e){return this.Kn(e),w.resolve()}removeTargetData(t,e){return this.Nr.delete(e.target),this.Br.gr(e.targetId),this.targetCount-=1,w.resolve()}removeTargets(t,e,n){let s=0;const i=[];return this.Nr.forEach(((a,u)=>{u.sequenceNumber<=e&&n.get(u.targetId)===null&&(this.Nr.delete(a),i.push(this.removeMatchingKeysForTargetId(t,u.targetId)),s++)})),w.waitFor(i).next((()=>s))}getTargetCount(t){return w.resolve(this.targetCount)}getTargetData(t,e){const n=this.Nr.get(e)||null;return w.resolve(n)}addMatchingKeys(t,e,n){return this.Br.Rr(e,n),w.resolve()}removeMatchingKeys(t,e,n){this.Br.mr(e,n);const s=this.persistence.referenceDelegate,i=[];return s&&e.forEach((a=>{i.push(s.markPotentiallyOrphaned(t,a))})),w.waitFor(i)}removeMatchingKeysForTargetId(t,e){return this.Br.gr(e),w.resolve()}getMatchingKeysForTargetId(t,e){const n=this.Br.yr(e);return w.resolve(n)}containsKey(t,e){return w.resolve(this.Br.containsKey(e))}}class Yo{constructor(t,e){this.qr={},this.overlays={},this.Qr=new Ft(0),this.Kr=!1,this.Kr=!0,this.$r=new qp,this.referenceDelegate=t(this),this.Ur=new Kp(this),this.indexManager=new Cp,this.remoteDocumentCache=(function(s){return new zp(s)})((n=>this.referenceDelegate.Wr(n))),this.serializer=new bh(e),this.Gr=new Bp(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Kr=!1,Promise.resolve()}get started(){return this.Kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(t){return this.indexManager}getDocumentOverlayCache(t){let e=this.overlays[t.toKey()];return e||(e=new Up,this.overlays[t.toKey()]=e),e}getMutationQueue(t,e){let n=this.qr[t.toKey()];return n||(n=new jp(e,this.referenceDelegate),this.qr[t.toKey()]=n),n}getGlobalsCache(){return this.$r}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Gr}runTransaction(t,e,n){x("MemoryPersistence","Starting transaction:",t);const s=new $p(this.Qr.next());return this.referenceDelegate.zr(),n(s).next((i=>this.referenceDelegate.jr(s).next((()=>i)))).toPromise().then((i=>(s.raiseOnCommittedEvent(),i)))}Hr(t,e){return w.or(Object.values(this.qr).map((n=>()=>n.containsKey(t,e))))}}class $p extends Rl{constructor(t){super(),this.currentSequenceNumber=t}}class li{constructor(t){this.persistence=t,this.Jr=new Jo,this.Yr=null}static Zr(t){return new li(t)}get Xr(){if(this.Yr)return this.Yr;throw F()}addReference(t,e,n){return this.Jr.addReference(n,e),this.Xr.delete(n.toString()),w.resolve()}removeReference(t,e,n){return this.Jr.removeReference(n,e),this.Xr.add(n.toString()),w.resolve()}markPotentiallyOrphaned(t,e){return this.Xr.add(e.toString()),w.resolve()}removeTarget(t,e){this.Jr.gr(e.targetId).forEach((s=>this.Xr.add(s.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(t,e.targetId).next((s=>{s.forEach((i=>this.Xr.add(i.toString())))})).next((()=>n.removeTargetData(t,e)))}zr(){this.Yr=new Set}jr(t){const e=this.persistence.getRemoteDocumentCache().newChangeBuffer();
17return w.forEach(this.Xr,(n=>{const s=O.fromPath(n);return this.ei(t,s).next((i=>{i||e.removeEntry(s,U.min())}))})).next((()=>(this.Yr=null,e.apply(t))))}updateLimboDocument(t,e){return this.ei(t,e).next((n=>{n?this.Xr.delete(e.toString()):this.Xr.add(e.toString())}))}Wr(t){return 0}ei(t,e){return w.or([()=>w.resolve(this.Jr.containsKey(e)),()=>this.persistence.getTargetCache().containsKey(t,e),()=>this.persistence.Hr(t,e)])}}class Hs{constructor(t,e){this.persistence=t,this.ti=new se((n=>Nt(n.path)),((n,s)=>n.isEqual(s))),this.garbageCollector=kh(this,e)}static Zr(t,e){return new Hs(t,e)}zr(){}jr(t){return w.resolve()}forEachTarget(t,e){return this.persistence.getTargetCache().forEachTarget(t,e)}Yn(t){const e=this.er(t);return this.persistence.getTargetCache().getTargetCount(t).next((n=>e.next((s=>n+s))))}er(t){let e=0;return this.Zn(t,(n=>{e++})).next((()=>e))}Zn(t,e){return w.forEach(this.ti,((n,s)=>this.nr(t,n,s).next((i=>i?w.resolve():e(s)))))}removeTargets(t,e,n){return this.persistence.getTargetCache().removeTargets(t,e,n)}removeOrphanedDocuments(t,e){let n=0;const s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.Or(t,(a=>this.nr(t,a,e).next((u=>{u||(n++,i.removeEntry(a,U.min()))})))).next((()=>i.apply(t))).next((()=>n))}markPotentiallyOrphaned(t,e){return this.ti.set(e,t.currentSequenceNumber),w.resolve()}removeTarget(t,e){const n=e.withSequenceNumber(t.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(t,n)}addReference(t,e,n){return this.ti.set(n,t.currentSequenceNumber),w.resolve()}removeReference(t,e,n){return this.ti.set(n,t.currentSequenceNumber),w.resolve()}updateLimboDocument(t,e){return this.ti.set(e,t.currentSequenceNumber),w.resolve()}Wr(t){let e=t.key.toString().length;return t.isFoundDocument()&&(e+=xs(t.data.value)),e}nr(t,e,n){return w.or([()=>this.persistence.Hr(t,e),()=>this.persistence.getTargetCache().containsKey(t,e),()=>{const s=this.ti.get(e);return w.resolve(s!==void 0&&s>n)}])}getCacheSize(t){return this.persistence.getRemoteDocumentCache().getSize(t)}}class Qp{constructor(t){this.serializer=t}O(t,e,n,s){const i=new ei("createOrUpgrade",e);n<1&&s>=1&&((function(c){c.createObjectStore("owner")})(t),(function(c){c.createObjectStore("mutationQueues",{keyPath:"userId"}),c.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",$u,{unique:!0}),c.createObjectStore("documentMutations")})(t),Nc(t),(function(c){c.createObjectStore("remoteDocuments")})(t));let a=w.resolve();return n<3&&s>=3&&(n!==0&&((function(c){c.deleteObjectStore("targetDocuments"),c.deleteObjectStore("targets"),c.deleteObjectStore("targetGlobal")})(t),Nc(t)),a=a.next((()=>(function(c){const h=c.store("targetGlobal"),f={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:U.min().toTimestamp(),targetCount:0};return h.put("targetGlobalKey",f)})(i)))),n<4&&s>=4&&(n!==0&&(a=a.next((()=>(function(c,h){return h.store("mutations").U().next((f=>{c.deleteObjectStore("mutations"),c.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",$u,{unique:!0});const g=h.store("mutations"),_=f.map((R=>g.put(R)));return w.waitFor(_)}))})(t,i)))),a=a.next((()=>{(function(c){c.createObjectStore("clientMetadata",{keyPath:"clientId"})})(t)}))),n<5&&s>=5&&(a=a.next((()=>this.ni(i)))),n<6&&s>=6&&(a=a.next((()=>((function(c){c.createObjectStore("remoteDocumentGlobal")})(t),this.ri(i))))),n<7&&s>=7&&(a=a.next((()=>this.ii(i)))),n<8&&s>=8&&(a=a.next((()=>this.si(t,i)))),n<9&&s>=9&&(a=a.next((()=>{(function(c){c.objectStoreNames.contains("remoteDocumentChanges")&&c.deleteObjectStore("remoteDocumentChanges")})(t)}))),n<10&&s>=10&&(a=a.next((()=>this.oi(i)))),n<11&&s>=11&&(a=a.next((()=>{(function(c){c.createObjectStore("bundles",{keyPath:"bundleId"})})(t),(function(c){c.createObjectStore("namedQueries",{keyPath:"name"})})(t)}))),n<12&&s>=12&&(a=a.next((()=>{(function(c){const h=c.createObjectStore("documentOverlays",{keyPath:Cg});h.createIndex("collectionPathOverlayIndex",Dg,{unique:!1}),h.createIndex("collectionGroupOverlayIndex",xg,{unique:!1})})(t)}))),n<13&&s>=13&&(a=a.next((()=>(function(c){const h=c.createObjectStore("remoteDocumentsV14",{keyPath:Ig});h.createIndex("documentKeyIndex",Eg),h.createIndex("collectionGroupIndex",Tg)})(t))).next((()=>this._i(t,i))).next((()=>t.deleteObjectStore("remoteDocuments")))),n<14&&s>=14&&(a=a.next((()=>this.ai(t,i)))),n<15&&s>=15&&(a=a.next((()=>(function(c){c.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),c.createObjectStore("indexState",{keyPath:bg}).createIndex("sequenceNumberIndex",Pg,{unique:!1}),c.createObjectStore("indexEntries",{keyPath:Sg}).createIndex("documentKeyIndex",Vg,{unique:!1})})(t)))),n<16&&s>=16&&(a=a.next((()=>{e.objectStore("indexState").clear()}
17)).next((()=>{e.objectStore("indexEntries").clear()}))),n<17&&s>=17&&(a=a.next((()=>{(function(c){c.createObjectStore("globals",{keyPath:"name"})})(t)}))),a}ri(t){let e=0;return t.store("remoteDocuments").J(((n,s)=>{e+=Ws(s)})).next((()=>{const n={byteSize:e};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)}))}ni(t){const e=t.store("mutationQueues"),n=t.store("mutations");return e.U().next((s=>w.forEach(s,(i=>{const a=IDBKeyRange.bound([i.userId,-1],[i.userId,i.lastAcknowledgedBatchId]);return n.U("userMutationsIndex",a).next((u=>w.forEach(u,(c=>{L(c.userId===i.userId);const h=Ge(this.serializer,c);return Ch(t,i.userId,h).next((()=>{}))}))))}))))}ii(t){const e=t.store("targetDocuments"),n=t.store("remoteDocuments");return t.store("targetGlobal").get("targetGlobalKey").next((s=>{const i=[];return n.J(((a,u)=>{const c=new W(a),h=(function(g){return[0,Nt(g)]})(c);i.push(e.get(h).next((f=>f?w.resolve():(g=>e.put({targetId:0,path:Nt(g),sequenceNumber:s.highestListenSequenceNumber}))(c))))})).next((()=>w.waitFor(i)))}))}si(t,e){t.createObjectStore("collectionParents",{keyPath:Rg});const n=e.store("collectionParents"),s=new Ho,i=a=>{if(s.add(a)){const u=a.lastSegment(),c=a.popLast();return n.put({collectionId:u,parent:Nt(c)})}};return e.store("remoteDocuments").J({H:!0},((a,u)=>{const c=new W(a);return i(c.popLast())})).next((()=>e.store("documentMutations").J({H:!0},(([a,u,c],h)=>{const f=Kt(u);return i(f.popLast())}))))}oi(t){const e=t.store("targets");return e.J(((n,s)=>{const i=vr(s),a=Ph(this.serializer,i);return e.put(a)}))}_i(t,e){const n=e.store("remoteDocuments"),s=[];return n.J(((i,a)=>{const u=e.store("remoteDocumentsV14"),c=(function(g){return g.document?new O(W.fromString(g.document.name).popFirst(5)):g.noDocument?O.fromSegments(g.noDocument.path):g.unknownDocument?O.fromSegments(g.unknownDocument.path):F()})(a).path.toArray(),h={prefixPath:c.slice(0,c.length-2),collectionGroup:c[c.length-2],documentId:c[c.length-1],readTime:a.readTime||[0,0],unknownDocument:a.unknownDocument,noDocument:a.noDocument,document:a.document,hasCommittedMutations:!!a.hasCommittedMutations};s.push(u.put(h))})).next((()=>w.waitFor(s)))}ai(t,e){const n=e.store("mutations"),s=Oh(this.serializer),i=new Yo(li.Zr,this.serializer.ct);return n.U().next((a=>{const u=new Map;return a.forEach((c=>{var h;let f=(h=u.get(c.userId))!==null&&h!==void 0?h:G();Ge(this.serializer,c).keys().forEach((g=>f=f.add(g))),u.set(c.userId,f)})),w.forEach(u,((c,h)=>{const f=new Et(h),g=ui.lt(this.serializer,f),_=i.getIndexManager(f),R=ci.lt(f,this.serializer,_,i.referenceDelegate);return new Fh(s,R,g,_).recalculateAndSaveOverlaysForDocumentKeys(new co(e,Ft.oe),c).next()}))}))}}function Nc(r){r.createObjectStore("targetDocuments",{keyPath:wg}).createIndex("documentTargetsIndex",Ag,{unique:!0}),r.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",vg,{unique:!0}),r.createObjectStore("targetGlobal")}const Xi="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Xo{constructor(t,e,n,s,i,a,u,c,h,f,g=17){if(this.allowTabSynchronization=t,this.persistenceKey=e,this.clientId=n,this.ui=i,this.window=a,this.document=u,this.ci=h,this.li=f,this.hi=g,this.Qr=null,this.Kr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Pi=null,this.inForeground=!1,this.Ii=null,this.Ti=null,this.Ei=Number.NEGATIVE_INFINITY,this.di=_=>Promise.resolve(),!Xo.D())throw new D(P.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new Mp(this,s),this.Ai=e+"main",this.serializer=new bh(c),this.Ri=new Qt(this.Ai,this.hi,new Qp(this.serializer)),this.$r=new Ap,this.Ur=new xp(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Oh(this.serializer),this.Gr=new wp,this.window&&this.window.localStorage?this.Vi=this.window.localStorage:(this.Vi=null,f===!1&>("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.mi().then((()=>
17{if(!this.isPrimary&&!this.allowTabSynchronization)throw new D(P.FAILED_PRECONDITION,Xi);return this.fi(),this.gi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(t=>this.Ur.getHighestSequenceNumber(t)))})).then((t=>{this.Qr=new Ft(t,this.ci)})).then((()=>{this.Kr=!0})).catch((t=>(this.Ri&&this.Ri.close(),Promise.reject(t))))}yi(t){return this.di=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ri.L((async e=>{e.newVersion===null&&await t()}))}setNetworkEnabled(t){this.networkEnabled!==t&&(this.networkEnabled=t,this.ui.enqueueAndForget((async()=>{this.started&&await this.mi()})))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(t=>bs(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.wi(t).next((e=>{e||(this.isPrimary=!1,this.ui.enqueueRetryable((()=>this.di(!1))))}))})).next((()=>this.Si(t))).next((e=>this.isPrimary&&!e?this.bi(t).next((()=>!1)):!!e&&this.Di(t).next((()=>!0)))))).catch((t=>{if(Ce(t))return x("IndexedDbPersistence","Failed to extend owner lease: ",t),this.isPrimary;if(!this.allowTabSynchronization)throw t;return x("IndexedDbPersistence","Releasing owner lease after error during lease refresh",t),!1})).then((t=>{this.isPrimary!==t&&this.ui.enqueueRetryable((()=>this.di(t))),this.isPrimary=t}))}wi(t){return yr(t).get("owner").next((e=>w.resolve(this.vi(e))))}Ci(t){return bs(t).delete(this.clientId)}async Fi(){if(this.isPrimary&&!this.Mi(this.Ei,18e5)){this.Ei=Date.now();const t=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const n=yt(e,"clientMetadata");return n.U().next((s=>{const i=this.xi(s,18e5),a=s.filter((u=>i.indexOf(u)===-1));return w.forEach(a,(u=>n.delete(u.clientId))).next((()=>a))}))})).catch((()=>[]));if(this.Vi)for(const e of t)this.Vi.removeItem(this.Oi(e.clientId))}}pi(){this.Ti=this.ui.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.mi().then((()=>this.Fi())).then((()=>this.pi()))))}vi(t){return!!t&&t.ownerId===this.clientId}Si(t){return this.li?w.resolve(!0):yr(t).get("owner").next((e=>{if(e!==null&&this.Mi(e.leaseTimestampMs,5e3)&&!this.Ni(e.ownerId)){if(this.vi(e)&&this.networkEnabled)return!0;if(!this.vi(e)){if(!e.allowTabSynchronization)throw new D(P.FAILED_PRECONDITION,Xi);return!1}}return!(!this.networkEnabled||!this.inForeground)||bs(t).U().next((n=>this.xi(n,5e3).find((s=>{if(this.clientId!==s.clientId){const i=!this.networkEnabled&&s.networkEnabled,a=!this.inForeground&&s.inForeground,u=this.networkEnabled===s.networkEnabled;if(i||a&&u)return!0}return!1}))===void 0))})).next((e=>(this.isPrimary!==e&&x("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Kr=!1,this.Li(),this.Ti&&(this.Ti.cancel(),this.Ti=null),this.Bi(),this.ki(),await this.Ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(t=>{const e=new co(t,Ft.oe);return this.bi(e).next((()=>this.Ci(e)))})),this.Ri.close(),this.qi()}xi(t,e){return t.filter((n=>this.Mi(n.updateTimeMs,e)&&!this.Ni(n.clientId)))}Qi(){return this.runTransaction("getActiveClients","readonly",(t=>bs(t).U().next((e=>this.xi(e,18e5).map((n=>n.clientId))))))}get started(){return this.Kr}getGlobalsCache(){return this.$r}getMutationQueue(t,e){return ci.lt(t,this.serializer,e,this.referenceDelegate)}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(t){return new Dp(t,this.serializer.ct.databaseId)}getDocumentOverlayCache(t){return ui.lt(this.serializer,t)}getBundleCache(){return this.Gr}runTransaction(t,e,n){x("IndexedDbPersistence","Starting transaction:",t);const s=e==="readonly"?"readonly":"readwrite",i=(function(c){return c===17?Mg:c===16?kg:c===15?Oo:c===14?Dl:c===13?Cl:c===12?Ng:c===11?Vl:void F()})(this.hi);let a;return this.Ri.runTransaction(t,s,i,(u=>(a=new co(u,this.Qr?this.Qr.next():Ft.oe),e==="readwrite-primary"?this.wi(a).next((c=>!!c||this.Si(a))).next((c=>{if(!c)throw gt(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.ui.enqueueRetryable((()=>this.di(!1))),new D(P.FAILED_PRECONDITION,Al);return n(a)})).next((c=>this.Di(a).next((()=>c)))):this.Ki(a).next((()=>n(a)))))).then((u=>(a.raiseOnCommittedEvent(),u)))}Ki(t){return yr(t).get("owner").next((e=>{if(e!==null&&this.Mi(e.leaseTimestampMs,5e3)&&!this.Ni(e.ownerId)&&!this.vi(e)&&!(this.li||this.allowTabSynchronization&&e.allowTabSynchronization))throw new D(P.FAILED_PRECONDITION,Xi)}))}Di(t){const e={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return yr(t).put("owner",e)}static D(){return Qt.D()}bi(t){const e=yr(t);return e.get("owner").next((n=>this.vi(n)?(x("IndexedDbPersistence","Releasing primary lease."),e.delete("owner")):w.resolve()))}Mi(t,e){const n=Date.now();return!(t<n-e)&&(!(t>n)||(gt(`Detected an update time that is in the future: ${t} > ${n}`),!1))}fi(){this.document!==null&&typeof this.document.addEventListener=="function"&&(this.Ii=()=>{this.ui.enqueueAndForget((()=>(this.inForeground=this.document.visibilityState==="visible",this.mi())
17))},this.document.addEventListener("visibilitychange",this.Ii),this.inForeground=this.document.visibilityState==="visible")}Bi(){this.Ii&&(this.document.removeEventListener("visibilitychange",this.Ii),this.Ii=null)}gi(){var t;typeof((t=this.window)===null||t===void 0?void 0:t.addEventListener)=="function"&&(this.Pi=()=>{this.Li();const e=/(?:Version|Mobile)\/1[456]/;sl()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ui.enterRestrictedMode(!0),this.ui.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.Pi))}ki(){this.Pi&&(this.window.removeEventListener("pagehide",this.Pi),this.Pi=null)}Ni(t){var e;try{const n=((e=this.Vi)===null||e===void 0?void 0:e.getItem(this.Oi(t)))!==null;return x("IndexedDbPersistence",`Client '${t}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(n){return gt("IndexedDbPersistence","Failed to get zombied client id.",n),!1}}Li(){if(this.Vi)try{this.Vi.setItem(this.Oi(this.clientId),String(Date.now()))}catch(t){gt("Failed to set zombie client id.",t)}}qi(){if(this.Vi)try{this.Vi.removeItem(this.Oi(this.clientId))}catch{}}Oi(t){return`firestore_zombie_${this.persistenceKey}_${t}`}}function yr(r){return yt(r,"owner")}function bs(r){return yt(r,"clientMetadata")}function Zo(r,t){let e=r.projectId;return r.isDefaultDatabase||(e+="."+r.database),"firestore/"+t+"/"+e+"/"}class ta{constructor(t,e,n,s){this.targetId=t,this.fromCache=e,this.$i=n,this.Ui=s}static Wi(t,e){let n=G(),s=G();for(const i of e.docChanges)switch(i.type){case 0:n=n.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new ta(t,e.fromCache,n,s)}}class Wp{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(t){this._documentReadCount+=t}}class Lh{constructor(){this.Gi=!1,this.zi=!1,this.ji=100,this.Hi=(function(){return sl()?8:bl(Ls())>0?6:4})()}initialize(t,e){this.Ji=t,this.indexManager=e,this.Gi=!0}getDocumentsMatchingQuery(t,e,n,s){const i={result:null};return this.Yi(t,e).next((a=>{i.result=a})).next((()=>{if(!i.result)return this.Zi(t,e,s,n).next((a=>{i.result=a}))})).next((()=>{if(i.result)return;const a=new Wp;return this.Xi(t,e,a).next((u=>{if(i.result=u,this.zi)return this.es(t,e,a,u.size)}))})).next((()=>i.result))}es(t,e,n,s){return n.documentReadCount<this.ji?(_n()<=Y.DEBUG&&x("QueryEngine","SDK will not create cache indexes for query:",yn(e),"since it only creates cache indexes for collection contains","more than or equal to",this.ji,"documents"),w.resolve()):(_n()<=Y.DEBUG&&x("QueryEngine","Query:",yn(e),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.Hi*s?(_n()<=Y.DEBUG&&x("QueryEngine","The SDK decides to create cache indexes for query:",yn(e),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(t,kt(e))):w.resolve())}Yi(t,e){if(ic(e))return w.resolve(null);let n=kt(e);return this.indexManager.getIndexType(t,n).next((s=>s===0?null:(e.limit!==null&&s===1&&(e=Gs(e,null,"F"),n=kt(e)),this.indexManager.getDocumentsMatchingTarget(t,n).next((i=>{const a=G(...i);return this.Ji.getDocuments(t,a).next((u=>this.indexManager.getMinOffset(t,n).next((c=>{const h=this.ts(e,u);return this.ns(e,h,a,c.readTime)?this.Yi(t,Gs(e,null,"F")):this.rs(t,h,e,c)}))))})))))}Zi(t,e,n,s){return ic(e)||s.isEqual(U.min())?w.resolve(null):this.Ji.getDocuments(t,n).next((i=>{const a=this.ts(e,i);return this.ns(e,a,n,s)?w.resolve(null):(_n()<=Y.DEBUG&&x("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),yn(e)),this.rs(t,a,e,vl(s,-1)).next((u=>u)))}))}ts(t,e){let n=new et(Jl(t));return e.forEach(((s,i)=>{Kr(t,i)&&(n=n.add(i))})),n}ns(t,e,n,s){if(t.limit===null)return!1;if(n.size!==e.size)return!0;const i=t.limitType==="F"?e.last():e.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}Xi(t,e,n){return _n()<=Y.DEBUG&&x("QueryEngine","Using full collection scan to execute query:",yn(e)),this.Ji.getDocumentsMatchingQuery(t,e,jt.min(),n)}rs(t,e,n,s){return this.Ji.getDocumentsMatchingQuery(t,n,s).next((i=>(e.forEach((a=>{i=i.insert(a.key,a)})),i)))}}class Hp{constructor(t,e,n,s){this.persistence=t,this.ss=e,this.serializer
17=s,this.os=new st(z),this._s=new se((i=>Ye(i)),zr),this.us=new Map,this.cs=t.getRemoteDocumentCache(),this.Ur=t.getTargetCache(),this.Gr=t.getBundleCache(),this.ls(n)}ls(t){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(t),this.indexManager=this.persistence.getIndexManager(t),this.mutationQueue=this.persistence.getMutationQueue(t,this.indexManager),this.localDocuments=new Fh(this.cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.cs.setIndexManager(this.indexManager),this.ss.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(e=>t.collect(e,this.os)))}}function Bh(r,t,e,n){return new Hp(r,t,e,n)}async function Uh(r,t){const e=k(r);return await e.persistence.runTransaction("Handle user change","readonly",(n=>{let s;return e.mutationQueue.getAllMutationBatches(n).next((i=>(s=i,e.ls(t),e.mutationQueue.getAllMutationBatches(n)))).next((i=>{const a=[],u=[];let c=G();for(const h of s){a.push(h.batchId);for(const f of h.mutations)c=c.add(f.key)}for(const h of i){u.push(h.batchId);for(const f of h.mutations)c=c.add(f.key)}return e.localDocuments.getDocuments(n,c).next((h=>({hs:h,removedBatchIds:a,addedBatchIds:u})))}))}))}function Jp(r,t){const e=k(r);return e.persistence.runTransaction("Acknowledge batch","readwrite-primary",(n=>{const s=t.batch.keys(),i=e.cs.newChangeBuffer({trackRemovals:!0});return(function(u,c,h,f){const g=h.batch,_=g.keys();let R=w.resolve();return _.forEach((C=>{R=R.next((()=>f.getEntry(c,C))).next((N=>{const V=h.docVersions.get(C);L(V!==null),N.version.compareTo(V)<0&&(g.applyToRemoteDocument(N,h),N.isValidDocument()&&(N.setReadTime(h.commitVersion),f.addEntry(N)))}))})),R.next((()=>u.mutationQueue.removeMutationBatch(c,g)))})(e,n,t,i).next((()=>i.apply(n))).next((()=>e.mutationQueue.performConsistencyCheck(n))).next((()=>e.documentOverlayCache.removeOverlaysForBatchId(n,s,t.batch.batchId))).next((()=>e.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(n,(function(u){let c=G();for(let h=0;h<u.mutationResults.length;++h)u.mutationResults[h].transformResults.length>0&&(c=c.add(u.batch.mutations[h].key));return c})(t)))).next((()=>e.localDocuments.getDocuments(n,s)))}))}function qh(r){const t=k(r);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Ur.getLastRemoteSnapshotVersion(e)))}function Yp(r,t){const e=k(r),n=t.snapshotVersion;let s=e.os;return e.persistence.runTransaction("Apply remote event","readwrite-primary",(i=>{const a=e.cs.newChangeBuffer({trackRemovals:!0});s=e.os;const u=[];
17t.targetChanges.forEach(((f,g)=>{const _=s.get(g);if(!_)return;u.push(e.Ur.removeMatchingKeys(i,f.removedDocuments,g).next((()=>e.Ur.addMatchingKeys(i,f.addedDocuments,g))));let R=_.withSequenceNumber(i.currentSequenceNumber);t.targetMismatches.get(g)!==null?R=R.withResumeToken(dt.EMPTY_BYTE_STRING,U.min()).withLastLimboFreeSnapshotVersion(U.min()):f.resumeToken.approximateByteSize()>0&&(R=R.withResumeToken(f.resumeToken,n)),s=s.insert(g,R),(function(N,V,q){return N.resumeToken.approximateByteSize()===0||V.snapshotVersion.toMicroseconds()-N.snapshotVersion.toMicroseconds()>=3e8?!0:q.addedDocuments.size+q.modifiedDocuments.size+q.removedDocuments.size>0})(_,R,f)&&u.push(e.Ur.updateTargetData(i,R))}));let c=Bt(),h=G();if(t.documentUpdates.forEach((f=>{t.resolvedLimboDocuments.has(f)&&u.push(e.persistence.referenceDelegate.updateLimboDocument(i,f))})),u.push(jh(i,a,t.documentUpdates).next((f=>{c=f.Ps,h=f.Is}))),!n.isEqual(U.min())){const f=e.Ur.getLastRemoteSnapshotVersion(i).next((g=>e.Ur.setTargetsMetadata(i,i.currentSequenceNumber,n)));u.push(f)}return w.waitFor(u).next((()=>a.apply(i))).next((()=>e.localDocuments.getLocalViewOfDocuments(i,c,h))).next((()=>c))})).then((i=>(e.os=s,i)))}function jh(r,t,e){let n=G(),s=G();return e.forEach((i=>n=n.add(i))),t.getEntries(r,n).next((i=>{let a=Bt();return e.forEach(((u,c)=>{const h=i.get(u);c.isFoundDocument()!==h.isFoundDocument()&&(s=s.add(u)),c.isNoDocument()&&c.version.isEqual(U.min())?(t.removeEntry(u,c.readTime),a=a.insert(u,c)):!h.isValidDocument()||c.version.compareTo(h.version)>0||c.version.compareTo(h.version)===0&&h.hasPendingWrites?(t.addEntry(c),a=a.insert(u,c)):x("LocalStore","Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)})),{Ps:a,Is:s}}))}function Xp(r,t){const e=k(r);return e.persistence.runTransaction("Get next mutation batch","readonly",(n=>(t===void 0&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t))))}function Dn(r,t){const e=k(r);return e.persistence.runTransaction("Allocate target","readwrite",(n=>{let s;return e.Ur.getTargetData(n,t).next((i=>i?(s=i,w.resolve(s)):e.Ur.allocateTargetId(n).next((a=>(s=new Zt(t,a,"TargetPurposeListen",n.currentSequenceNumber),e.Ur.addTargetData(n,s).next((()=>s)))))))})).then((n=>{const s=e.os.get(n.targetId);return(s===null||n.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(e.os=e.os.insert(n.targetId,n),e._s.set(t,n.targetId)),n}))}async function xn(r,t,e){const n=k(r),s=n.os.get(t),i=e?"readwrite":"readwrite-primary";try{e||await n.persistence.runTransaction("Release target",i,(a=>n.persistence.referenceDelegate.removeTarget(a,s)))}catch(a){if(!Ce(a))throw a;x("LocalStore",`Failed to update sequence numbers for target ${t}: ${a}`)}n.os=n.os.remove(t),n._s.delete(s.target)}function Js(r,t,e){const n=k(r);let s=U.min(),i=G();return n.persistence.runTransaction("Execute query","readwrite",(a=>(function(c,h,f){const g=k(c),_=g._s.get(f);return _!==void 0?w.resolve(g.os.get(_)):g.Ur.getTargetData(h,f)})(n,a,kt(t)).next((u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,n.Ur.getMatchingKeysForTargetId(a,u.targetId).next((c=>{i=c}))})).next((()=>n.ss.getDocumentsMatchingQuery(a,t,e?s:U.min(),e?i:G()))).next((u=>(Kh(n,Hl(t),u),{documents:u,Ts:i})))))}function zh(r,t){const e=k(r),n=k(e.Ur),s=e.os.get(t);return s?Promise.resolve(s.target):e.persistence.runTransaction("Get target data","readonly",(i=>n.ot(i,t).next((a=>a?a.target:null))))}function Gh(r,t){const e=k(r),n=e.us.get(t)||U.min();return e.persistence.runTransaction("Get new document changes","readonly",(s=>e.cs.getAllFromCollectionGroup(s,t,vl(n,-1),Number.MAX_SAFE_INTEGER))).then((s=>(Kh(e,t,s),s)))}function Kh(r,t,e){let n=r.us.get(t)||U.min();e.forEach(((s,i)=>{i.readTime.compareTo(n)>0&&(n=i.readTime)})),r.us.set(t,n)}async function Zp(r,t,e,n){const s=k(r);let i=G(),a=Bt();for(const h of e){const f=t.Es(h.metadata.name);h.document&&(i=i.add(f));const g=t.ds(h);g.setReadTime(t.As(h.metadata.readTime)),a=a.insert(f,g)}const u=s.cs.newChangeBuffer({trackRemovals:!0}),c=await Dn(s,(function(f){return kt(Un(W.fromString(`__bundle__/docs/${f}`)))})(n));return s.persistence.runTransaction("Apply bundle documents","readwrite",(h=>jh(h,u,a).next((f=>(u.apply(h),f))).next((f=>s.Ur.removeMatchingKeysForTargetId(h,c.targetId).next((()=>s.Ur.addMatchingKeys(h,i,c.targetId))).next((()=>s.localDocuments.getLocalViewOfDocuments(h,f.Ps,f.Is))).next((()=>f.Ps))))))}async function t_(r,t,e=G()){const n=await Dn(r,kt(Qo(t.bundledQuery))),s=k(r);return s.persistence.runTransaction("Save named query","readwrite",(i=>{const a=pt(t.readTime);if(n.snapshotVersion.compareTo(a)>=0)return s.Gr.saveNamedQuery(i,t);const u=n.withResumeToken(dt.EMPTY_BYTE_STRING,a);return s.os=s.os.insert(u.targetId,u),s.Ur.updateTargetData(i,u).next((()=>s.Ur.removeMatchingKeysForTargetId(i,n.targetId))).next((()=>s.Ur.addMatchingKeys(i,e,n.targetId))).next((()=>s.Gr.saveNamedQuery(i,t)))}))}function kc(r,t){return`firestore_clients_${r}_${t}`}function Mc(r,t,e){let n=`firestore_mutations_${r}_${e}`;return t.isAuthenticated()&&(n+=`_${t.uid}`),n}function Zi(r,t){return`firestore_targets_${r}_${t}`}class Ys{constructor(t,e,n,s){this.user=t,this.batchId=e,this.state=n,this.error=s}static Rs(t,e,n){const s=JSON.parse(n);let i,a=typeof s=="object"&&["pending","acknowledged","rejected"].indexOf(s.state)!==-1&&(s.error===void 0||typeof s.error=="object");return a&&s.error&&(a=typeof s.error.message=="string"&&typeof s.error.code=="string",a&&(i=new D(s.error.code,s.error.message))),a?new Ys(t,e,s.state,i):(gt("SharedCl
17ientState",`Failed to parse mutation state for ID '${e}': ${n}`),null)}Vs(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class Sr{constructor(t,e,n){this.targetId=t,this.state=e,this.error=n}static Rs(t,e){const n=JSON.parse(e);let s,i=typeof n=="object"&&["not-current","current","rejected"].indexOf(n.state)!==-1&&(n.error===void 0||typeof n.error=="object");return i&&n.error&&(i=typeof n.error.message=="string"&&typeof n.error.code=="string",i&&(s=new D(n.error.code,n.error.message))),i?new Sr(t,n.state,s):(gt("SharedClientState",`Failed to parse target state for ID '${t}': ${e}`),null)}Vs(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class Xs{constructor(t,e){this.clientId=t,this.activeTargetIds=e}static Rs(t,e){const n=JSON.parse(e);let s=typeof n=="object"&&n.activeTargetIds instanceof Array,i=Bo();for(let a=0;s&&a<n.activeTargetIds.length;++a)s=Pl(n.activeTargetIds[a]),i=i.add(n.activeTargetIds[a]);return s?new Xs(t,i):(gt("SharedClientState",`Failed to parse client data for instance '${t}': ${e}`),null)}}class ea{constructor(t,e){this.clientId=t,this.onlineState=e}static Rs(t){const e=JSON.parse(t);return typeof e=="object"&&["Unknown","Online","Offline"].indexOf(e.onlineState)!==-1&&typeof e.clientId=="string"?new ea(e.clientId,e.onlineState):(gt("SharedClientState",`Failed to parse online state: ${t}`),null)}}class Ao{constructor(){this.activeTargetIds=Bo()}fs(t){this.activeTargetIds=this.activeTargetIds.add(t)}gs(t){this.activeTargetIds=this.activeTargetIds.delete(t)}Vs(){const t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)}}class to{constructor(t,e,n,s,i){this.window=t,this.ui=e,this.persistenceKey=n,this.ps=s,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ys=this.ws.bind(this),this.Ss=new st(z),this.started=!1,this.bs=[];const a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ds=kc(this.persistenceKey,this.ps),this.vs=(function(c){return`firestore_sequence_number_${c}`})(this.persistenceKey),this.Ss=this.Ss.insert(this.ps,new Ao),this.Cs=new RegExp(`^firestore_clients_${a}_([^_]*)$`),this.Fs=new RegExp(`^firestore_mutations_${a}_(\\d+)(?:_(.*))?$`),this.Ms=new RegExp(`^firestore_targets_${a}_(\\d+)$`),this.xs=(function(c){return`firestore_online_state_${c}`})(this.persistenceKey),this.Os=(function(c){return`firestore_bundle_loaded_v2_${c}`})(this.persistenceKey),this.window.addEventListener("storage",this.ys)}static D(t){return!(!t||!t.localStorage)}async start(){const t=await this.syncEngine.Qi();for(const n of t){if(n===this.ps)continue;const s=this.getItem(kc(this.persistenceKey,n));if(s){const i=Xs.Rs(n,s);i&&(this.Ss=this.Ss.insert(i.clientId,i))}}this.Ns();const e=this.storage.getItem(this.xs);if(e){const n=this.Ls(e);n&&this.Bs(n)}for(const n of this.bs)this.ws(n);this.bs=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(t){this.setItem(this.vs,JSON.stringify(t))}getAllActiveQueryTargets(){return this.ks(this.Ss)}isActiveQueryTarget(t){let e=!1;return this.Ss.forEach(((n,s)=>{s.activeTargetIds.has(t)&&(e=!0)})),e}addPendingMutation(t){this.qs(t,"pending")}updateMutationState(t,e,n){this.qs(t,e,n),this.Qs(t)}addLocalQueryTarget(t,e=!0){let n="not-current";if(this.isActiveQueryTarget(t)){const s=this.storage.getItem(Zi(this.persistenceKey,t));if(s){const i=Sr.Rs(t,s);i&&(n=i.state)}}return e&&this.Ks.fs(t),this.Ns(),n}removeLocalQueryTarget(t){this.Ks.gs(t),this.Ns()}isLocalQueryTarget(t){return this.Ks.activeTargetIds.has(t)}clearQueryState(t){this.removeItem(Zi(this.persistenceKey,t))}updateQueryState(t,e,n){this.$s(t,e,n)}handleUserChange(t,e,n){e.forEach((s=>{this.Qs(s)})),this.currentUser=t,n.forEach((s=>{this.addPendingMutation(s)}))}setOnlineState(t){this.Us(t)}notifyBundleLoaded(t){this.Ws(t)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ys),this.removeItem(this.Ds),this.started=!1)}getItem(t){const e=this.storage.getItem(t);
17return x("SharedClientState","READ",t,e),e}setItem(t,e){x("SharedClientState","SET",t,e),this.storage.setItem(t,e)}removeItem(t){x("SharedClientState","REMOVE",t),this.storage.removeItem(t)}ws(t){const e=t;if(e.storageArea===this.storage){if(x("SharedClientState","EVENT",e.key,e.newValue),e.key===this.Ds)return void gt("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.ui.enqueueRetryable((async()=>{if(this.started){if(e.key!==null){if(this.Cs.test(e.key)){if(e.newValue==null){const n=this.Gs(e.key);return this.zs(n,null)}{const n=this.js(e.key,e.newValue);if(n)return this.zs(n.clientId,n)}}else if(this.Fs.test(e.key)){if(e.newValue!==null){const n=this.Hs(e.key,e.newValue);if(n)return this.Js(n)}}else if(this.Ms.test(e.key)){if(e.newValue!==null){const n=this.Ys(e.key,e.newValue);if(n)return this.Zs(n)}}else if(e.key===this.xs){if(e.newValue!==null){const n=this.Ls(e.newValue);if(n)return this.Bs(n)}}else if(e.key===this.vs){const n=(function(i){let a=Ft.oe;if(i!=null)try{const u=JSON.parse(i);L(typeof u=="number"),a=u}catch(u){gt("SharedClientState","Failed to read sequence number from WebStorage",u)}return a})(e.newValue);n!==Ft.oe&&this.sequenceNumberHandler(n)}else if(e.key===this.Os){const n=this.Xs(e.newValue);await Promise.all(n.map((s=>this.syncEngine.eo(s))))}}}else this.bs.push(e)}))}}get Ks(){return this.Ss.get(this.ps)}Ns(){this.setItem(this.Ds,this.Ks.Vs())}qs(t,e,n){const s=new Ys(this.currentUser,t,e,n),i=Mc(this.persistenceKey,this.currentUser,t);this.setItem(i,s.Vs())}Qs(t){const e=Mc(this.persistenceKey,this.currentUser,t);this.removeItem(e)}Us(t){const e={clientId:this.ps,onlineState:t};this.storage.setItem(this.xs,JSON.stringify(e))}$s(t,e,n){const s=Zi(this.persistenceKey,t),i=new Sr(t,e,n);this.setItem(s,i.Vs())}Ws(t){const e=JSON.stringify(Array.from(t));this.setItem(this.Os,e)}Gs(t){const e=this.Cs.exec(t);return e?e[1]:null}js(t,e){const n=this.Gs(t);return Xs.Rs(n,e)}Hs(t,e){const n=this.Fs.exec(t),s=Number(n[1]),i=n[2]!==void 0?n[2]:null;return Ys.Rs(new Et(i),s,e)}Ys(t,e){const n=this.Ms.exec(t),s=Number(n[1]);return Sr.Rs(s,e)}Ls(t){return ea.Rs(t)}Xs(t){return JSON.parse(t)}async Js(t){if(t.user.uid===this.currentUser.uid)return this.syncEngine.no(t.batchId,t.state,t.error);x("SharedClientState",`Ignoring mutation for non-active user ${t.user.uid}`)}Zs(t){return this.syncEngine.ro(t.targetId,t.state,t.error)}zs(t,e){const n=e?this.Ss.insert(t,e):this.Ss.remove(t),s=this.ks(this.Ss),i=this.ks(n),a=[],u=[];return i.forEach((c=>{s.has(c)||a.push(c)})),s.forEach((c=>{i.has(c)||u.push(c)})),this.syncEngine.io(a,u).then((()=>{this.Ss=n}))}Bs(t){this.Ss.get(t.clientId)&&this.onlineStateHandler(t.onlineState)}ks(t){let e=Bo();return t.forEach(((n,s)=>{e=e.unionWith(s.activeTargetIds)})),e}}class $h{constructor(){this.so=new Ao,this.oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(t){}updateMutationState(t,e,n){}addLocalQueryTarget(t,e=!0){return e&&this.so.fs(t),this.oo[t]||"not-current"}updateQueryState(t,e,n){this.oo[t]=e}removeLocalQueryTarget(t){this.so.gs(t)}isLocalQueryTarget(t){return this.so.activeTargetIds.has(t)}clearQueryState(t){delete this.oo[t]}getAllActiveQueryTargets(){return this.so.activeTargetIds}isActiveQueryTarget(t){return this.so.activeTargetIds.has(t)}start(){return this.so=new Ao,Promise.resolve()}handleUserChange(t,e,n){}setOnlineState(t){}shutdown(){}writeSequenceNumber(t){}notifyBundleLoaded(t){}}class e_{_o(t){}shutdown(){}}class Oc{constructor(){this.ao=()=>this.uo(),this.co=()=>this.lo(),this.ho=[],this.Po()}_o(t){this.ho.push(t)}shutdown(){window.removeEventListener("online",this.ao),window.removeEventListener("offline",this.co)}Po(){window.addEventListener("online",this.ao),window.addEventListener("offline",this.co)}uo(){x("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const t of this.ho)t(0)}lo(){x("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const t of this.ho)t(1)}static D(){return typeof window<"u"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}}let Ps=null;function eo(){return Ps===null?Ps=(function(){return 268435456+Math.round(2147483648*Math.random())})():Ps++,"0x"+Ps.toString(16)}const n_={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
17Query:"runAggregationQuery"};class r_{constructor(t){this.Io=t.Io,this.To=t.To}Eo(t){this.Ao=t}Ro(t){this.Vo=t}mo(t){this.fo=t}onMessage(t){this.po=t}close(){this.To()}send(t){this.Io(t)}yo(){this.Ao()}wo(){this.Vo()}So(t){this.fo(t)}bo(t){this.po(t)}}const Dt="WebChannelConnection";class s_ extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const n=e.ssl?"https":"http",s=encodeURIComponent(this.databaseId.projectId),i=encodeURIComponent(this.databaseId.database);this.Do=n+"://"+e.host,this.vo=`projects/${s}/databases/${i}`,this.Co=this.databaseId.database==="(default)"?`project_id=${s}`:`project_id=${s}&database_id=${i}`}get Fo(){return!1}Mo(e,n,s,i,a){const u=eo(),c=this.xo(e,n.toUriEncodedString());x("RestConnection",`Sending RPC '${e}' ${u}:`,c,s);const h={"google-cloud-resource-prefix":this.vo,"x-goog-request-params":this.Co};return this.Oo(h,i,a),this.No(e,c,h,s).then((f=>(x("RestConnection",`Received RPC '${e}' ${u}: `,f),f)),(f=>{throw qt("RestConnection",`RPC '${e}' ${u} failed with error: `,f,"url: ",c,"request:",s),f}))}Lo(e,n,s,i,a,u){return this.Mo(e,n,s,i,a)}Oo(e,n,s){e["X-Goog-Api-Client"]=(function(){return"gl-js/ fire/"+Bn})(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),n&&n.headers.forEach(((i,a)=>e[a]=i)),s&&s.headers.forEach(((i,a)=>e[a]=i))}xo(e,n){const s=n_[e];return`${this.Do}/v1/${n}:${s}`}terminate(){}}{constructor(t){super(t),this.forceLongPolling=t.forceLongPolling,this.autoDetectLongPolling=t.autoDetectLongPolling,this.useFetchStreams=t.useFetchStreams,this.longPollingOptions=t.longPollingOptions}No(t,e,n,s){const i=eo();return new Promise(((a,u)=>{const c=new fl;c.setWithCredentials(!0),c.listenOnce(ml.COMPLETE,(()=>{try{switch(c.getLastErrorCode()){case Vs.NO_ERROR:const f=c.getResponseJson();x(Dt,`XHR for RPC '${t}' ${i} received:`,JSON.stringify(f)),a(f);break;case Vs.TIMEOUT:x(Dt,`RPC '${t}' ${i} timed out`),u(new D(P.DEADLINE_EXCEEDED,"Request time out"));break;case Vs.HTTP_ERROR:const g=c.getStatus();if(x(Dt,`RPC '${t}' ${i} failed with status:`,g,"response text:",c.getResponseText()),g>0){let _=c.getResponseJson();Array.isArray(_)&&(_=_[0]);const R=_?.error;if(R&&R.status&&R.message){const C=(function(V){const q=V.toLowerCase().replace(/_/g,"-");return Object.values(P).indexOf(q)>=0?q:P.UNKNOWN})(R.status);u(new D(C,R.message))}else u(new D(P.UNKNOWN,"Server responded with status "+c.getStatus()))}else u(new D(P.UNAVAILABLE,"Connection failed."));break;default:F()}}finally{x(Dt,`RPC '${t}' ${i} completed.`)}}));const h=JSON.stringify(s);x(Dt,`RPC '${t}' ${i} sending request:`,s),c.send(e,"POST",h,n,15)}))}Bo(t,e,n){const s=eo(),i=[this.Do,"/","google.firestore.v1.Firestore","/",t,"/channel"],a=_l(),u=pl(),c={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},h=this.longPollingOptions.timeoutSeconds;h!==void 0&&(c.longPollingTimeout=Math.round(1e3*h)),this.useFetchStreams&&(c.useFetchStreams=!0),this.Oo(c.initMessageHeaders,e,n),c.encodeInitMessageHeaders=!0;const f=i.join("");x(Dt,`Creating RPC '${t}' stream ${s}: ${f}`,c);const g=a.createWebChannel(f,c);let _=!1,R=!1;const C=new r_({Io:V=>{R?x(Dt,`Not sending because RPC '${t}' stream ${s} is closed:`,V):(_||(x(Dt,`Opening RPC '${t}' stream ${s} transport.`),g.open(),_=!0),x(Dt,`RPC '${t}' stream ${s} sending:`,V),g.send(V))},To:()=>g.close()}),N=(V,q,j)=>{V.listen(q,(B=>{try{j(B)}catch($){setTimeout((()=>{throw $}),0)}}))};return N(g,Ir.EventType.OPEN,(()=>{R||(x(Dt,`RPC '${t}' stream ${s} transport opened.`),C.yo())})),N(g,Ir.EventType.CLOSE,(()=>{R||(R=!0,x(Dt,`RPC '${t}' stream ${s} transport closed`),C.So())})),N(g,Ir.EventType.ERROR,(V=>{R||(R=!0,qt(Dt,`RPC '${t}' stream ${s} transport errored:`,V),C.So(new D(P.UNAVAILABLE,"The operation could not be completed")))})),N(g,Ir.EventType.MESSAGE,(V=>
17{var q;if(!R){const j=V.data[0];L(!!j);const B=j,$=B.error||((q=B[0])===null||q===void 0?void 0:q.error);if($){x(Dt,`RPC '${t}' stream ${s} received error:`,$);const Z=$.status;let K=(function(I){const T=_t[I];if(T!==void 0)return lh(T)})(Z),E=$.message;K===void 0&&(K=P.INTERNAL,E="Unknown error status: "+Z+" with message "+$.message),R=!0,C.So(new D(K,E)),g.close()}else x(Dt,`RPC '${t}' stream ${s} received:`,j),C.bo(j)}})),N(u,gl.STAT_EVENT,(V=>{V.stat===ao.PROXY?x(Dt,`RPC '${t}' stream ${s} detected buffering proxy`):V.stat===ao.NOPROXY&&x(Dt,`RPC '${t}' stream ${s} detected no buffering proxy`)})),setTimeout((()=>{C.wo()}),0),C}}function Qh(){return typeof window<"u"?window:null}function Os(){return typeof document<"u"?document:null}function Hr(r){return new dp(r,!0)}class na{constructor(t,e,n=1e3,s=1.5,i=6e4){this.ui=t,this.timerId=e,this.ko=n,this.qo=s,this.Qo=i,this.Ko=0,this.$o=null,this.Uo=Date.now(),this.reset()}reset(){this.Ko=0}Wo(){this.Ko=this.Qo}Go(t){this.cancel();const e=Math.floor(this.Ko+this.zo()),n=Math.max(0,Date.now()-this.Uo),s=Math.max(0,e-n);s>0&&x("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Ko} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),this.$o=this.ui.enqueueAfterDelay(this.timerId,s,(()=>(this.Uo=Date.now(),t()))),this.Ko*=this.qo,this.Ko<this.ko&&(this.Ko=this.ko),this.Ko>this.Qo&&(this.Ko=this.Qo)}jo(){this.$o!==null&&(this.$o.skipDelay(),this.$o=null)}cancel(){this.$o!==null&&(this.$o.cancel(),this.$o=null)}zo(){return(Math.random()-.5)*this.Ko}}class Wh{constructor(t,e,n,s,i,a,u,c){this.ui=t,this.Ho=n,this.Jo=s,this.connection=i,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=u,this.listener=c,this.state=0,this.Yo=0,this.Zo=null,this.Xo=null,this.stream=null,this.e_=0,this.t_=new na(t,e)}n_(){return this.state===1||this.state===5||this.r_()}r_(){return this.state===2||this.state===3}start(){this.e_=0,this.state!==4?this.auth():this.i_()}async stop(){this.n_()&&await this.close(0)}s_(){this.state=0,this.t_.reset()}o_(){this.r_()&&this.Zo===null&&(this.Zo=this.ui.enqueueAfterDelay(this.Ho,6e4,(()=>this.__())))}a_(t){this.u_(),this.stream.send(t)}async __(){if(this.r_())return this.close(0)}u_(){this.Zo&&(this.Zo.cancel(),this.Zo=null)}c_(){this.Xo&&(this.Xo.cancel(),this.Xo=null)}async close(t,e){this.u_(),this.c_(),this.t_.cancel(),this.Yo++,t!==4?this.t_.reset():e&&e.code===P.RESOURCE_EXHAUSTED?(gt(e.toString()),gt("Using maximum backoff delay to prevent overloading the backend."),this.t_.Wo()):e&&e.code===P.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.l_(),this.stream.close(),this.stream=null),this.state=t,await this.listener.mo(e)}l_(){}auth(){this.state=1;const t=this.h_(this.Yo),e=this.Yo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([n,s])=>{this.Yo===e&&this.P_(n,s)}),(n=>{t((()=>{const s=new D(P.UNKNOWN,"Fetching auth token failed: "+n.message);return this.I_(s)}))}))}P_(t,e){const n=this.h_(this.Yo);this.stream=this.T_(t,e),this.stream.Eo((()=>{n((()=>this.listener.Eo()))})),this.stream.Ro((()=>{n((()=>(this.state=2,this.Xo=this.ui.enqueueAfterDelay(this.Jo,1e4,(()=>(this.r_()&&(this.state=3),Promise.resolve()))),this.listener.Ro())))})),this.stream.mo((s=>{n((()=>this.I_(s)))})),this.stream.onMessage((s=>{n((()=>++this.e_==1?this.E_(s):this.onNext(s)))}))}i_(){this.state=5,this.t_.Go((async()=>{this.state=0,this.start()}))}I_(t){return x("PersistentStream",`close with error: ${t}`),this.stream=null,this.close(4,t)}h_(t){return e=>{this.ui.enqueueAndForget((()=>this.Yo===t?e():(x("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class i_ extends Wh{constructor(t,e,n,s,i,a){super(t,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",e,n,s,a),this.serializer=i}T_(t,e){return this.connection.Bo("Listen",t,e)}E_(t){return this.onNext(t)}onNext(t){this.t_.reset();const e=gp(this.serializer,t),n=(function(i){if(!("targetChange"in i))return U.min();const a=i.targetChange;return a.targetIds&&a.targetIds.length?U.min():a.readTime?pt(a.readTime):U.min()})(t);return this.listener.d_(e,n)}A_(t){const e={};e.database=Io(this.serializer),e.addTarget=(function(i,a){let u;const c=a.target;if(u=js(c)?{documents:Eh(i,c)}:{query:ai(i,c)._t},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=mh(i,a.resumeToken);const h=_o(i,a.expectedCount);h!==null&&(u.expectedCount=h)}else if(a.snapshotVersion.compareTo(U.min())>0){u.readTime=Cn(i,a.snapshotVersion.toTimestamp());const h=_o(i,a.expectedCount);h!==null&&(u.expectedCount=h)}return u})(this.serializer,t);const n=_p(this.serializer,t);n&&(e.labels=n),this.a_(e)}R_(t){const e={};e.database=Io(this.serializer),e.removeTarget=t,this.a_(e)}}class o_ extends Wh{constructor(t,e,n,s,i,a){super(t,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",e,n,s,a),this.serializer
17=i}get V_(){return this.e_>0}start(){this.lastStreamToken=void 0,super.start()}l_(){this.V_&&this.m_([])}T_(t,e){return this.connection.Bo("Write",t,e)}E_(t){return L(!!t.streamToken),this.lastStreamToken=t.streamToken,L(!t.writeResults||t.writeResults.length===0),this.listener.f_()}onNext(t){L(!!t.streamToken),this.lastStreamToken=t.streamToken,this.t_.reset();const e=pp(t.writeResults,t.commitTime),n=pt(t.commitTime);return this.listener.g_(n,e)}p_(){const t={};t.database=Io(this.serializer),this.a_(t)}m_(t){const e={streamToken:this.lastStreamToken,writes:t.map((n=>Br(this.serializer,n)))};this.a_(e)}}class a_ extends class{}{constructor(t,e,n,s){super(),this.authCredentials=t,this.appCheckCredentials=e,this.connection=n,this.serializer=s,this.y_=!1}w_(){if(this.y_)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.")}Mo(t,e,n,s){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,a])=>this.connection.Mo(t,yo(e,n),s,i,a))).catch((i=>{throw i.name==="FirebaseError"?(i.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new D(P.UNKNOWN,i.toString())}))}Lo(t,e,n,s,i){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([a,u])=>this.connection.Lo(t,yo(e,n),s,a,u,i))).catch((a=>{throw a.name==="FirebaseError"?(a.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new D(P.UNKNOWN,a.toString())}))}terminate(){this.y_=!0,this.connection.terminate()}}class u_{constructor(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state="Unknown",this.S_=0,this.b_=null,this.D_=!0}v_(){this.S_===0&&(this.C_("Unknown"),this.b_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.b_=null,this.F_("Backend didn't respond within 10 seconds."),this.C_("Offline"),Promise.resolve()))))}M_(t){this.state==="Online"?this.C_("Unknown"):(this.S_++,this.S_>=1&&(this.x_(),this.F_(`Connection failed 1 times. Most recent error: ${t.toString()}`),this.C_("Offline")))}set(t){this.x_(),this.S_=0,t==="Online"&&(this.D_=!1),this.C_(t)}C_(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))}F_(t){const e=`Could not reach Cloud Firestore backend. ${t} 18This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.D_?(gt(e),this.D_=!1):x("OnlineStateTracker",e)}x_(){this.b_!==null&&(this.b_.cancel(),this.b_=null)}}class c_{constructor(t,e,n,s,i){this.localStore=t,this.datastore=e,this.asyncQueue=n,this.remoteSyncer={},this.O_=[],this.N_=new Map,this.L_=new Set,this.B_=[],this.k_=i,this.k_._o((a=>{n.enqueueAndForget((async()=>{xe(this)&&(x("RemoteStore","Restarting streams for network reachability change."),await(async function(c){const h=k(c);h.L_.add(4),await zn(h),h.q_.set("Unknown"),h.L_.delete(4),await Jr(h)})(this))}))})),this.q_=new u_(n,s)}}async function Jr(r){if(xe(r))for(const t of r.B_)await t(!0)}async function zn(r){for(const t of r.B_)await t(!1)}function hi(r,t){const e=k(r);e.N_.has(t.targetId)||(e.N_.set(t.targetId,t),ia(e)?sa(e):Kn(e).r_()&&ra(e,t))}function Nn(r,t){const e=k(r),n=Kn(e);e.N_.delete(t),n.r_()&&Hh(e,t),e.N_.size===0&&(n.r_()?n.o_():xe(e)&&e.q_.set("Unknown"))}function ra(r,t){if(r.Q_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(U.min())>0){const e=r.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(e)}Kn(r).A_(t)}function Hh(r,t){r.Q_.xe(t),Kn(r).R_(t)}function sa(r){r.Q_=new up({getRemoteKeysForTarget:t=>r.remoteSyncer.getRemoteKeysForTarget(t),ot:t=>r.N_.get(t)||null,tt:()=>r.datastore.serializer.databaseId}),Kn(r).start(),r.q_.v_()}function ia(r){return xe(r)&&!Kn(r).n_()&&r.N_.size>0}function xe(r){return k(r).L_.size===0}function Jh(r){r.Q_=void 0}async function l_(r){r.q_.set("Online")}async function h_(r){r.N_.forEach(((t,e)=>{ra(r,t)}))}async function d_(r,t){Jh(r),ia(r)?(r.q_.M_(t),sa(r)):r.q_.set("Unknown")}async function f_(r,t,e){if(r.q_.set("Online"),t instanceof fh&&t.state===2&&t.cause)try{await(async function(s,i){const a=i.cause;for(const u of i.targetIds)s.N_.has(u)&&(await s.remoteSyncer.rejectListen(u,a),s.N_.delete(u),s.Q_.removeTarget(u))})(r,t)}catch(n){x("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Zs(r,n)}else if(t instanceof Ms?r.Q_.Ke(t):t instanceof dh?r.Q_.He(t):r.Q_.We(t),!e.isEqual(U.min()))try{const n=await qh(r.localStore);e.compareTo(n)>=0&&await(function(i,a){const u=i.Q_.rt(a);
18return u.targetChanges.forEach(((c,h)=>{if(c.resumeToken.approximateByteSize()>0){const f=i.N_.get(h);f&&i.N_.set(h,f.withResumeToken(c.resumeToken,a))}})),u.targetMismatches.forEach(((c,h)=>{const f=i.N_.get(c);if(!f)return;i.N_.set(c,f.withResumeToken(dt.EMPTY_BYTE_STRING,f.snapshotVersion)),Hh(i,c);const g=new Zt(f.target,c,h,f.sequenceNumber);ra(i,g)})),i.remoteSyncer.applyRemoteEvent(u)})(r,e)}catch(n){x("RemoteStore","Failed to raise snapshot:",n),await Zs(r,n)}}async function Zs(r,t,e){if(!Ce(t))throw t;r.L_.add(1),await zn(r),r.q_.set("Offline"),e||(e=()=>qh(r.localStore)),r.asyncQueue.enqueueRetryable((async()=>{x("RemoteStore","Retrying IndexedDB access"),await e(),r.L_.delete(1),await Jr(r)}))}function Yh(r,t){return t().catch((e=>Zs(r,e,t)))}async function Gn(r){const t=k(r),e=Re(t);let n=t.O_.length>0?t.O_[t.O_.length-1].batchId:-1;for(;m_(t);)try{const s=await Xp(t.localStore,n);if(s===null){t.O_.length===0&&e.o_();break}n=s.batchId,g_(t,s)}catch(s){await Zs(t,s)}Xh(t)&&Zh(t)}function m_(r){return xe(r)&&r.O_.length<10}function g_(r,t){r.O_.push(t);const e=Re(r);e.r_()&&e.V_&&e.m_(t.mutations)}function Xh(r){return xe(r)&&!Re(r).n_()&&r.O_.length>0}function Zh(r){Re(r).start()}async function p_(r){Re(r).p_()}async function __(r){const t=Re(r);for(const e of r.O_)t.m_(e.mutations)}async function y_(r,t,e){const n=r.O_.shift(),s=zo.from(n,t,e);await Yh(r,(()=>r.remoteSyncer.applySuccessfulWrite(s))),await Gn(r)}async function I_(r,t){t&&Re(r).V_&&await(async function(n,s){if((function(a){return ch(a)&&a!==P.ABORTED})(s.code)){const i=n.O_.shift();Re(n).s_(),await Yh(n,(()=>n.remoteSyncer.rejectFailedWrite(i.batchId,s))),await Gn(n)}})(r,t),Xh(r)&&Zh(r)}async function Fc(r,t){const e=k(r);e.asyncQueue.verifyOperationInProgress(),x("RemoteStore","RemoteStore received new credentials");const n=xe(e);e.L_.add(3),await zn(e),n&&e.q_.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.L_.delete(3),await Jr(e)}async function Ro(r,t){const e=k(r);t?(e.L_.delete(2),await Jr(e)):t||(e.L_.add(2),await zn(e),e.q_.set("Unknown"))}function Kn(r){return r.K_||(r.K_=(function(e,n,s){const i=k(e);return i.w_(),new i_(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(r.datastore,r.asyncQueue,{Eo:l_.bind(null,r),Ro:h_.bind(null,r),mo:d_.bind(null,r),d_:f_.bind(null,r)}),r.B_.push((async t=>{t?(r.K_.s_(),ia(r)?sa(r):r.q_.set("Unknown")):(await r.K_.stop(),Jh(r))}))),r.K_}function Re(r){return r.U_||(r.U_=(function(e,n,s){const i=k(e);return i.w_(),new o_(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(r.datastore,r.asyncQueue,{Eo:()=>Promise.resolve(),Ro:p_.bind(null,r),mo:I_.bind(null,r),f_:__.bind(null,r),g_:y_.bind(null,r)}),r.B_.push((async t=>{t?(r.U_.s_(),await Gn(r)):(await r.U_.stop(),r.O_.length>0&&(x("RemoteStore",`Stopping write stream with ${r.O_.length} pending writes`),r.O_=[]))}))),r.U_}class oa{constructor(t,e,n,s,i){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=s,this.removalCallback=i,this.deferred=new Tt,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((a=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(t,e,n,s,i){const a=Date.now()+n,u=new oa(t,e,a,s,i);return u.start(n),u}start(t){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),t)}skipDelay(){return this.handleDelayElapsed()}cancel(t){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new D(P.CANCELLED,"Operation cancelled"+(t?": "+t:"")))
18)}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then((t=>this.deferred.resolve(t)))):Promise.resolve()))}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function $n(r,t){if(gt("AsyncQueue",`${t}: ${r}`),Ce(r))return new D(P.UNAVAILABLE,`${t}: ${r}`);throw r}class vn{constructor(t){this.comparator=t?(e,n)=>t(e,n)||O.comparator(e.key,n.key):(e,n)=>O.comparator(e.key,n.key),this.keyedMap=Er(),this.sortedSet=new st(this.comparator)}static emptySet(t){return new vn(t.comparator)}has(t){return this.keyedMap.get(t)!=null}get(t){return this.keyedMap.get(t)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(t){const e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1}get size(){return this.sortedSet.size}forEach(t){this.sortedSet.inorderTraversal(((e,n)=>(t(e),!1)))}add(t){const e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))}delete(t){const e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this}isEqual(t){if(!(t instanceof vn)||this.size!==t.size)return!1;const e=this.sortedSet.getIterator(),n=t.sortedSet.getIterator();for(;e.hasNext();){const s=e.getNext().key,i=n.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){const t=[];return this.forEach((e=>{t.push(e.toString())})),t.length===0?"DocumentSet ()":`DocumentSet ( 19 `+t.join(` 20`)+` 21)`}copy(t,e){const n=new vn;return n.comparator=this.comparator,n.keyedMap=t,n.sortedSet=e,n}}class Lc{constructor(){this.W_=new st(O.comparator)}track(t){const e=t.doc.key,n=this.W_.get(e);n?t.type!==0&&n.type===3?this.W_=this.W_.insert(e,t):t.type===3&&n.type!==1?this.W_=this.W_.insert(e,{type:n.type,doc:t.doc}):t.type===2&&n.type===2?this.W_=this.W_.insert(e,{type:2,doc:t.doc}):t.type===2&&n.type===0?this.W_=this.W_.insert(e,{type:0,doc:t.doc}):t.type===1&&n.type===0?this.W_=this.W_.remove(e):t.type===1&&n.type===2?this.W_=this.W_.insert(e,{type:1,doc:n.doc}):t.type===0&&n.type===1?this.W_=this.W_.insert(e,{type:2,doc:t.doc}):F():this.W_=this.W_.insert(e,t)}
21G_(){const t=[];return this.W_.inorderTraversal(((e,n)=>{t.push(n)})),t}}class kn{constructor(t,e,n,s,i,a,u,c,h){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=u,this.excludesMetadataChanges=c,this.hasCachedResults=h}static fromInitialDocuments(t,e,n,s,i){const a=[];return e.forEach((u=>{a.push({type:0,doc:u})})),new kn(t,e,vn.emptySet(e),a,n,s,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.hasCachedResults===t.hasCachedResults&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&Gr(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;const e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(let s=0;s<e.length;s++)if(e[s].type!==n[s].type||!e[s].doc.isEqual(n[s].doc))return!1;return!0}}class E_{constructor(){this.z_=void 0,this.j_=[]}H_(){return this.j_.some((t=>t.J_()))}}class T_{constructor(){this.queries=Bc(),this.onlineState="Unknown",this.Y_=new Set}terminate(){(function(e,n){const s=k(e),i=s.queries;s.queries=Bc(),i.forEach(((a,u)=>{for(const c of u.j_)c.onError(n)}))})(this,new D(P.ABORTED,"Firestore shutting down"))}}function Bc(){return new se((r=>Wl(r)),Gr)}async function aa(r,t){const e=k(r);let n=3;const s=t.query;let i=e.queries.get(s);i?!i.H_()&&t.J_()&&(n=2):(i=new E_,n=t.J_()?0:1);try{switch(n){case 0:i.z_=await e.onListen(s,!0);break;case 1:i.z_=await e.onListen(s,!1);break;case 2:await e.onFirstRemoteStoreListen(s)}}catch(a){const u=$n(a,`Initialization of query '${yn(t.query)}' failed`);return void t.onError(u)}e.queries.set(s,i),i.j_.push(t),t.Z_(e.onlineState),i.z_&&t.X_(i.z_)&&ca(e)}async function ua(r,t){const e=k(r),n=t.query;let s=3;const i=e.queries.get(n);if(i){const a=i.j_.indexOf(t);a>=0&&(i.j_.splice(a,1),i.j_.length===0?s=t.J_()?0:1:!i.H_()&&t.J_()&&(s=2))}switch(s){case 0:return e.queries.delete(n),e.onUnlisten(n,!0);case 1:return e.queries.delete(n),e.onUnlisten(n,!1);case 2:return e.onLastRemoteStoreUnlisten(n);default:return}}function v_(r,t){const e=k(r);let n=!1;for(const s of t){const i=s.query,a=e.queries.get(i);if(a){for(const u of a.j_)u.X_(s)&&(n=!0);a.z_=s}}n&&ca(e)}function w_(r,t,e){const n=k(r),s=n.queries.get(t);if(s)for(const i of s.j_)i.onError(e);n.queries.delete(t)}function ca(r){r.Y_.forEach((t=>{t.next()}))}var bo,Uc;(Uc=bo||(bo={})).ea="default",Uc.Cache="cache";class la{constructor(t,e,n){this.query=t,this.ta=e,this.na=!1,this.ra=null,this.onlineState="Unknown",this.options=n||{}}X_(t){if(!this.options.includeMetadataChanges){const n=[];for(const s of t.docChanges)s.type!==3&&n.push(s);t=new kn(t.query,t.docs,t.oldDocs,n,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0,t.hasCachedResults)}let e=!1;return this.na?this.ia(t)&&(this.ta.next(t),e=!0):this.sa(t,this.onlineState)&&(this.oa(t),e=!0),this.ra=t,e}onError(t){this.ta.error(t)}Z_(t){this.onlineState=t;let e=!1;return this.ra&&!this.na&&this.sa(this.ra,t)&&(this.oa(this.ra),e=!0),e}sa(t,e){if(!t.fromCache||!this.J_())return!0;const n=e!=="Offline";return(!this.options._a||!n)&&(!t.docs.isEmpty()||t.hasCachedResults||e==="Offline")}ia(t){if(t.docChanges.length>0)return!0;const e=this.ra&&this.ra.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&this.options.includeMetadataChanges===!0}oa(t){t=kn.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache,t.hasCachedResults),this.na=!0,this.ta.next(t)}J_(){return this.options.source!==bo.Cache}}class A_{constructor(t,e){this.aa=t,this.byteLength=e}ua(){return"metadata"in this.aa}}class qc{constructor(t){this.serializer=t}Es(t){return Wt(this.serializer,t)}
21ds(t){return t.metadata.exists?Ih(this.serializer,t.document,!1):ot.newNoDocument(this.Es(t.metadata.name),this.As(t.metadata.readTime))}As(t){return pt(t)}}class R_{constructor(t,e,n){this.ca=t,this.localStore=e,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=td(t)}la(t){this.progress.bytesLoaded+=t.byteLength;let e=this.progress.documentsLoaded;if(t.aa.namedQuery)this.queries.push(t.aa.namedQuery);else if(t.aa.documentMetadata){this.documents.push({metadata:t.aa.documentMetadata}),t.aa.documentMetadata.exists||++e;const n=W.fromString(t.aa.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else t.aa.document&&(this.documents[this.documents.length-1].document=t.aa.document,++e);return e!==this.progress.documentsLoaded?(this.progress.documentsLoaded=e,Object.assign({},this.progress)):null}ha(t){const e=new Map,n=new qc(this.serializer);for(const s of t)if(s.metadata.queries){const i=n.Es(s.metadata.name);for(const a of s.metadata.queries){const u=(e.get(a)||G()).add(i);e.set(a,u)}}return e}async complete(){const t=await Zp(this.localStore,new qc(this.serializer),this.documents,this.ca.id),e=this.ha(this.documents);for(const n of this.queries)await t_(this.localStore,n,e.get(n.name));return this.progress.taskState="Success",{progress:this.progress,Pa:this.collectionGroups,Ia:t}}}function td(r){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:r.totalDocuments,totalBytes:r.totalBytes}}class ed{constructor(t){this.key=t}}class nd{constructor(t){this.key=t}}class rd{constructor(t,e){this.query=t,this.Ta=e,this.Ea=null,this.hasCachedResults=!1,this.current=!1,this.da=G(),this.mutatedKeys=G(),this.Aa=Jl(t),this.Ra=new vn(this.Aa)}get Va(){return this.Ta}ma(t,e){const n=e?e.fa:new Lc,s=e?e.Ra:this.Ra;let i=e?e.mutatedKeys:this.mutatedKeys,a=s,u=!1;const c=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,h=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(t.inorderTraversal(((f,g)=>{const _=s.get(f),R=Kr(this.query,g)?g:null,C=!!_&&this.mutatedKeys.has(_.key),N=!!R&&(R.hasLocalMutations||this.mutatedKeys.has(R.key)&&R.hasCommittedMutations);let V=!1;_&&R?_.data.isEqual(R.data)?C!==N&&(n.track({type:3,doc:R}),V=!0):this.ga(_,R)||(n.track({type:2,doc:R}),V=!0,(c&&this.Aa(R,c)>0||h&&this.Aa(R,h)<0)&&(u=!0)):!_&&R?(n.track({type:0,doc:R}),V=!0):_&&!R&&(n.track({type:1,doc:_}),V=!0,(c||h)&&(u=!0)),V&&(R?(a=a.add(R),i=N?i.add(f):i.delete(f)):(a=a.delete(f),i=i.delete(f)))})),this.query.limit!==null)for(;a.size>this.query.limit;){const f=this.query.limitType==="F"?a.last():a.first();a=a.delete(f.key),i=i.delete(f.key),n.track({type:1,doc:f})}return{Ra:a,fa:n,ns:u,mutatedKeys:i}}ga(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations}applyChanges(t,e,n,s){const i=this.Ra;this.Ra=t.Ra,this.mutatedKeys=t.mutatedKeys;const a=t.fa.G_();a.sort(((f,g)=>(function(R,C){const N=V=>{switch(V){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return F()}};return N(R)-N(C)})(f.type,g.type)||this.Aa(f.doc,g.doc))),this.pa(n),s=s!=null&&s;const u=e&&!s?this.ya():[],c=this.da.size===0&&this.current&&!s?1:0,h=c!==this.Ea;return this.Ea=c,a.length!==0||h?{snapshot:new kn(this.query,t.Ra,i,a,t.mutatedKeys,c===0,h,!1,!!n&&n.resumeToken.approximateByteSize()>0),wa:u}:{wa:u}}Z_(t){return this.current&&t==="Offline"?(this.current=!1,this.applyChanges({Ra:this.Ra,fa:new Lc,mutatedKeys:this.mutatedKeys,ns:!1},!1)):{wa:[]}}Sa(t){return!this.Ta.has(t)&&!!this.Ra.has(t)&&!this.Ra.get(t).hasLocalMutations}pa(t){t&&(t.addedDocuments.forEach((e=>this.Ta=this.Ta.add(e))),t.modifiedDocuments.forEach((e=>{})),t.removedDocuments.forEach((e=>this.Ta=this.Ta.delete(e))),this.current=t.current)}ya(){if(!this.current)return[];const t=this.da;this.da=G(),this.Ra.forEach((n=>{this.Sa(n.key)&&(this.da=this.da.add(n.key))}));const e=[];return t.forEach((n=>{this.da.has(n)||e.push(new nd(n))})),this.da.forEach((n=>{t.has(n)||e.push(new ed(n))})),e}ba(t){this.Ta=t.Ts,this.da=G();const e=this.ma(t.documents);return this.applyChanges(e,!0)}Da(){return kn.fromInitialDocuments(this.query,this.Ra,this.mutatedKeys,this.Ea===0,this.hasCachedResults)}}class b_{constructor(t,e,n){this.query=t,this.targetId=e,this.view=n}}class P_{constructor(t){this.key=t,this.va=!1}}class S_{constructor(t,e,n,s,i,a){this.localStore=t,this.remoteStore=e,this.eventManager=n,this.sharedCl
21ientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.Ca={},this.Fa=new se((u=>Wl(u)),Gr),this.Ma=new Map,this.xa=new Set,this.Oa=new st(O.comparator),this.Na=new Map,this.La=new Jo,this.Ba={},this.ka=new Map,this.qa=nn.kn(),this.onlineState="Unknown",this.Qa=void 0}get isPrimaryClient(){return this.Qa===!0}}async function V_(r,t,e=!0){const n=di(r);let s;const i=n.Fa.get(t);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Da()):s=await sd(n,t,e,!0),s}async function C_(r,t){const e=di(r);await sd(e,t,!0,!1)}async function sd(r,t,e,n){const s=await Dn(r.localStore,kt(t)),i=s.targetId,a=r.sharedClientState.addLocalQueryTarget(i,e);let u;return n&&(u=await ha(r,t,i,a==="current",s.resumeToken)),r.isPrimaryClient&&e&&hi(r.remoteStore,s),u}async function ha(r,t,e,n,s){r.Ka=(g,_,R)=>(async function(N,V,q,j){let B=V.view.ma(q);B.ns&&(B=await Js(N.localStore,V.query,!1).then((({documents:E})=>V.view.ma(E,B))));const $=j&&j.targetChanges.get(V.targetId),Z=j&&j.targetMismatches.get(V.targetId)!=null,K=V.view.applyChanges(B,N.isPrimaryClient,$,Z);return Po(N,V.targetId,K.wa),K.snapshot})(r,g,_,R);const i=await Js(r.localStore,t,!0),a=new rd(t,i.Ts),u=a.ma(i.documents),c=Wr.createSynthesizedTargetChangeForCurrentChange(e,n&&r.onlineState!=="Offline",s),h=a.applyChanges(u,r.isPrimaryClient,c);Po(r,e,h.wa);const f=new b_(t,e,a);return r.Fa.set(t,f),r.Ma.has(e)?r.Ma.get(e).push(t):r.Ma.set(e,[t]),h.snapshot}async function D_(r,t,e){const n=k(r),s=n.Fa.get(t),i=n.Ma.get(s.targetId);if(i.length>1)return n.Ma.set(s.targetId,i.filter((a=>!Gr(a,t)))),void n.Fa.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await xn(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),e&&Nn(n.remoteStore,s.targetId),Mn(n,s.targetId)})).catch(Ve)):(Mn(n,s.targetId),await xn(n.localStore,s.targetId,!0))}async function x_(r,t){const e=k(r),n=e.Fa.get(t),s=e.Ma.get(n.targetId);e.isPrimaryClient&&s.length===1&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),Nn(e.remoteStore,n.targetId))}async function N_(r,t,e){const n=ga(r);try{const s=await(function(a,u){const c=k(a),h=lt.now(),f=u.reduce(((R,C)=>R.add(C.key)),G());let g,_;return c.persistence.runTransaction("Locally write mutations","readwrite",(R=>{let C=Bt(),N=G();return c.cs.getEntries(R,f).next((V=>{C=V,C.forEach(((q,j)=>{j.isValidDocument()||(N=N.add(q))}))})).next((()=>c.localDocuments.getOverlayedDocuments(R,C))).next((V=>{g=V;const q=[];for(const j of u){const B=ip(j,g.get(j.key).overlayedDocument);B!=null&&q.push(new ie(j.key,B,Fl(B.value.mapValue),ct.exists(!0)))}return c.mutationQueue.addMutationBatch(R,h,q,u)})).next((V=>{_=V;const q=V.applyToLocalDocumentSet(g,N);return c.documentOverlayCache.saveOverlays(R,V.batchId,q)}))})).then((()=>({batchId:_.batchId,changes:Xl(g)})))})(n.localStore,t);n.sharedClientState.addPendingMutation(s.batchId),(function(a,u,c){let h=a.Ba[a.currentUser.toKey()];h||(h=new st(z)),h=h.insert(u,c),a.Ba[a.currentUser.toKey()]=h})(n,s.batchId,e),await oe(n,s.changes),await Gn(n.remoteStore)}catch(s){const i=$n(s,"Failed to persist write");e.reject(i)}}async function id(r,t){const e=k(r);try{const n=await Yp(e.localStore,t);
21t.targetChanges.forEach(((s,i)=>{const a=e.Na.get(i);a&&(L(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1),s.addedDocuments.size>0?a.va=!0:s.modifiedDocuments.size>0?L(a.va):s.removedDocuments.size>0&&(L(a.va),a.va=!1))})),await oe(e,n,t)}catch(n){await Ve(n)}}function jc(r,t,e){const n=k(r);if(n.isPrimaryClient&&e===0||!n.isPrimaryClient&&e===1){const s=[];n.Fa.forEach(((i,a)=>{const u=a.view.Z_(t);u.snapshot&&s.push(u.snapshot)})),(function(a,u){const c=k(a);c.onlineState=u;let h=!1;c.queries.forEach(((f,g)=>{for(const _ of g.j_)_.Z_(u)&&(h=!0)})),h&&ca(c)})(n.eventManager,t),s.length&&n.Ca.d_(s),n.onlineState=t,n.isPrimaryClient&&n.sharedClientState.setOnlineState(t)}}async function k_(r,t,e){const n=k(r);n.sharedClientState.updateQueryState(t,"rejected",e);const s=n.Na.get(t),i=s&&s.key;if(i){let a=new st(O.comparator);a=a.insert(i,ot.newNoDocument(i,U.min()));const u=G().add(i),c=new Qr(U.min(),new Map,new st(z),a,u);await id(n,c),n.Oa=n.Oa.remove(i),n.Na.delete(t),ma(n)}else await xn(n.localStore,t,!1).then((()=>Mn(n,t,e))).catch(Ve)}async function M_(r,t){const e=k(r),n=t.batch.batchId;try{const s=await Jp(e.localStore,t);fa(e,n,null),da(e,n),e.sharedClientState.updateMutationState(n,"acknowledged"),await oe(e,s)}catch(s){await Ve(s)}}async function O_(r,t,e){const n=k(r);try{const s=await(function(a,u){const c=k(a);return c.persistence.runTransaction("Reject batch","readwrite-primary",(h=>{let f;return c.mutationQueue.lookupMutationBatch(h,u).next((g=>
21(L(g!==null),f=g.keys(),c.mutationQueue.removeMutationBatch(h,g)))).next((()=>c.mutationQueue.performConsistencyCheck(h))).next((()=>c.documentOverlayCache.removeOverlaysForBatchId(h,f,u))).next((()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(h,f))).next((()=>c.localDocuments.getDocuments(h,f)))}))})(n.localStore,t);fa(n,t,e),da(n,t),n.sharedClientState.updateMutationState(t,"rejected",e),await oe(n,s)}catch(s){await Ve(s)}}async function F_(r,t){const e=k(r);xe(e.remoteStore)||x("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const n=await(function(a){const u=k(a);return u.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(c=>u.mutationQueue.getHighestUnacknowledgedBatchId(c)))})(e.localStore);if(n===-1)return void t.resolve();const s=e.ka.get(n)||[];s.push(t),e.ka.set(n,s)}catch(n){const s=$n(n,"Initialization of waitForPendingWrites() operation failed");t.reject(s)}}function da(r,t){(r.ka.get(t)||[]).forEach((e=>{e.resolve()})),r.ka.delete(t)}function fa(r,t,e){const n=k(r);let s=n.Ba[n.currentUser.toKey()];if(s){const i=s.get(t);i&&(e?i.reject(e):i.resolve(),s=s.remove(t)),n.Ba[n.currentUser.toKey()]=s}}function Mn(r,t,e=null){r.sharedClientState.removeLocalQueryTarget(t);for(const n of r.Ma.get(t))r.Fa.delete(n),e&&r.Ca.$a(n,e);r.Ma.delete(t),r.isPrimaryClient&&r.La.gr(t).forEach((n=>{r.La.containsKey(n)||od(r,n)}))}function od(r,t){r.xa.delete(t.path.canonicalString());const e=r.Oa.get(t);e!==null&&(Nn(r.remoteStore,e),r.Oa=r.Oa.remove(t),r.Na.delete(e),ma(r))}function Po(r,t,e){for(const n of e)n instanceof ed?(r.La.addReference(n.key,t),L_(r,n)):n instanceof nd?(x("SyncEngine","Document no longer in limbo: "+n.key),r.La.removeReference(n.key,t),r.La.containsKey(n.key)||od(r,n.key)):F()}function L_(r,t){const e=t.key,n=e.path.canonicalString();r.Oa.get(e)||r.xa.has(n)||(x("SyncEngine","New document in limbo: "+e),r.xa.add(n),ma(r))}function ma(r){for(;r.xa.size>0&&r.Oa.size<r.maxConcurrentLimboResolutions;){const t=r.xa.values().next().value;r.xa.delete(t);const e=new O(W.fromString(t)),n=r.qa.next();r.Na.set(n,new P_(e)),r.Oa=r.Oa.insert(e,n),hi(r.remoteStore,new Zt(kt(Un(e.path)),n,"TargetPurposeLimboResolution",Ft.oe))}}async function oe(r,t,e){const n=k(r),s=[],i=[],a=[];n.Fa.isEmpty()||(n.Fa.forEach(((u,c)=>{a.push(n.Ka(c,t,e).then((h=>{var f;if((h||e)&&n.isPrimaryClient){const g=h?!h.fromCache:(f=e?.targetChanges.get(c.targetId))===null||f===void 0?void 0:f.current;n.sharedClientState.updateQueryState(c.targetId,g?"current":"not-current")}if(h){s.push(h);const g=ta.Wi(c.targetId,h);i.push(g)}})))})),await Promise.all(a),n.Ca.d_(s),await(async function(c,h){const f=k(c);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",(g=>w.forEach(h,(_=>w.forEach(_.$i,(R=>f.persistence.referenceDelegate.addReference(g,_.targetId,R))).next((()=>w.forEach(_.Ui,(R=>f.persistence.referenceDelegate.removeReference(g,_.targetId,R)))))))))}catch(g){if(!Ce(g))throw g;x("LocalStore","Failed to update sequence numbers: "+g)}for(const g of h){const _=g.targetId;if(!g.fromCache){const R=f.os.get(_),C=R.snapshotVersion,N=R.withLastLimboFreeSnapshotVersion(C);f.os=f.os.insert(_,N)}}})(n.localStore,i))}async function B_(r,t){const e=k(r);if(!e.currentUser.isEqual(t)){x("SyncEngine","User change. New user:",t.toKey());const n=await Uh(e.localStore,t);e.currentUser=t,(function(i,a){i.ka.forEach((u=>{u.forEach((c=>{c.reject(new D(P.CANCELLED,a))}))})),i.ka.clear()})(e,"'waitForPendingWrites' promise is rejected due to a user change."),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await oe(e,n.hs)}}function U_(r,t){const e=k(r),n=e.Na.get(t);if(n&&n.va)return G().add(n.key);{let s=G();const i=e.Ma.get(t);if(!i)return s;for(const a of i){const u=e.Fa.get(a);s=s.unionWith(u.view.Va)}return s}}async function q_(r,t){const e=k(r),n=await Js(e.localStore,t.query,!0),s=t.view.ba(n);return e.isPrimaryClient&&Po(e,t.targetId,s.wa),s}async function j_(r,t){const e=k(r);return Gh(e.localStore,t).then((n=>oe(e,n)))}async function z_(r,t,e,n){const s=k(r),i=await(function(u,c){const h=k(u),f=k(h.mutation
21Queue);return h.persistence.runTransaction("Lookup mutation documents","readonly",(g=>f.Mn(g,c).next((_=>_?h.localDocuments.getDocuments(g,_):w.resolve(null)))))})(s.localStore,t);i!==null?(e==="pending"?await Gn(s.remoteStore):e==="acknowledged"||e==="rejected"?(fa(s,t,n||null),da(s,t),(function(u,c){k(k(u).mutationQueue).On(c)})(s.localStore,t)):F(),await oe(s,i)):x("SyncEngine","Cannot apply mutation batch with id: "+t)}async function G_(r,t){const e=k(r);if(di(e),ga(e),t===!0&&e.Qa!==!0){const n=e.sharedClientState.getAllActiveQueryTargets(),s=await zc(e,n.toArray());e.Qa=!0,await Ro(e.remoteStore,!0);for(const i of s)hi(e.remoteStore,i)}else if(t===!1&&e.Qa!==!1){const n=[];let s=Promise.resolve();e.Ma.forEach(((i,a)=>{e.sharedClientState.isLocalQueryTarget(a)?n.push(a):s=s.then((()=>(Mn(e,a),xn(e.localStore,a,!0)))),Nn(e.remoteStore,a)})),await s,await zc(e,n),(function(a){const u=k(a);u.Na.forEach(((c,h)=>{Nn(u.remoteStore,h)})),u.La.pr(),u.Na=new Map,u.Oa=new st(O.comparator)})(e),e.Qa=!1,await Ro(e.remoteStore,!1)}}async function zc(r,t,e){const n=k(r),s=[],i=[];for(const a of t){let u;const c=n.Ma.get(a);if(c&&c.length!==0){u=await Dn(n.localStore,kt(c[0]));for(const h of c){const f=n.Fa.get(h),g=await q_(n,f);g.snapshot&&i.push(g.snapshot)}}else{const h=await zh(n.localStore,a);u=await Dn(n.localStore,h),await ha(n,ad(h),a,!1,u.resumeToken)}s.push(u)}return n.Ca.d_(i),s}function ad(r){return Kl(r.path,r.collectionGroup,r.orderBy,r.filters,r.limit,"F",r.startAt,r.endAt)}function K_(r){return(function(e){return k(k(e).persistence).Qi()})(k(r).localStore)}async function $_(r,t,e,n){const s=k(r);if(s.Qa)return void x("SyncEngine","Ignoring unexpected query state notification.");const i=s.Ma.get(t);if(i&&i.length>0)switch(e){case"current":case"not-current":{const a=await Gh(s.localStore,Hl(i[0])),u=Qr.createSynthesizedRemoteEventForCurrentChange(t,e==="current",dt.EMPTY_BYTE_STRING);await oe(s,a,u);break}case"rejected":await xn(s.localStore,t,!0),Mn(s,t,n);break;default:F()}}async function Q_(r,t,e){const n=di(r);if(n.Qa){for(const s of t){if(n.Ma.has(s)&&n.sharedClientState.isActiveQueryTarget(s)){x("SyncEngine","Adding an already active target "+s);continue}const i=await zh(n.localStore,s),a=await Dn(n.localStore,i);await ha(n,ad(i),a.targetId,!1,a.resumeToken),hi(n.remoteStore,a)}for(const s of e)n.Ma.has(s)&&await xn(n.localStore,s,!1).then((()=>{Nn(n.remoteStore,s),Mn(n,s)})).catch(Ve)}}function di(r){const t=k(r);return t.remoteStore.remoteSyncer.applyRemoteEvent=id.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=U_.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=k_.bind(null,t),t.Ca.d_=v_.bind(null,t.eventManager),t.Ca.$a=w_.bind(null,t.eventManager),t}function ga(r){const t=k(r);return t.remoteStore.remoteSyncer.applySuccessfulWrite=M_.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=O_.bind(null,t),t}function W_(r,t,e){const n=k(r);(async function(i,a,u){try{const c=await a.getMetadata();if(await(function(R,C){const N=k(R),V=pt(C.createTime);return N.persistence.runTransaction("hasNewerBundle","readonly",(q=>N.Gr.getBundleMetadata(q,C.id))).then((q=>!!q&&q.createTime.compareTo(V)>=0))})(i.localStore,c))return await a.close(),u._completeWith((function(R){return{taskState:"Success",documentsLoaded:R.totalDocuments,bytesLoaded:R.totalBytes,totalDocuments:R.totalDocuments,totalBytes:R.totalBytes}})(c)),Promise.resolve(new Set);u._updateProgress(td(c));const h=new R_(c,i.localStore,a.serializer);let f=await a.Ua();for(;f;){const _=await h.la(f);_&&u._updateProgress(_),f=await a.Ua()}const g=await h.complete();return await oe(i,g.Ia,void 0),await(function(R,C){const N=k(R);return N.persistence.runTransaction("Save bundle","readwrite",(V=>N.Gr.saveBundleMetadata(V,C)))})(i.localStore,c),u._completeWith(g.progress),Promise.resolve(g.Pa)}catch(c){return qt("SyncEngine",`Loading bundle failed with ${c}`),u._failWith(c),Promise.resolve(new Set)}})(n,t,e).then((s=>{n.sharedClientState.notifyBundleLoaded(s)}))}class be{constructor(){this.kind="memory",this.synchronizeTabs=!1}
21async initialize(t){this.serializer=Hr(t.databaseInfo.databaseId),this.sharedClientState=this.Wa(t),this.persistence=this.Ga(t),await this.persistence.start(),this.localStore=this.za(t),this.gcScheduler=this.ja(t,this.localStore),this.indexBackfillerScheduler=this.Ha(t,this.localStore)}ja(t,e){return null}Ha(t,e){return null}za(t){return Bh(this.persistence,new Lh,t.initialUser,this.serializer)}Ga(t){return new Yo(li.Zr,this.serializer)}Wa(t){return new $h}async terminate(){var t,e;(t=this.gcScheduler)===null||t===void 0||t.stop(),(e=this.indexBackfillerScheduler)===null||e===void 0||e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}be.provider={build:()=>new be};class H_ extends be{constructor(t){super(),this.cacheSizeBytes=t}ja(t,e){L(this.persistence.referenceDelegate instanceof Hs);const n=this.persistence.referenceDelegate.garbageCollector;return new Nh(n,t.asyncQueue,e)}Ga(t){const e=this.cacheSizeBytes!==void 0?xt.withCacheSize(this.cacheSizeBytes):xt.DEFAULT;return new Yo((n=>Hs.Zr(n,e)),this.serializer)}}class pa extends be{constructor(t,e,n){super(),this.Ja=t,this.cacheSizeBytes=e,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(t){await super.initialize(t),await this.Ja.initialize(this,t),await ga(this.Ja.syncEngine),await Gn(this.Ja.remoteStore),await this.persistence.yi((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}za(t){return Bh(this.persistence,new Lh,t.initialUser,this.serializer)}ja(t,e){const n=this.persistence.referenceDelegate.garbageCollector;return new Nh(n,t.asyncQueue,e)}Ha(t,e){const n=new pg(e,this.persistence);return new gg(t.asyncQueue,n)}Ga(t){const e=Zo(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey),n=this.cacheSizeBytes!==void 0?xt.withCacheSize(this.cacheSizeBytes):xt.DEFAULT;return new Xo(this.synchronizeTabs,e,t.clientId,n,t.asyncQueue,Qh(),Os(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Wa(t){return new $h}}class ud extends pa{constructor(t,e){super(t,e,!1),this.Ja=t,this.cacheSizeBytes=e,this.synchronizeTabs=!0}async initialize(t){await super.initialize(t);const e=this.Ja.syncEngine;this.sharedClientState instanceof to&&(this.sharedClientState.syncEngine={no:z_.bind(null,e),ro:$_.bind(null,e),io:Q_.bind(null,e),Qi:K_.bind(null,e),eo:j_.bind(null,e)},await this.sharedClientState.start()),await this.persistence.yi((async n=>{await G_(this.Ja.syncEngine,n),this.gcScheduler&&(n&&!this.gcScheduler.started?this.gcScheduler.start():n||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(n&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():n||this.indexBackfillerScheduler.stop())}))}Wa(t){const e=Qh();if(!to.D(e))throw new D(P.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=Zo(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey);return new to(e,t.asyncQueue,n,t.clientId,t.initialUser)}}class Pe{async initialize(t,e){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=n=>jc(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=B_.bind(null,this.syncEngine),await Ro(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return(function(){return new T_})()}createDatastore(t){const e=Hr(t.databaseInfo.databaseId),n=(function(i){return new s_(i)})(t.databaseInfo);return(function(i,a,u,c){return new a_(i,a,u,c)})(t.authCredentials,t.appCheckCredentials,n,e)}createRemoteStore(t){return(function(n,s,i,a,u){return new c_(n,s,i,a,u)})(this.localStore,this.datastore,t.asyncQueue,(e=>jc(this.syncEngine,e,0)),(function(){return Oc.D()?new Oc:new e_})())}createSyncEngine(t,e){return(function(s,i,a,u,c,h,f){const g=new S_(s,i,a,u,c,h);return f&&(g.Qa=!0),g})(this.localStore,this.remoteStore,this.eventManager,this.sharedCl
21ientState,t.initialUser,t.maxConcurrentLimboResolutions,e)}async terminate(){var t,e;await(async function(s){const i=k(s);x("RemoteStore","RemoteStore shutting down."),i.L_.add(5),await zn(i),i.k_.shutdown(),i.q_.set("Unknown")})(this.remoteStore),(t=this.datastore)===null||t===void 0||t.terminate(),(e=this.eventManager)===null||e===void 0||e.terminate()}}Pe.provider={build:()=>new Pe};function Gc(r,t=10240){let e=0;return{async read(){if(e<r.byteLength){const n={value:r.slice(e,e+t),done:!1};return e+=t,n}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class fi{constructor(t){this.observer=t,this.muted=!1}next(t){this.muted||this.observer.next&&this.Ya(this.observer.next,t)}error(t){this.muted||(this.observer.error?this.Ya(this.observer.error,t):gt("Uncaught Error in snapshot listener:",t.toString()))}Za(){this.muted=!0}Ya(t,e){setTimeout((()=>{this.muted||t(e)}),0)}}class J_{constructor(t,e){this.Xa=t,this.serializer=e,this.metadata=new Tt,this.buffer=new Uint8Array,this.eu=(function(){return new TextDecoder("utf-8")})(),this.tu().then((n=>{n&&n.ua()?this.metadata.resolve(n.aa.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is 22 ${JSON.stringify(n?.aa)}`))}),(n=>this.metadata.reject(n)))}close(){return this.Xa.cancel()}async getMetadata(){return this.metadata.promise}async Ua(){return await this.getMetadata(),this.tu()}async tu(){const t=await this.nu();if(t===null)return null;const e=this.eu.decode(t),n=Number(e);isNaN(n)&&this.ru(`length string (${e}) is not valid number`);const s=await this.iu(n);return new A_(JSON.parse(s),t.length+n)}su(){return this.buffer.findIndex((t=>t===123))}async nu(){for(;this.su()<0&&!await this.ou(););if(this.buffer.length===0)return null;const t=this.su();t<0&&this.ru("Reached the end of bundle when a length string is expected.");const e=this.buffer.slice(0,t);return this.buffer=this.buffer.slice(t),e}async iu(t){for(;this.buffer.length<t;)await this.ou()&&this.ru("Reached the end of bundle when more is expected.");const e=this.eu.decode(this.buffer.slice(0,t));return this.buffer=this.buffer.slice(t),e}ru(t){throw this.Xa.cancel(),new Error(`Invalid bundle format: ${t}`)}async ou(){const t=await this.Xa.read();if(!t.done){const e=new Uint8Array(this.buffer.length+t.value.length);e.set(this.buffer),e.set(t.value,this.buffer.length),this.buffer=e}return t.done}}class Y_{constructor(t){this.datastore=t,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(t){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new D(P.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const e=await(async function(s,i){const a=k(s),u={documents:i.map((g=>Lr(a.serializer,g)))},c=await a.Lo("BatchGetDocuments",a.serializer.databaseId,W.emptyPath(),u,i.length),h=new Map;c.forEach((g=>{const _=mp(a.serializer,g);h.set(_.key.toString(),_)}));const f=[];return i.forEach((g=>{const _=h.get(g.toString());L(!!_),f.push(_)})),f})(this.datastore,t);return e.forEach((n=>this.recordVersion(n))),e}set(t,e){this.write(e.toMutation(t,this.precondition(t))),this.writtenDocs.add(t.toString())}update(t,e){try{this.write(e.toMutation(t,this.preconditionForUpdate(t)))}catch(n){this.lastTransactionError=n}this.writtenDocs.add(t.toString())}delete(t){this.write(new jn(t,this.precondition(t))),this.writtenDocs.add(t.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const t=this.readVersions;this.mutations.forEach((e=>{t.delete(e.key.toString())})),t.forEach(((e,n)=>{const s=O.fromPath(n);this.mutations.push(new qo(s,this.precondition(s)))})),await(async function(n,s){const i=k(n),a={writes:s.map((u=>Br(i.serializer,u)))};await i.Mo("Commit",i.serializer.databaseId,W.emptyPath(),a)})(this.datastore,this.mutations),this.committed=!0}recordVersion(t){let e;if(t.isFoundDocument())e=t.version;else{if(!t.isNoDocument())throw F();e=U.min()}const n=this.readVersions.get(t.key.toString());if(n){if(!e.isEqual(n))throw new D(P.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(t.key.toString(),e)}precondition(t){const e=this.readVersions.get(t.toString());return!this.writtenDocs.has(t.toString())&&e?e.isEqual(U.min())?ct.exists(!1):ct.updateTime(e):ct.none()}preconditionForUpdate(t){const e=this.readVersions.get(t.toString());if(!this.writtenDocs.has(t.toString())&&e){if(e.isEqual(U.min()))throw new D(P.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return ct.updateTime(e)}return ct.exists(!0)}write(t){this.ensureCommitNotCalled(),this.mutations.push(t)}ensureCommitNotCalled(){}}class X_{constructor(t,e,n,s,i){this.asyncQueue=t,this.datastore=e,this.options=n,this.updateFunction=s,this.deferred=i,this._u=n.maxAttempts,this.t_=new na(this.asyncQueue,"transaction_retry")}au(){this._u-=1,this.uu()}uu(){this.t_.Go((async()=>{const t=new Y_(this.datastore),e=this.cu(t);e&&e.then((n=>{this.asyncQueue.enqueueAndForget((()=>t.commit().then((()=>{this.deferred.resolve(n)})).catch((s=>{this.lu(s)}))))}
22)).catch((n=>{this.lu(n)}))}))}cu(t){try{const e=this.updateFunction(t);return!jr(e)&&e.catch&&e.then?e:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}lu(t){this._u>0&&this.hu(t)?(this._u-=1,this.asyncQueue.enqueueAndForget((()=>(this.uu(),Promise.resolve())))):this.deferred.reject(t)}hu(t){if(t.name==="FirebaseError"){const e=t.code;return e==="aborted"||e==="failed-precondition"||e==="already-exists"||!ch(e)}return!1}}class Z_{constructor(t,e,n,s,i){this.authCredentials=t,this.appCheckCredentials=e,this.asyncQueue=n,this.databaseInfo=s,this.user=Et.UNAUTHENTICATED,this.clientId=No.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async a=>{x("FirestoreClient","Received user=",a.uid),await this.authCredentialListener(a),this.user=a})),this.appCheckCredentials.start(n,(a=>(x("FirestoreClient","Received new app check token=",a),this.appCheckCredentialListener(a,this.user))))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(t){this.authCredentialListener=t}setAppCheckTokenChangeListener(t){this.appCheckCredentialListener=t}terminate(){this.asyncQueue.enterRestrictedMode();const t=new Tt;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),t.resolve()}catch(e){const n=$n(e,"Failed to shutdown persistence");t.reject(n)}})),t.promise}}async function no(r,t){r.asyncQueue.verifyOperationInProgress(),x("FirestoreClient","Initializing OfflineComponentProvider");const e=r.configuration;await t.initialize(e);let n=e.initialUser;r.setCredentialChangeListener((async s=>{n.isEqual(s)||(await Uh(t.localStore,s),n=s)})),t.persistence.setDatabaseDeletedListener((()=>r.terminate())),r._offlineComponents=t}async function Kc(r,t){r.asyncQueue.verifyOperationInProgress();const e=await _a(r);x("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(e,r.configuration),r.setCredentialChangeListener((n=>Fc(t.remoteStore,n))),r.setAppCheckTokenChangeListener(((n,s)=>Fc(t.remoteStore,s))),r._onlineComponents=t}async function _a(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){x("FirestoreClient","Using user provided OfflineComponentProvider");try{await no(r,r._uninitializedComponentsProvider._offline)}catch(t){const e=t;if(!(function(s){return s.name==="FirebaseError"?s.code===P.FAILED_PRECONDITION||s.code===P.UNIMPLEMENTED:!(typeof DOMException<"u"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11})(e))throw e;qt("Error using user provided cache. Falling back to memory cache: "+e),await no(r,new be)}}else x("FirestoreClient","Using default OfflineComponentProvider"),await no(r,new be);return r._offlineComponents}async function mi(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(x("FirestoreClient","Using user provided OnlineComponentProvider"),await Kc(r,r._uninitializedComponentsProvider._online)):(x("FirestoreClient","Using default OnlineComponentProvider"),await Kc(r,new Pe))),r._onlineComponents}function cd(r){return _a(r).then((t=>t.persistence))}function Qn(r){return _a(r).then((t=>t.localStore))}function ld(r){return mi(r).then((t=>t.remoteStore))}function ya(r){return mi(r).then((t=>t.syncEngine))}function hd(r){return mi(r).then((t=>t.datastore))}async function On(r){const t=await mi(r),e=t.eventManager;return e.onListen=V_.bind(null,t.syncEngine),e.onUnlisten=D_.bind(null,t.syncEngine),e.onFirstRemoteStoreListen=C_.bind(null,t.syncEngine),e.onLastRemoteStoreUnlisten=x_.bind(null,t.syncEngine),e}function ty(r){return r.asyncQueue.enqueue((async()=>{const t=await cd(r),e=await ld(r);return t.setNetworkEnabled(!0),(function(s){const i=k(s);return i.L_.delete(0),Jr(i)})(e)}))}function ey(r){return r.asyncQueue.enqueue((async()=>{const t=await cd(r),e=await ld(r);return t.setNetworkEnabled(!1),(async function(s){const i=k(s);i.L_.add(0),await zn(i),i.q_.set("Offline")})(e)}))}function ny(r,t){const e=new Tt;return r.asyncQueue.enqueueAndForget((async()=>(async function(s,i,a){try{const u=await(function(h,f){const g=k(h);return g.persistence.runTransaction("read document","readonly",(_=>g.localDocuments.getDocument(_,f)))})(s,i);u.isFoundDocument()?a.resolve(u):u.isNoDocument()?a.resolve(null):a.reject(new D(P.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(u){const c=$n(u,`Failed to get document '${i} from cache`);a.reject(c)}})(await Qn(r),t,e))),e.promise}function dd(r,t,e={}){const n=new Tt;return r.asyncQueue.enqueueAndForget((async()=>(function(i,a,u,c,h){const f=new fi({next:_=>{f.Za(),a.enqueueAndForget((()=>ua(i,g)));const R=_.docs.has(u);!R&&_.fromCache?h.reject(new D(P.UNAVAILABLE,"Failed to get document because the client is offline.")):R&&_.fromCache&&c&&c.source==="server"?h.reject(new D(P.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):h.resolve(_)},error:_=>h.reject(_)}),g=new la(Un(u.path),f,{includeMetadataChanges:!0,_a:!0});return aa(i,g)})(await On(r),r.asyncQueue,t,e,n))),n.promise}function ry(r,t){const e=new Tt;return r.asyncQueue.enqueueAndForget((async()=>(async function(s,i,a){try{const u=await Js(s,i,!0),c=new rd(i,u.Ts),h=c.ma(u.documents),f=c.applyChanges(h,!1);a.resolve(f.snapshot)}catch(u){const c=$n(u,`Failed to execute query '${i} against cache`);a.reject(c)}})(await Qn(r),t,e))),e.promise}function fd(r,t,e={}){const n=new Tt;return r.asyncQueue.enqueueAndForget((async()=>(function(i,a,u,c,h){const f=new fi({next:_=>{f.Za(),a.enqueueAndForget((()=>ua(i,g))),_.fromCache&&c.source==="server"?h.reject(new D(P.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):h.resolve(_)},error:_=>h.reject(_)}),g=new la(u,f,{includeMetadataChanges:!0,_a:!0});return aa(i,g)})(await On(r),r.asyncQueue,t,e,n))),n.promise}function sy(r,t,e){const n=new Tt;return r.asyncQueue.enqueueAndForget((async()=>{try{const s=await hd(r);n.resolve((async function(a,u,c){var h;const f=k(a),{request:g,ut:_,parent:R}=Th(f.serializer,$l(u),c);f.connection.Fo||delete g.parent;
22const C=(await f.Lo("RunAggregationQuery",f.serializer.databaseId,R,g,1)).filter((V=>!!V.result));L(C.length===1);const N=(h=C[0].result)===null||h===void 0?void 0:h.aggregateFields;return Object.keys(N).reduce(((V,q)=>(V[_[q]]=N[q],V)),{})})(s,t,e))}catch(s){n.reject(s)}})),n.promise}function iy(r,t){const e=new fi(t);return r.asyncQueue.enqueueAndForget((async()=>(function(s,i){k(s).Y_.add(i),i.next()})(await On(r),e))),()=>{e.Za(),r.asyncQueue.enqueueAndForget((async()=>(function(s,i){k(s).Y_.delete(i)})(await On(r),e)))}}function oy(r,t,e,n){const s=(function(a,u){let c;return c=typeof a=="string"?hh().encode(a):a,(function(f,g){return new J_(f,g)})((function(f,g){if(f instanceof Uint8Array)return Gc(f,g);if(f instanceof ArrayBuffer)return Gc(new Uint8Array(f),g);if(f instanceof ReadableStream)return f.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")})(c),u)})(e,Hr(t));r.asyncQueue.enqueueAndForget((async()=>{W_(await ya(r),s,n)}))}function ay(r,t){return r.asyncQueue.enqueue((async()=>(function(n,s){const i=k(n);return i.persistence.runTransaction("Get named query","readonly",(a=>i.Gr.getNamedQuery(a,s)))})(await Qn(r),t)))}function uy(r,t){return r.asyncQueue.enqueue((async()=>(async function(n,s){const i=k(n),a=i.indexManager,u=[];return i.persistence.runTransaction("Configure indexes","readwrite",(c=>a.getFieldIndexes(c).next((h=>(function(g,_,R,C,N){g=[...g],_=[..._],g.sort(R),_.sort(R);const V=g.length,q=_.length;let j=0,B=0;for(;j<q&&B<V;){const $=R(g[B],_[j]);$<0?N(g[B++]):$>0?C(_[j++]):(j++,B++)}for(;j<q;)C(_[j++]);for(;B<V;)N(g[B++])})(h,s,hg,(f=>{u.push(a.addFieldIndex(c,f))}),(f=>{u.push(a.deleteFieldIndex(c,f))})))).next((()=>w.waitFor(u)))))})(await Qn(r),t)))}function cy(r,t){return r.asyncQueue.enqueue((async()=>(function(n,s){k(n).ss.zi=s})(await Qn(r),t)))}function ly(r){return r.asyncQueue.enqueue((async()=>(function(e){const n=k(e),s=n.indexManager;return n.persistence.runTransaction("Delete All Indexes","readwrite",(i=>s.deleteAllFieldIndexes(i)))})(await Qn(r))))}function md(r){const t={};return r.timeoutSeconds!==void 0&&(t.timeoutSeconds=r.timeoutSeconds),t}const $c=new Map;function Ia(r,t,e){if(!e)throw new D(P.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${t}.`)}function gd(r,t,e,n){if(t===!0&&n===!0)throw new D(P.INVALID_ARGUMENT,`${r} and ${e} cannot be used together.`)}function Qc(r){if(!O.isDocumentKey(r))throw new D(P.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function Wc(r){if(O.isDocumentKey(r))throw new D(P.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${r} has ${r.length}.`)}function gi(r){if(r===void 0)return"undefined";if(r===null)return"null";if(typeof r=="string")return r.length>20&&(r=`${r.substring(0,20)}...`),JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean")return""+r;if(typeof r=="object"){if(r instanceof Array)return"an array";{const t=(function(n){return n.constructor?n.constructor.name:null})(r);return t?`a custom ${t} object`:"an object"}}return typeof r=="function"?"a function":F()}function Q(r,t){if("_delegate"in r&&(r=r._delegate),!(r instanceof t)){if(t.name===r.constructor.name)throw new D(P.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const e=gi(r);throw new D(P.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${e}`)}}return r}function pd(r,t){if(t<=0)throw new D(P.INVALID_ARGUMENT,`Function ${r}() requires a positive number, but it was: ${t}.`)}class Hc{constructor(t){var e,n;if(t.host===void 0){if(t.ssl!==void 0)throw new D(P.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=t.host,this.ssl=(e=t.ssl)===null||e===void 0||e;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,this.localCache=t.localCache,t.cacheSizeBytes===void 0)this.cacheSizeBytes=41943040;else{if(t.cacheSizeBytes!==-1&&t.cacheSizeBytes<1048576)throw new D(P.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}gd("experimentalForceLongPolling",t.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",t.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:t.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=md((n=t.experimentalLongPollingOptions)!==null&&n!==void 0?n:{}),(function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!t.useFetchStreams}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.experimentalForceLongPolling===t.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===t.experimentalAutoDetectLongPolling&&(function(n,s){return n.timeoutSeconds===s.timeoutSeconds})(this.experimentalLongPollingOptions,t.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===t.ignoreUndefinedProperties&&this.useFetchStreams===t.useFetchStreams}}class Yr{constructor(t,e,n,s){this._authCredentials=t,this._appCheckCredentials=e,this._databaseId=n,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Hc({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new D(P.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!=="notTerminated"}_setSettings(t){if(this._settingsFrozen)throw new D(P.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Hc(t),t.credentials!==void 0&&(this._authCredentials=(function(n){if(!n)return new Il;switch(n.type){case"firstParty":return new og(n.sessionIndex||"0",n.iamToken||null,n.authTokenFactory||null);case"provider":return n.client;default:throw new D(P.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
22d credential type")}})(t.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(e){const n=$c.get(e);n&&(x("ComponentProvider","Removing Datastore"),$c.delete(e),n.terminate())})(this),Promise.resolve()}}function _d(r,t,e,n={}){var s;const i=(r=Q(r,Yr))._getSettings(),a=`${t}:${e}`;if(i.host!=="firestore.googleapis.com"&&i.host!==a&&qt("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),r._setSettings(Object.assign(Object.assign({},i),{host:a,ssl:!1})),n.mockUserToken){let u,c;if(typeof n.mockUserToken=="string")u=n.mockUserToken,c=Et.MOCK_USER;else{u=kf(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);const h=n.mockUserToken.sub||n.mockUserToken.user_id;if(!h)throw new D(P.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");c=new Et(h)}r._authCredentials=new rg(new yl(u,c))}}class wt{constructor(t,e,n){this.converter=e,this._query=n,this.type="query",this.firestore=t}withConverter(t){return new wt(this.firestore,t,this._query)}}class mt{constructor(t,e,n){this.converter=e,this._key=n,this.type="document",this.firestore=t}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Gt(this.firestore,this.converter,this._key.path.popLast())}withConverter(t){return new mt(this.firestore,t,this._key)}}class Gt extends wt{constructor(t,e,n){super(t,e,Un(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const t=this._path.popLast();return t.isEmpty()?null:new mt(this.firestore,null,new O(t))}withConverter(t){return new Gt(this.firestore,t,this._path)}}function hy(r,t,...e){if(r=vt(r),Ia("collection","path",t),r instanceof Yr){const n=W.fromString(t,...e);return Wc(n),new Gt(r,null,n)}{if(!(r instanceof mt||r instanceof Gt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=r._path.child(W.fromString(t,...e));return Wc(n),new Gt(r.firestore,null,n)}}function dy(r,t){if(r=Q(r,Yr),Ia("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new D(P.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new wt(r,null,(function(n){return new re(W.emptyPath(),n)})(t))}function yd(r,t,...e){if(r=vt(r),arguments.length===1&&(t=No.newId()),Ia("doc","path",t),r instanceof Yr){const n=W.fromString(t,...e);return Qc(n),new mt(r,null,new O(n))}{if(!(r instanceof mt||r instanceof Gt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=r._path.child(W.fromString(t,...e));return Qc(n),new mt(r.firestore,r instanceof Gt?r.converter:null,new O(n))}}function fy(r,t){return r=vt(r),t=vt(t),(r instanceof mt||r instanceof Gt)&&(t instanceof mt||t instanceof Gt)&&r.firestore===t.firestore&&r.path===t.path&&r.converter===t.converter}function Ea(r,t){return r=vt(r),t=vt(t),r instanceof wt&&t instanceof wt&&r.firestore===t.firestore&&Gr(r._query,t._query)&&r.converter===t.converter}class Jc{constructor(t=Promise.resolve()){this.Pu=[],this.Iu=!1,this.Tu=[],this.Eu=null,this.du=!1,this.Au=!1,this.Ru=[],this.t_=new na(this,"async_queue_retry"),this.Vu=()=>{const n=Os();n&&x("AsyncQueue","Visibility state changed to "+n.visibilityState),this.t_.jo()},this.mu=t;const e=Os();e&&typeof e.addEventListener=="function"&&e.addEventListener("visibilitychange",this.Vu)}get isShuttingDown(){return this.Iu}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.fu(),this.gu(t)}enterRestrictedMode(t){if(!this.Iu){this.Iu=!0,this.Au=t||!1;const e=Os();e&&typeof e.removeEventListener=="function"&&e.removeEventListener("visibilitychange",this.Vu)}}enqueue(t){if(this.fu(),this.Iu)return new Promise((()=>{}));const e=new Tt;return this.gu((()=>this.Iu&&this.Au?Promise.resolve():(t().then(e.resolve,e.reject),e.promise))).then((()=>e.promise))}enqueueRetryable(t){this.enqueueAndForget((()=>(this.Pu.push(t),this.pu())))}async pu(){if(this.Pu.length!==0){try{await this.Pu[0](),this.Pu.shift(),this.t_.reset()}catch(t){if(!Ce(t))throw t;x("AsyncQueue","Operation failed with retryable error: "+t)}this.Pu.length>0&&this.t_.Go((()=>this.pu()))}}gu(t){const e=this.mu.then((()=>(this.du=!0,t().catch((n=>{this.Eu=n,this.du=!1;const s=(function(a){let u=a.message||"";return a.stack&&(u=a.stack.includes(a.message)?a.stack:a.message+` 23`+a.stack),u})(n);throw gt("INTERNAL UNHANDLED ERROR: ",s),n})).then((n=>(this.du=!1,n))))));return this.mu=e,e}
23enqueueAfterDelay(t,e,n){this.fu(),this.Ru.indexOf(t)>-1&&(e=0);const s=oa.createAndSchedule(this,t,e,n,(i=>this.yu(i)));return this.Tu.push(s),s}fu(){this.Eu&&F()}verifyOperationInProgress(){}async wu(){let t;do t=this.mu,await t;while(t!==this.mu)}Su(t){for(const e of this.Tu)if(e.timerId===t)return!0;return!1}bu(t){return this.wu().then((()=>{this.Tu.sort(((e,n)=>e.targetTimeMs-n.targetTimeMs));for(const e of this.Tu)if(e.skipDelay(),t!=="all"&&e.timerId===t)break;return this.wu()}))}Du(t){this.Ru.push(t)}yu(t){const e=this.Tu.indexOf(t);this.Tu.splice(e,1)}}function So(r){return(function(e,n){if(typeof e!="object"||e===null)return!1;const s=e;for(const i of n)if(i in s&&typeof s[i]=="function")return!0;return!1})(r,["next","error","complete"])}class Id{constructor(){this._progressObserver={},this._taskCompletionResolver=new Tt,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(t,e,n){this._progressObserver={next:t,error:e,complete:n}}catch(t){return this._taskCompletionResolver.promise.catch(t)}then(t,e){return this._taskCompletionResolver.promise.then(t,e)}_completeWith(t){this._updateProgress(t),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(t)}_failWith(t){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(t),this._taskCompletionResolver.reject(t)}_updateProgress(t){this._lastProgress=t,this._progressObserver.next&&this._progressObserver.next(t)}}const my=-1;class nt extends Yr{constructor(t,e,n,s){super(t,e,n,s),this.type="firestore",this._queue=new Jc,this._persistenceKey=s?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const t=this._firestoreClient.terminate();this._queue=new Jc(t),this._firestoreClient=void 0,await t}}}function gy(r,t,e){e||(e="(default)");const n=Do(r,"firestore");if(n.isInitialized(e)){const s=n.getImmediate({identifier:e}),i=n.getOptions(e);if(He(i,t))return s;throw new D(P.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(t.cacheSizeBytes!==void 0&&t.localCache!==void 0)throw new D(P.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(t.cacheSizeBytes!==void 0&&t.cacheSizeBytes!==-1&&t.cacheSizeBytes<1048576)throw new D(P.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return n.initialize({options:t,instanceIdentifier:e})}function py(r,t){const e=typeof r=="object"?r:Km(),n=typeof r=="string"?r:t||"(default)",s=Do(e,"firestore").getImmediate({identifier:n});if(!s._initialized){const i=xf("firestore");i&&_d(s,...i)}return s}function ht(r){if(r._terminated)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||Ed(r),r._firestoreClient}function Ed(r){var t,e,n;const s=r._freezeSettings(),i=(function(u,c,h,f){return new Lg(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,md(f.experimentalLongPollingOptions),f.useFetchStreams)})(r._databaseId,((t=r._app)===null||t===void 0?void 0:t.options.appId)||"",r._persistenceKey,s);r._componentsProvider||!((e=s.localCache)===null||e===void 0)&&e._offlineComponentProvider&&(!((n=s.localCache)===null||n===void 0)&&n._onlineComponentProvider)&&(r._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),r._firestoreClient=new Z_(r._authCredentials,r._appCheckCredentials,r._queue,i,r._componentsProvider&&(function(u){const c=u?._online.build();return{_offline:u?._offline.build(c),_online:c}})(r._componentsProvider))}function _y(r,t){qt("enableIndexedDbPersistence() will be deprecated
23in the future, you can use `FirestoreSettings.cache` instead.");const e=r._freezeSettings();return Td(r,Pe.provider,{build:n=>new pa(n,e.cacheSizeBytes,t?.forceOwnership)}),Promise.resolve()}async function yy(r){qt("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=r._freezeSettings();Td(r,Pe.provider,{build:e=>new ud(e,t.cacheSizeBytes)})}function Td(r,t,e){if((r=Q(r,nt))._firestoreClient||r._terminated)throw new D(P.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(r._componentsProvider||r._getSettings().localCache)throw new D(P.FAILED_PRECONDITION,"SDK cache is already specified.");r._componentsProvider={_online:t,_offline:e},Ed(r)}function Iy(r){if(r._initialized&&!r._terminated)throw new D(P.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Tt;return r._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await(async function(n){if(!Qt.D())return Promise.resolve();const s=n+"main";await Qt.delete(s)})(Zo(r._databaseId,r._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise}function Ey(r){return(function(e){const n=new Tt;return e.asyncQueue.enqueueAndForget((async()=>F_(await ya(e),n))),n.promise})(ht(r=Q(r,nt)))}function Ty(r){return ty(ht(r=Q(r,nt)))}function vy(r){return ey(ht(r=Q(r,nt)))}function wy(r){return Um(r.app,"firestore",r._databaseId.database),r._delete()}function Ay(r,t){const e=ht(r=Q(r,nt)),n=new Id;return oy(e,r._databaseId,t,n),n}function Ry(r,t){return ay(ht(r=Q(r,nt)),t).then((e=>e?new wt(r,null,e.query):null))}class Fn{constructor(t="count",e){this._internalFieldPath=e,this.type="AggregateField",this.aggregateType=t}}class vd{constructor(t,e,n){this._userDataWriter=e,this._data=n,this.type="AggregateQuerySnapshot",this.query=t}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Se{constructor(t){this._byteString=t}static fromBase64String(t){try{return new Se(dt.fromBase64String(t))}catch(e){throw new D(P.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(t){return new Se(dt.fromUint8Array(t))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(t){return this._byteString.isEqual(t._byteString)}}class Ne{constructor(...t){for(let e=0;e<t.length;++e)if(t[e].length===0)throw new D(P.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new at(t)}isEqual(t){return this._internalPath.isEqual(t._internalPath)}}function by(){return new Ne("__name__")}class ke{constructor(t){this._methodName=t}}class pi{constructor(t,e){if(!isFinite(t)||t<-90||t>90)throw new D(P.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new D(P.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(t){return z(this._lat,t._lat)||z(this._long,t._long)}}class Xr{constructor(t){this._values=(t||[]).map((e=>e))}toArray(){return this._values.map((t=>t))}isEqual(t){return(function(n,s){if(n.length!==s.length)return!1;for(let i=0;i<n.length;++i)if(n[i]!==s[i])return!1;return!0})(this._values,t._values)}}const Py=/^__.*__$/;class Sy{constructor(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}toMutation(t,e){return this.fieldMask!==null?new ie(t,this.data,this.fieldMask,e,this.fieldTransforms):new qn(t,this.data,e,this.fieldTransforms)}}class wd{constructor(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}toMutation(t,e){return new ie(t,this.data,this.fieldMask,e,this.fieldTransforms)}}function Ad(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw F()}}class _i{constructor(t,e,n,s,i,a){this.settings=t,this.databaseId=e,this.serializer
23=n,this.ignoreUndefinedProperties=s,i===void 0&&this.vu(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get Cu(){return this.settings.Cu}Fu(t){return new _i(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mu(t){var e;const n=(e=this.path)===null||e===void 0?void 0:e.child(t),s=this.Fu({path:n,xu:!1});return s.Ou(t),s}Nu(t){var e;const n=(e=this.path)===null||e===void 0?void 0:e.child(t),s=this.Fu({path:n,xu:!1});return s.vu(),s}Lu(t){return this.Fu({path:void 0,xu:!0})}Bu(t){return ti(t,this.settings.methodName,this.settings.ku||!1,this.path,this.settings.qu)}contains(t){return this.fieldMask.find((e=>t.isPrefixOf(e)))!==void 0||this.fieldTransforms.find((e=>t.isPrefixOf(e.field)))!==void 0}vu(){if(this.path)for(let t=0;t<this.path.length;t++)this.Ou(this.path.get(t))}Ou(t){if(t.length===0)throw this.Bu("Document fields must not be empty");if(Ad(this.Cu)&&Py.test(t))throw this.Bu('Document fields cannot begin and end with "__"')}}class Vy{constructor(t,e,n){this.databaseId=t,this.ignoreUndefinedProperties=e,this.serializer=n||Hr(t)}Qu(t,e,n,s=!1){return new _i({Cu:t,methodName:e,qu:n,path:at.emptyPath(),xu:!1,ku:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function on(r){const t=r._freezeSettings(),e=Hr(r._databaseId);return new Vy(r._databaseId,!!t.ignoreUndefinedProperties,e)}function yi(r,t,e,n,s,i={}){const a=r.Qu(i.merge||i.mergeFields?2:0,t,e,s);Pa("Data must be an object, but it was:",a,n);const u=Pd(n,a);let c,h;if(i.merge)c=new Lt(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){const f=[];for(const g of i.mergeFields){const _=Ur(t,g,e);if(!a.contains(_))throw new D(P.INVALID_ARGUMENT,`Field '${_}' is specified in your field mask but missing from your input data.`);Vd(f,_)||f.push(_)}c=new Lt(f),h=a.fieldTransforms.filter((g=>c.covers(g.field)))}else c=null,h=a.fieldTransforms;return new Sy(new bt(u),c,h)}class Zr extends ke{_toFieldTransform(t){if(t.Cu!==2)throw t.Cu===1?t.Bu(`${this._methodName}() can only appear at the top level of your update data`):t.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return t.fieldMask.push(t.path),null}isEqual(t){return t instanceof Zr}}function Rd(r,t,e){return new _i({Cu:3,qu:t.settings.qu,methodName:r._methodName,xu:e},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class Ta extends ke{_toFieldTransform(t){return new $r(t.path,new Sn)}isEqual(t){return t instanceof Ta}}class va extends ke{constructor(t,e){super(t),this.Ku=e}_toFieldTransform(t){const e=Rd(this,t,!0),n=this.Ku.map((i=>an(i,e))),s=new Xe(n);return new $r(t.path,s)}isEqual(t){return t instanceof va&&He(this.Ku,t.Ku)}}class wa extends ke{constructor(t,e){super(t),this.Ku=e}_toFieldTransform(t){const e=Rd(this,t,!0),n=this.Ku.map((i=>an(i,e))),s=new Ze(n);return new $r(t.path,s)}isEqual(t){return t instanceof wa&&He(this.Ku,t.Ku)}}class Aa extends ke{constructor(t,e){super(t),this.$u=e}_toFieldTransform(t){const e=new Vn(t.serializer,eh(t.serializer,this.$u));return new $r(t.path,e)}isEqual(t){return t instanceof Aa&&this.$u===t.$u}}function Ra(r,t,e,n){const s=r.Qu(1,t,e);Pa("Data must be an object, but it was:",s,n);const i=[],a=bt.empty();De(n,((c,h)=>{const f=Ii(t,c,e);h=vt(h);const g=s.Nu(f);if(h instanceof Zr)i.push(f);else{const _=an(h,g);_!=null&&(i.push(f),a.set(f,_))}}));const u=new Lt(i);return new wd(a,u,s.fieldTransforms)}function ba(r,t,e,n,s,i){const a=r.Qu(1,t,e),u=[Ur(t,n,e)],c=[s];if(i.length%2!=0)throw new D(P.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let _=0;_<i.length;_+=2)u.push(Ur(t,i[_])),c.push(i[_+1]);const h=[],f=bt.empty();for(let _=u.length-1;_>=0;--_)if(!Vd(h,u[_])){const R=u[_];let C=c[_];C=vt(C);const N=a.Nu(R);if(C instanceof Zr)h.push(R);else{const V=an(C,N);V!=null&&(h.push(R),f.set(R,V))}}const g=new Lt(h);return new wd(f,g,a.fieldTransforms)}function bd(r,t,e,n=!1){return an(e,r.Qu(n?4:3,t))}function an(r,t){if(Sd(r=vt(r)))return Pa("Unsupported field value:",t,r),Pd(r,t);if(r instanceof ke)return(function(n,s){if(!Ad(s.Cu))throw s.Bu(`${n._methodName}
23() can only be used with update() and set()`);if(!s.path)throw s.Bu(`${n._methodName}() is not currently supported inside arrays`);const i=n._toFieldTransform(s);i&&s.fieldTransforms.push(i)})(r,t),null;if(r===void 0&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),r instanceof Array){if(t.settings.xu&&t.Cu!==4)throw t.Bu("Nested arrays are not supported");return(function(n,s){const i=[];let a=0;for(const u of n){let c=an(u,s.Lu(a));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),a++}return{arrayValue:{values:i}}})(r,t)}return(function(n,s){if((n=vt(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return eh(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){const i=lt.fromDate(n);return{timestampValue:Cn(s.serializer,i)}}if(n instanceof lt){const i=new lt(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:Cn(s.serializer,i)}}if(n instanceof pi)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof Se)return{bytesValue:mh(s.serializer,n._byteString)};if(n instanceof mt){const i=s.databaseId,a=n.firestore._databaseId;if(!a.isEqual(i))throw s.Bu(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:$o(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof Xr)return(function(a,u){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:a.toArray().map((c=>{if(typeof c!="number")throw u.Bu("VectorValues must only contain numeric values.");return Uo(u.serializer,c)}))}}}}}})(n,s);throw s.Bu(`Unsupported field value: ${gi(n)}`)})(r,t)}function Pd(r,t){const e={};return Nl(r)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):De(r,((n,s)=>{const i=an(s,t.Mu(n));i!=null&&(e[n]=i)})),{mapValue:{fields:e}}}function Sd(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof lt||r instanceof pi||r instanceof Se||r instanceof mt||r instanceof ke||r instanceof Xr)}function Pa(r,t,e){if(!Sd(e)||!(function(s){return typeof s=="object"&&s!==null&&(Object.getPrototypeOf(s)===Object.prototype||Object.getPrototypeOf(s)===null)})(e)){const n=gi(e);throw n==="an object"?t.Bu(r+" a custom object"):t.Bu(r+" "+n)}}function Ur(r,t,e){if((t=vt(t))instanceof Ne)return t._internalPath;if(typeof t=="string")return Ii(r,t);throw ti("Field path arguments must be of type string or ",r,!1,void 0,e)}const Cy=new RegExp("[~\\*/\\[\\]]");function Ii(r,t,e){if(t.search(Cy)>=0)throw ti(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,e);try{return new Ne(...t.split("."))._internalPath}catch{throw ti(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,e)}}function ti(r,t,e,n,s){const i=n&&!n.isEmpty(),a=s!==void 0;let u=`Function ${t}() called with invalid data`;e&&(u+=" (via `toFirestore()`)"),u+=". ";let c="";return(i||a)&&(c+=" (found",i&&(c+=` in field ${n}`),a&&(c+=` in document ${s}`),c+=")"),new D(P.INVALID_ARGUMENT,u+r+c)}function Vd(r,t){return r.some((e=>e.isEqual(t)))}class qr{constructor(t,e,n,s,i){this._firestore=t,this._userDataWriter=e,this._key=n,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new mt(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){const t=new Dy(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}return this._userDataWriter.convertValue(this._document.data.value)}}get(t){if(this._document){const e=this._document.data.field(Ei("DocumentSnapshot.get",t));if(e!==null)return this._userDataWriter.convertValue(e)}}}class Dy extends qr{data(){return super.data()}}function Ei(r,t){return typeof t=="string"?Ii(r,t):t instanceof Ne?t._internalPath:t._delegate._internalPath}function Cd(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new D(P.UNIMPLEMENT
23ED,"limitToLast() queries require specifying at least one orderBy() clause")}class Sa{}class Wn extends Sa{}function xy(r,t,...e){let n=[];t instanceof Sa&&n.push(t),n=n.concat(e),(function(i){const a=i.filter((c=>c instanceof un)).length,u=i.filter((c=>c instanceof Hn)).length;if(a>1||a>0&&u>0)throw new D(P.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(n);for(const s of n)r=s._apply(r);return r}class Hn extends Wn{constructor(t,e,n){super(),this._field=t,this._op=e,this._value=n,this.type="where"}static _create(t,e,n){return new Hn(t,e,n)}_apply(t){const e=this._parse(t);return xd(t._query,e),new wt(t.firestore,t.converter,po(t._query,e))}_parse(t){const e=on(t.firestore);return(function(i,a,u,c,h,f,g){let _;if(h.isKeyField()){if(f==="array-contains"||f==="array-contains-any")throw new D(P.INVALID_ARGUMENT,`Invalid Query. You can't perform '${f}' queries on documentId().`);if(f==="in"||f==="not-in"){Xc(g,f);const R=[];for(const C of g)R.push(Yc(c,i,C));_={arrayValue:{values:R}}}else _=Yc(c,i,g)}else f!=="in"&&f!=="not-in"&&f!=="array-contains-any"||Xc(g,f),_=bd(u,a,g,f==="in"||f==="not-in");return H.create(h,f,_)})(t._query,"where",e,t.firestore._databaseId,this._field,this._op,this._value)}}function Ny(r,t,e){const n=t,s=Ei("where",r);return Hn._create(s,n,e)}class un extends Sa{constructor(t,e){super(),this.type=t,this._queryConstraints=e}static _create(t,e){return new un(t,e)}_parse(t){const e=this._queryConstraints.map((n=>n._parse(t))).filter((n=>n.getFilters().length>0));return e.length===1?e[0]:tt.create(e,this._getOperator())}_apply(t){const e=this._parse(t);return e.getFilters().length===0?t:((function(s,i){let a=s;const u=i.getFlattenedFilters();for(const c of u)xd(a,c),a=po(a,c)})(t._query,e),new wt(t.firestore,t.converter,po(t._query,e)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}}function ky(...r){return r.forEach((t=>Nd("or",t))),un._create("or",r)}function My(...r){return r.forEach((t=>Nd("and",t))),un._create("and",r)}class Ti extends Wn{constructor(t,e){super(),this._field=t,this._direction=e,this.type="orderBy"}static _create(t,e){return new Ti(t,e)}_apply(t){const e=(function(s,i,a){if(s.startAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(s.endAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Fr(i,a)})(t._query,this._field,this._direction);return new wt(t.firestore,t.converter,(function(s,i){const a=s.explicitOrderBy.concat([i]);return new re(s.path,s.collectionGroup,a,s.filters.slice(),s.limit,s.limitType,s.startAt,s.endAt)})(t._query,e))}}function Oy(r,t="asc"){const e=t,n=Ei("orderBy",r);return Ti._create(n,e)}class ts extends Wn{constructor(t,e,n){super(),this.type=t,this._limit=e,this._limitType=n}static _create(t,e,n){return new ts(t,e,n)}_apply(t){return new wt(t.firestore,t.converter,Gs(t._query,this._limit,this._limitType))}}function Fy(r){return pd("limit",r),ts._create("limit",r,"F")}function Ly(r){return pd("limitToLast",r),ts._create("limitToLast",r,"L")}class es extends Wn{constructor(t,e,n){super(),this.type=t,this._docOrFields=e,this._inclusive=n}static _create(t,e,n){return new es(t,e,n)}_apply(t){const e=Dd(t,this.type,this._docOrFields,this._inclusive);return new wt(t.firestore,t.converter,(function(s,i){return new re(s.path,s.collectionGroup,s.explicitOrderBy.slice(),s.filters.slice(),s.limit,s.limitType,i,s.endAt)})(t._query,e))}}function By(...r){return es._create("startAt",r,!0)}function Uy(...r){return es._create("startAfter",r,!1)}class ns extends Wn{constructor(t,e,n){super(),this.type=t,this._docOrFields=e,this._inclusive=n}static _create(t,e,n){return new ns(t,e,n)}_apply(t){const e=Dd(t,this.type,this._docOrFields,this._inclusive);return new wt(t.firestore,t.converter,(function(s,i){return new re(s.path,s.collectionGroup,s.explicitOrderBy.slice(),s.filters.slice(),s.limit,s.limitType,s.startAt,i)})(t._query,e))}}function qy(...r){return ns._create("endBefore",r,!1)}function jy(...r){return ns._create("endAt",r,!0)}function Dd(r,t,e,n){if(e[0]=vt(e[0]),e[0]instanceof qr)return(function(i,a,u,c,h){if(!c)throw new D(P.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${u}().`);const f=[];for(const g of Tn(i))if(g.field.isKeyField())f.push(Je(a,c.key));else{const _=c.data.field(g.field);if(ni(_))throw new D(P.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+g.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(_===null){const R=g.field.canonicalString();throw new D(P.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${R}' (used as the orderBy) does not exist.`)}f.push(_)}return new Ae(f,h)})(r._query,r.firestore._databaseId,t,e[0]._document,n);{const s=on(r.firestore);return(function(a,u,c,h,f,g){const _=a.explicitOrderBy;if(f.length>_.length)throw new D(P.INVALID_ARGUMENT,`Too many arguments provided to ${h}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const R=[];for(let C=0;C<f.length;C++){const N=f[C];
23if(_[C].field.isKeyField()){if(typeof N!="string")throw new D(P.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${h}(), but got a ${typeof N}`);if(!Lo(a)&&N.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${h}() must be a plain document ID, but '${N}' contains a slash.`);const V=a.path.child(W.fromString(N));if(!O.isDocumentKey(V))throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${h}() must result in a valid document path, but '${V}' is not because it contains an odd number of segments.`);const q=new O(V);R.push(Je(u,q))}else{const V=bd(c,h,N);R.push(V)}}return new Ae(R,g)})(r._query,r.firestore._databaseId,s,t,e,n)}}function Yc(r,t,e){if(typeof(e=vt(e))=="string"){if(e==="")throw new D(P.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Lo(t)&&e.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${e}' contains a '/' character.`);const n=t.path.child(W.fromString(e));if(!O.isDocumentKey(n))throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`);return Je(r,new O(n))}if(e instanceof mt)return Je(r,e._key);throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${gi(e)}.`)}function Xc(r,t){if(!Array.isArray(r)||r.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function xd(r,t){const e=(function(s,i){for(const a of s)for(const u of a.getFlattenedFilters())if(i.indexOf(u.op)>=0)return u.op;return null})(r.filters,(function(s){switch(s){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(t.op));if(e!==null)throw e===t.op?new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${e.toString()}' filters.`)}function Nd(r,t){if(!(t instanceof Hn||t instanceof un))throw new D(P.INVALID_ARGUMENT,`Function ${r}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Va{convertValue(t,e="none"){switch(ve(t)){case 0:return null;case 1:return t.booleanValue;case 2:return ut(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(ne(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 11:return this.convertObject(t.mapValue,e);case 10:return this.convertVectorValue(t.mapValue);default:throw F()}}convertObject(t,e){return this.convertObjectMap(t.fields,e)}convertObjectMap(t,e="none"){const n={};return De(t,((s,i)=>{n[s]=this.convertValue(i,e)})),n}convertVectorValue(t){var e,n,s;const i=(s=(n=(e=t.fields)===null||e===void 0?void 0:e.value.arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map((a=>ut(a.doubleValue)));return new Xr(i)}convertGeoPoint(t){return new pi(ut(t.latitude),ut(t.longitude))}convertArray(t,e){return(t.values||[]).map((n=>this.convertValue(n,e)))}convertServerTimestamp(t,e){switch(e){case"previous":const n=ri(t);return n==null?null:this.convertValue(n,e);case"estimate":return this.convertTimestamp(kr(t));default:return null}}convertTimestamp(t){const e=ee(t);return new lt(e.seconds,e.nanos)}convertDocumentKey(t,e){const n=W.fromString(t);L(Rh(n));const s=new Te(n.get(1),n.get(3)),i=new O(n.popFirst(5));return s.isEqual(e)||gt(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),i}}function vi(r,t,e){let n;return n=r?e&&(e.merge||e.mergeFields)?r.toFirestore(t,e):r.toFirestore(t):t,n}class zy extends Va{constructor(t){super(),this.firestore=t}convertBytes(t){return new Se(t)}convertReference(t){const e=this.convertDocumentKey(t,this.firestore._databaseId);
23return new mt(this.firestore,null,e)}}function Gy(r){return new Fn("sum",Ur("sum",r))}function Ky(r){return new Fn("avg",Ur("average",r))}function kd(){return new Fn("count")}function $y(r,t){var e,n;return r instanceof Fn&&t instanceof Fn&&r.aggregateType===t.aggregateType&&((e=r._internalFieldPath)===null||e===void 0?void 0:e.canonicalString())===((n=t._internalFieldPath)===null||n===void 0?void 0:n.canonicalString())}function Qy(r,t){return Ea(r.query,t.query)&&He(r.data(),t.data())}class _e{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class rn extends qr{constructor(t,e,n,s,i,a){super(t,e,n,s,a),this._firestore=t,this._firestoreImpl=t,this.metadata=i}exists(){return super.exists()}data(t={}){if(this._document){if(this._converter){const e=new Vr(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(e,t)}return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps)}}get(t,e={}){if(this._document){const n=this._document.data.field(Ei("DocumentSnapshot.get",t));if(n!==null)return this._userDataWriter.convertValue(n,e.serverTimestamps)}}}class Vr extends rn{data(t={}){return super.data(t)}}class sn{constructor(t,e,n,s){this._firestore=t,this._userDataWriter=e,this._snapshot=s,this.metadata=new _e(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){const t=[];return this.forEach((e=>t.push(e))),t}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(t,e){this._snapshot.docs.forEach((n=>{t.call(e,new Vr(this._firestore,this._userDataWriter,n.key,n,new _e(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(t={}){const e=!!t.includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new D(P.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=(function(s,i){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map((u=>{const c=new Vr(s._firestore,s._userDataWriter,u.doc.key,u.doc,new _e(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:c,oldIndex:-1,newIndex:a++}}))}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter((u=>i||u.type!==3)).map((u=>{const c=new Vr(s._firestore,s._userDataWriter,u.doc.key,u.doc,new _e(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);let h=-1,f=-1;return u.type!==0&&(h=a.indexOf(u.doc.key),a=a.delete(u.doc.key)),u.type!==1&&(a=a.add(u.doc),f=a.indexOf(u.doc.key)),{type:Wy(u.type),doc:c,oldIndex:h,newIndex:f}}))}})(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}function Wy(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return F()}}function Hy(r,t){return r instanceof rn&&t instanceof rn?r._firestore===t._firestore&&r._key.isEqual(t._key)&&(r._document===null?t._document===null:r._document.isEqual(t._document))&&r._converter===t._converter:r instanceof sn&&t instanceof sn&&r._firestore===t._firestore&&Ea(r.query,t.query)&&r.metadata.isEqual(t.metadata)&&r._snapshot.isEqual(t._snapshot)}function Jy(r){r=Q(r,mt);const t=Q(r.firestore,nt);return dd(ht(t),r._key).then((e=>Ca(t,r,e)))}class Me extends Va{constructor(t){super(),this.firestore=t}convertBytes(t){return new Se(t)}convertReference(t){const e=this.convertDocumentKey(t,this.firestore._databaseId);return new mt(this.firestore,null,e)}}function Yy(r){r=Q(r,mt);const t=Q(r.firestore,nt),e=ht(t),n=new Me(t);return ny(e,r._key).then((s=>new rn(t,n,r._key,s,new _e(s!==null&&s.hasLocalMutations,!0),r.converter)))}function Xy(r){r=Q(r,mt);const t=Q(r.firestore,nt);return dd(ht(t),r._key,{source:"server"}).then((e=>Ca(t,r,e)))}function Zy(r){r=Q(r,wt);const t=Q(r.firestore,nt),e=ht(t),n=new Me(t);return Cd(r._query),fd(e,r._query).then((s=>new sn(t,n,r,s)))}function tI(r){r=Q(r,wt);
23const t=Q(r.firestore,nt),e=ht(t),n=new Me(t);return ry(e,r._query).then((s=>new sn(t,n,r,s)))}function eI(r){r=Q(r,wt);const t=Q(r.firestore,nt),e=ht(t),n=new Me(t);return fd(e,r._query,{source:"server"}).then((s=>new sn(t,n,r,s)))}function nI(r,t,e){r=Q(r,mt);const n=Q(r.firestore,nt),s=vi(r.converter,t,e);return Jn(n,[yi(on(n),"setDoc",r._key,s,r.converter!==null,e).toMutation(r._key,ct.none())])}function rI(r,t,e,...n){r=Q(r,mt);const s=Q(r.firestore,nt),i=on(s);let a;return a=typeof(t=vt(t))=="string"||t instanceof Ne?ba(i,"updateDoc",r._key,t,e,n):Ra(i,"updateDoc",r._key,t),Jn(s,[a.toMutation(r._key,ct.exists(!0))])}function sI(r){return Jn(Q(r.firestore,nt),[new jn(r._key,ct.none())])}function iI(r,t){const e=Q(r.firestore,nt),n=yd(r),s=vi(r.converter,t);return Jn(e,[yi(on(r.firestore),"addDoc",n._key,s,r.converter!==null,{}).toMutation(n._key,ct.exists(!1))]).then((()=>n))}function oI(r,...t){var e,n,s;r=vt(r);let i={includeMetadataChanges:!1,source:"default"},a=0;typeof t[a]!="object"||So(t[a])||(i=t[a],a++);const u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(So(t[a])){const g=t[a];t[a]=(e=g.next)===null||e===void 0?void 0:e.bind(g),t[a+1]=(n=g.error)===null||n===void 0?void 0:n.bind(g),t[a+2]=(s=g.complete)===null||s===void 0?void 0:s.bind(g)}let c,h,f;if(r instanceof mt)h=Q(r.firestore,nt),f=Un(r._key.path),c={next:g=>{t[a]&&t[a](Ca(h,r,g))},error:t[a+1],complete:t[a+2]};else{const g=Q(r,wt);h=Q(g.firestore,nt),f=g._query;const _=new Me(h);c={next:R=>{t[a]&&t[a](new sn(h,_,g,R))},error:t[a+1],complete:t[a+2]},Cd(r._query)}return(function(_,R,C,N){const V=new fi(N),q=new la(R,V,C);return _.asyncQueue.enqueueAndForget((async()=>aa(await On(_),q))),()=>{V.Za(),_.asyncQueue.enqueueAndForget((async()=>ua(await On(_),q)))}})(ht(h),f,u,c)}function aI(r,t){return iy(ht(r=Q(r,nt)),So(t)?t:{next:t})}function Jn(r,t){return(function(n,s){const i=new Tt;return n.asyncQueue.enqueueAndForget((async()=>N_(await ya(n),s,i))),i.promise})(ht(r),t)}function Ca(r,t,e){const n=e.docs.get(t._key),s=new Me(r);return new rn(r,s,t._key,n,new _e(e.hasPendingWrites,e.fromCache),t.converter)}function uI(r){return Md(r,{count:kd()})}function Md(r,t){const e=Q(r.firestore,nt),n=ht(e),s=xl(t,((i,a)=>new uh(a,i.aggregateType,i._internalFieldPath)));return sy(n,r._query,s).then((i=>(function(u,c,h){const f=new Me(u);return new vd(c,f,h)})(e,r,i)))}class cI{constructor(t){this.kind="memory",this._onlineComponentProvider=Pe.provider,t?.garbageCollector?this._offlineComponentProvider=t.garbageCollector._offlineComponentProvider:this._offlineComponentProvider=be.provider}toJSON(){return{kind:this.kind}}}class lI{constructor(t){let e;this.kind="persistent",t?.tabManager?(t.tabManager._initialize(t),e=t.tabManager):(e=Od(void 0),e._initialize(t)),this._onlineComponentProvider=e._onlineComponentProvider,this._offlineComponentProvider=e._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class hI{constructor(){this.kind="memoryEager",this._offlineComponentProvider=be.provider}toJSON(){return{kind:this.kind}}}class dI{constructor(t){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new H_(t)}}toJSON(){return{kind:this.kind}}}function fI(){return new hI}function mI(r){return new dI(r?.cacheSizeBytes)}function gI(r){return new cI(r)}function pI(r){return new lI(r)}class _I{constructor(t){this.forceOwnership=t,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(t){this._onlineComponentProvider=Pe.provider,this._offlineComponentProvider={build:e=>new pa(e,t?.cacheSizeBytes,this.forceOwnership)}}}class yI{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(t){this._onlineComponentProvider=Pe.provider,this._offlineComponentProvider={build:e=>new ud(e,t?.cacheSizeBytes)}}}function Od(r){return new _I(r?.forceOwnership)}function II(){return new yI}const EI={maxAttempts:5};class Fd{constructor(t,e){this._firestore=t,this._commitHandler=e,this._mutations=[],this._committed=!1,this._dataReader=on(t)}set(t,e,n){this._verifyNotCommitted();const s=ge(t,this._firestore),i=vi(s.converter,e,n),a=yi(this._dataReader,"WriteBatch.set",s._key,i,s.converter!==null,n);return this._mutations.push(a.toMutation(s._key,ct.none())),this}
23update(t,e,n,...s){this._verifyNotCommitted();const i=ge(t,this._firestore);let a;return a=typeof(e=vt(e))=="string"||e instanceof Ne?ba(this._dataReader,"WriteBatch.update",i._key,e,n,s):Ra(this._dataReader,"WriteBatch.update",i._key,e),this._mutations.push(a.toMutation(i._key,ct.exists(!0))),this}delete(t){this._verifyNotCommitted();const e=ge(t,this._firestore);return this._mutations=this._mutations.concat(new jn(e._key,ct.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new D(P.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function ge(r,t){if((r=vt(r)).firestore!==t)throw new D(P.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return r}class Ld extends class{constructor(e,n){this._firestore=e,this._transaction=n,this._dataReader=on(e)}get(e){const n=ge(e,this._firestore),s=new zy(this._firestore);return this._transaction.lookup([n._key]).then((i=>{if(!i||i.length!==1)return F();const a=i[0];if(a.isFoundDocument())return new qr(this._firestore,s,a.key,a,n.converter);if(a.isNoDocument())return new qr(this._firestore,s,n._key,null,n.converter);throw F()}))}set(e,n,s){const i=ge(e,this._firestore),a=vi(i.converter,n,s),u=yi(this._dataReader,"Transaction.set",i._key,a,i.converter!==null,s);return this._transaction.set(i._key,u),this}update(e,n,s,...i){const a=ge(e,this._firestore);let u;return u=typeof(n=vt(n))=="string"||n instanceof Ne?ba(this._dataReader,"Transaction.update",a._key,n,s,i):Ra(this._dataReader,"Transaction.update",a._key,n),this._transaction.update(a._key,u),this}delete(e){const n=ge(e,this._firestore);return this._transaction.delete(n._key),this}}{constructor(t,e){super(t,e),this._firestore=t}get(t){const e=ge(t,this._firestore),n=new Me(this._firestore);return super.get(t).then((s=>new rn(this._firestore,n,e._key,s._document,new _e(!1,!1),e.converter)))}}function TI(r,t,e){r=Q(r,nt);const n=Object.assign(Object.assign({},EI),e);return(function(i){if(i.maxAttempts<1)throw new D(P.INVALID_ARGUMENT,"Max attempts must be at least 1")})(n),(function(i,a,u){const c=new Tt;return i.asyncQueue.enqueueAndForget((async()=>{const h=await hd(i);new X_(i.asyncQueue,h,u,a,c).au()})),c.promise})(ht(r),(s=>t(new Ld(r,s))),n)}function vI(){return new Zr("deleteField")}function wI(){return new Ta("serverTimestamp")}function AI(...r){return new va("arrayUnion",r)}function RI(...r){return new wa("arrayRemove",r)}function bI(r){return new Aa("increment",r)}function PI(r){return new Xr(r)}function SI(r){return ht(r=Q(r,nt)),new Fd(r,(t=>Jn(r,t)))}function VI(r,t){const e=ht(r=Q(r,nt));if(!e._uninitializedComponentsProvider||e._uninitializedComponentsProvider._offline.kind==="memory")return qt("Cannot enable indexes when persistence is disabled"),Promise.resolve();const n=(function(i){const a=typeof i=="string"?(function(h){try{return JSON.parse(h)}catch(f){throw new D(P.INVALID_ARGUMENT,"Failed to parse JSON: "+f?.message)}})(i):i,u=[];if(Array.isArray(a.indexes))for(const c of a.indexes){const h=Zc(c,"collectionGroup"),f=[];if(Array.isArray(c.fields))for(const g of c.fields){const _=Ii("setIndexConfiguration",Zc(g,"fieldPath"));g.arrayConfig==="CONTAINS"?f.push(new We(_,2)):g.order==="ASCENDING"?f.push(new We(_,0)):g.order==="DESCENDING"&&f.push(new We(_,1))}u.push(new An(An.UNKNOWN_ID,h,f,Rn.empty()))}return u})(t);return uy(e,n)}function Zc(r,t){if(typeof r[t]!="string")throw new D(P.INVALID_ARGUMENT,"Missing string value for: "+t);return r[t]}class Bd{constructor(t){this._firestore=t,this.type="PersistentCacheIndexManager"}}function CI(r){var t;r=Q(r,nt);const e=tl.get(r);if(e)return e;if(((t=ht(r)._uninitializedComponentsProvider)===null||t===void 0?void 0:t._offline.kind)!=="persistent")return null;const n=new Bd(r);return tl.set(r,n),n}function DI(r){Ud(r,!0)}function xI(r){Ud(r,!1)}function NI(r){ly(ht(r._firestore)).then((t=>x("deleting all persistent cache indexes succeeded"))).catch((t=>qt("deleting all persistent cache indexes failed",t)))}function Ud(r,t){cy(ht(r._firestore),t).then((e=>x(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e=>qt(`setting persistent cache index auto creation isEnabled=${t} failed`,e)))}const tl=new WeakMap;function kI(r){var t;
23const e=(t=ht(Q(r.firestore,nt))._onlineComponents)===null||t===void 0?void 0:t.datastore.serializer;return e===void 0?null:ai(e,kt(r._query))._t}function MI(r,t){var e;const n=xl(t,((i,a)=>new uh(a,i.aggregateType,i._internalFieldPath))),s=(e=ht(Q(r.firestore,nt))._onlineComponents)===null||e===void 0?void 0:e.datastore.serializer;return s===void 0?null:Th(s,$l(r._query),n,!0).request}class OI{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(t){return Da.instance.onExistenceFilterMismatch(t)}}class Da{constructor(){this.Uu=new Map}static get instance(){return Ss||(Ss=new Da,(function(e){if(Ks)throw new Error("a TestingHooksSpi instance is already set");Ks=e})(Ss)),Ss}et(t){this.Uu.forEach((e=>e(t)))}onExistenceFilterMismatch(t){const e=Symbol(),n=this.Uu;return n.set(e,t),()=>n.delete(e)}}let Ss=null;(function(t,e=!0){(function(s){Bn=s})(zm),qs(new Cr("firestore",((n,{instanceIdentifier:s,options:i})=>{const a=n.getProvider("app").getImmediate(),u=new nt(new sg(n.getProvider("auth-internal")),new ag(n.getProvider("app-check-internal")),(function(h,f){if(!Object.prototype.hasOwnProperty.apply(h.options,["projectId"]))throw new D(P.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Te(h.options.projectId,f)})(a,s),a);return i=Object.assign({useFetchStreams:e},i),u._setSettings(i),u}),"PUBLIC").setMultipleInstances(!0)),wr(zu,"4.7.3",t),wr(zu,"4.7.3","esm2017")})();const GI=Object.freeze(Object.defineProperty({__proto__:null,AbstractUserDataWriter:Va,AggregateField:Fn,AggregateQuerySnapshot:vd,Bytes:Se,CACHE_SIZE_UNLIMITED:my,CollectionReference:Gt,DocumentReference:mt,DocumentSnapshot:rn,FieldPath:Ne,FieldValue:ke,Firestore:nt,FirestoreError:D,GeoPoint:pi,LoadBundleTask:Id,PersistentCacheIndexManager:Bd,Query:wt,QueryCompositeFilterConstraint:un,QueryConstraint:Wn,QueryDocumentSnapshot:Vr,QueryEndAtConstraint:ns,QueryFieldFilterConstraint:Hn,QueryLimitConstraint:ts,QueryOrderByConstraint:Ti,QuerySnapshot:sn,QueryStartAtConstraint:es,SnapshotMetadata:_e,Timestamp:lt,Transaction:Ld,VectorValue:Xr,WriteBatch:Fd,_AutoId:No,_ByteString:dt,_DatabaseId:Te,_DocumentKey:O,_EmptyAppCheckTokenProvider:ug,_EmptyAuthCredentialsProvider:Il,_FieldPath:at,_TestingHooks:OI,_cast:Q,_debugAssert:ng,_internalAggregationQueryToProtoRunAggregationQueryRequest:MI,_internalQueryToProtoQueryTarget:kI,_isBase64Available:Og,_logWarn:qt,_validateIsNotUsedTogether:gd,addDoc:iI,aggregateFieldEqual:$y,aggregateQuerySnapshotEqual:Qy,and:My,arrayRemove:RI,arrayUnion:AI,average:Ky,clearIndexedDbPersistence:Iy,collection:hy,collectionGroup:dy,connectFirestoreEmulator:_d,count:kd,deleteAllPersistentCacheIndexes:NI,deleteDoc:sI,deleteField:vI,disableNetwork:vy,disablePersistentCacheIndexAutoCreation:xI,doc:yd,documentId:by,enableIndexedDbPersistence:_y,enableMultiTabIndexedDbPersistence:yy,enableNetwork:Ty,enablePersistentCacheIndexAutoCreation:DI,endAt:jy,endBefore:qy,ensureFirestoreConfigured:ht,executeWrite:Jn,getAggregateFromServer:Md,getCountFromServer:uI,getDoc:Jy,getDocFromCache:Yy,getDocFromServer:Xy,getDocs:Zy,getDocsFromCache:tI,getDocsFromServer:eI,getFirestore:py,getPersistentCacheIndexManager:CI,increment:bI,initializeFirestore:gy,limit:Fy,limitToLast:Ly,loadBundle:Ay,memoryEagerGarbageCollector:fI,memoryLocalCache:gI,memoryLruGarbageCollector:mI,namedQuery:Ry,onSnapshot:oI,onSnapshotsInSync:aI,or:ky,orderBy:Oy,persistentLocalCache:pI,persistentMultipleTabManager:II,persistentSingleTabManager:Od,query:xy,queryEqual:Ea,refEqual:fy,runTransaction:TI,serverTimestamp:wI,setDoc:nI,setIndexConfiguration:VI,setLogLevel:eg,snapshotEqual:Hy,startAfter:Uy,startAt:By,sum:Gy,terminate:wy,updateDoc:rI,vector:PI,waitForPendingWrites:Ey,where:Ny,writeBatch:SI},Symbol.toStringTag,{value:"Module"}));export{Cr as C,ol as E,Ln as F,al as L,qs as _,Do as a,vt as b,_d as c,FI as d,il as e,BI as f,py as g,LI as h,Gm as i,Km as j,He as k,GI as l,om as o,wr as r,Of as v};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.