import{A as Kv,B as Wv,C as z,D as gt,E as je,F as Nd,G as $v,H as Po,I as te,J as Ws,K as Wc,L as At,M as $c,N as Dd,O as Dt,P as Zn,Q as Qr,R as Hc,S as Qc,T as Hv,U as Bt,V as Ge,a as V,b as Ks,c as qc,d as Lv,e as Uv,f as Rd,g as Qe,h as jc,i as So,j as Pd,k as Bv,l as sn,m as xd,n as kd,o as Gc,p as qv,q as jv,r as zc,s as Oe,t as Gv,u as zv,v as Nt,w as Xn,x as Kc,y as Ro,z as Hr}from"./chunk-ATVQGBMO.js";import{c as Ov,d as Mv,g as Fv}from"./chunk-GOGW25MK.js";import{$ as K,$b as Cn,Ac as Co,Ca as Yn,D as Fc,Ec as Vv,F as vv,Fb as Ut,Gb as bn,H as Lc,Hb as Ao,I as Wr,J as wv,Jb as Ed,K as dd,Kb as Td,L as Ev,Lb as Id,M as Uc,Mb as Ad,N as In,Nb as Nv,O as fd,Ob as bd,Pb as at,R as Tv,Ra as Pv,S as Iv,Sa as yd,T as Av,X as Xe,Xa as qe,Y as nn,Yb as bo,_ as De,_b as Jn,_c as Bc,aa as se,ba as bv,bc as $r,c as Zt,d as en,e as _v,ea as An,f as js,fc as Cd,g as yv,ga as pd,gc as Sd,ha as md,hc as Sn,i as vo,j as Oc,jb as vd,k as Qn,ka as To,kb as rn,l as tn,la as gd,m as Mc,mb as xv,p as _e,pa as Ve,sa as Gs,sb as wd,ta as _d,tb as Io,ua as Cv,ub as kv,uc as zs,vb as Tt,vc as Dv,wa as Sv,wb as It,x as wo,y as Eo,ya as Rv,z as hd}from"./chunk-CGTN5U7L.js";import{a as Q,b as tt}from"./chunk-Q7L6LLAK.js";var Qv={production:!1,apiBaseUrl:"https://localhost:5001/api",firebase:{apiKey:"********************************",authDomain:"********************************",projectId:"********************************",storageBucket:"********************************",messagingSenderId:"********************************",appId:"********************************",measurementId:"********************************"}};var xo={baseUrl:Qv.apiBaseUrl??"https://localhost:5001/api",endpoints:{auth:"/v1/auth",users:"/users",tenants:"/tenants",masters:"/masters",billing:"/billing",localization:"/localization",theming:"/theming",platform:"/platform",monitoring:"/monitoring"}};var Yc=class n{accessTokenKey="master-admin-access-token";refreshTokenKey="master-admin-refresh-token";accessTokenExpiresOnKey="master-admin-access-token-expires-on";refreshTokenExpiresOnKey="master-admin-refresh-token-expires-on";userKey="master-admin-user";saveAuth(e){e.accessToken&&localStorage.setItem(this.accessTokenKey,e.accessToken),e.refreshToken&&localStorage.setItem(this.refreshTokenKey,e.refreshToken),e.accessTokenExpiresOn&&localStorage.setItem(this.accessTokenExpiresOnKey,e.accessTokenExpiresOn),e.refreshTokenExpiresOn&&localStorage.setItem(this.refreshTokenExpiresOnKey,e.refreshTokenExpiresOn);let t=this.buildUserProfile(e);t&&localStorage.setItem(this.userKey,JSON.stringify(t))}clearAuth(){localStorage.removeItem(this.accessTokenKey),localStorage.removeItem(this.refreshTokenKey),localStorage.removeItem(this.accessTokenExpiresOnKey),localStorage.removeItem(this.refreshTokenExpiresOnKey),localStorage.removeItem(this.userKey)}getAccessToken(){return localStorage.getItem(this.accessTokenKey)}getRefreshToken(){return localStorage.getItem(this.refreshTokenKey)}getAccessTokenExpiresOn(){return localStorage.getItem(this.accessTokenExpiresOnKey)}getRefreshTokenExpiresOn(){return localStorage.getItem(this.refreshTokenExpiresOnKey)}getUser(){let e=localStorage.getItem(this.userKey);return e?JSON.parse(e):null}buildUserProfile(e){return e.user?e.user:e.userId||e.email?{id:e.userId??"",email:e.email??"",roles:e.roles}:null}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})};var Yv=class n{http=se(Mv);tokenStorage=se(Yc);userSubject=new _v(this.tokenStorage.getUser());user$=this.userSubject.asObservable();currentUserSignal=Gs(this.tokenStorage.getUser());isRefreshing=!1;refreshPromise=null;login(e){return this.http.post(`${xo.baseUrl}${xo.endpoints.auth}/login`,e).pipe(_e(t=>{let r=this.buildUserFromResponse(t);return this.tokenStorage.saveAuth(t),this.userSubject.next(r),this.currentUserSignal.set(r),t}))}refreshAccessToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;let e=this.tokenStorage.getRefreshToken();return e?(this.isRefreshing=!0,this.refreshPromise=this.http.post(`${xo.baseUrl}${xo.endpoints.auth}/refresh`,{refreshToken:e}).pipe(_e(t=>{let r=this.buildUserFromResponse(t);return this.tokenStorage.saveAuth(t),this.userSubject.next(r),this.currentUserSignal.set(r),t}),hd(t=>(this.logout(),Mc(()=>t)))),this.refreshPromise.pipe(_e(t=>(this.isRefreshing=!1,this.refreshPromise=null,t)),hd(t=>(this.isRefreshing=!1,this.refreshPromise=null,Mc(()=>t))))):(this.logout(),Mc(()=>new Ov({status:401,statusText:"Refresh token missing"})))}logout(){this.tokenStorage.clearAuth(),this.userSubject.next(null),this.currentUserSignal.set(null),this.isRefreshing=!1,this.refreshPromise=null}get accessToken(){return this.tokenStorage.getAccessToken()}get isAuthenticated(){return!!this.accessToken}get currentUser(){return this.currentUserSignal()}buildUserFromResponse(e){return e.user?e.user:e.userId||e.email?{id:e.userId??"",email:e.email??"",roles:e.roles}:this.tokenStorage.getUser()}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})};var gS="firebase",_S="12.13.0";Bt(gS,_S,"app");function Pe(n){n===void 0&&(n=se(To));let e=n.get(_d);return t=>new Zt(r=>{let s=e.add(),i=!1;function o(){i||(s(),i=!0)}let a=t.subscribe({next:l=>{r.next(l),o()},complete:()=>{r.complete(),o()},error:l=>{r.error(l),o()}});return a.add(()=>{r.unsubscribe(),o()}),a})}var on=new Iv("ANGULARFIRE2_VERSION");var Jv=(n,e)=>{let t=e?[e]:Hv(),r=[];return t.forEach(s=>{s.container.getProvider(n).instances.forEach(o=>{r.includes(o)||r.push(o)})}),r},Vd=(function(n){return n[n.SILENT=0]="SILENT",n[n.WARN=1]="WARN",n[n.VERBOSE=2]="VERBOSE",n})(Vd||{}),ED=Co()&&typeof Zone<"u"?Vd.WARN:Vd.SILENT;var Jc=class{zone;delegate;constructor(e,t=yv){this.zone=e,this.delegate=t}now(){return this.delegate.now()}schedule(e,t,r){let s=this.zone,i=function(o){s?s.runGuarded(()=>{e.apply(this,[o])}):e.apply(this,[o])};return this.delegate.schedule(i,t,r)}},Jr=(()=>{class n{outsideAngular;insideAngular;constructor(){let t=se(Ve);this.outsideAngular=t.runOutsideAngular(()=>new Jc(typeof Zone>"u"?void 0:Zone.current)),this.insideAngular=t.run(()=>new Jc(typeof Zone>"u"?void 0:Zone.current,js))}static \u0275fac=function(r){return new(r||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})();var yS="firebase",vS="12.13.0";Ge.registerVersion(yS,vS,"app-compat");var wS=["ngOnDestroy"],Zv=(n,e,t,r={})=>new Proxy(n,{get:(s,i)=>t.runOutsideAngular(()=>{if(n[i])return r?.spy?.get&&r.spy.get(i,n[i]),n[i];if(wS.includes(i))return()=>{};let o=e.toPromise().then(a=>{let l=a?.[i];return typeof l=="function"?l.bind(a):l?.then?l.then(u=>t.run(()=>u)):t.run(()=>l)});return new Proxy(()=>{},{get:(a,l)=>o[l],apply:(a,l,u)=>o.then(d=>{let p=d?.(...u);return r?.spy?.apply&&r.spy.apply(i,u,p),p})})})});var Xc=class{constructor(e){return e}},er=new De("angularfire2.app.options"),tr=new De("angularfire2.app.name");function Xr(n,e,t){let r=typeof t=="string"&&t||"[DEFAULT]",s=typeof t=="object"&&t||{};s.name=s.name||r;let o=Ge.apps.find(a=>a&&a.name===s.name)||e.runOutsideAngular(()=>Ge.initializeApp(n,s));try{if(JSON.stringify(n)!==JSON.stringify(o.options)){let a=!!module.hot;ES("error",`${o.name} Firebase App already initialized with different options${a?", you may need to reload as Firebase is not HMR aware.":"."}`)}}catch{}return new Xc(o)}var ES=(n,...e)=>{Co()&&typeof console<"u"&&console[n](...e)},TS={provide:Xc,useFactory:Xr,deps:[er,Ve,[new Cv,tr]]},xD=(()=>{class n{static initializeApp(t,r){return{ngModule:n,providers:[{provide:er,useValue:t},{provide:tr,useValue:r}]}}constructor(t){Ge.registerVersion("angularfire",on.full,"core"),Ge.registerVersion("angularfire",on.full,"app-compat"),Ge.registerVersion("angular",Av.full,t.toString())}static \u0275fac=function(r){return new(r||n)(K(Yn))};static \u0275mod=rn({type:n});static \u0275inj=nn({providers:[TS]})}return n})();function $s(n,e,t,r,s){let[,i,o]=globalThis.\u0275AngularfireInstanceCache.find(a=>a[0]===n)||[];if(i)return IS(s,o)||(Xv("error",`${e} was already initialized on the ${t} Firebase App with different settings.${AS?" You may need to reload as Firebase is not HMR aware.":""}`),Xv("warn",{is:s,was:o})),i;{let a=r();return globalThis.\u0275AngularfireInstanceCache.push([n,a,s]),a}}function IS(n,e){try{return n.toString()===e.toString()}catch{return n===e}}var AS=typeof module<"u"&&!!module.hot,Xv=(n,...e)=>{Co()&&typeof console<"u"&&console[n](...e)};globalThis.\u0275AngularfireInstanceCache||=[];var bS=new Map,CS={activated:!1,tokenObservers:[]},SS={initialized:!1,enabled:!1};function qt(n){return bS.get(n)||Q({},CS)}function iw(){return SS}var RS="https://content-firebaseappcheck.googleapis.com/v1";var PS="exchangeDebugToken",ew={OFFSET_DURATION:300*1e3,RETRIAL_MIN_WAIT:30*1e3,RETRIAL_MAX_WAIT:960*1e3},LD=1440*60*1e3;var Ld=class{constructor(e,t,r,s,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=s,this.upperBound=i,this.pending=null,this.nextErrorWaitInterval=s,s>i)throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new Qe,this.pending.promise.catch(t=>{}),await xS(this.getNextRun(e)),this.pending.resolve(),await this.pending.promise,this.pending=new Qe,this.pending.promise.catch(t=>{}),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(t){this.retryPolicy(t)?this.process(!1).catch(()=>{}):this.stop()}}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();{let t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}};function xS(n){return new Promise(e=>{setTimeout(e,n)})}var kS={"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.","initial-throttle":"{$httpStatus} error. Attempts allowed again after {$time}",throttled:"Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}"},nr=new jv("appCheck","AppCheck",kS);function ow(n){if(!qt(n).activated)throw nr.create("use-before-activation",{appName:n.name})}async function aw({url:n,body:e},t){let r={"Content-Type":"application/json"},s=t.getImmediate({optional:!0});if(s){let p=await s.getHeartbeatsHeader();p&&(r["X-Firebase-Client"]=p)}let i={method:"POST",body:JSON.stringify(e),headers:r},o;try{o=await fetch(n,i)}catch(p){throw nr.create("fetch-network-error",{originalErrorMessage:p?.message})}if(o.status!==200)throw nr.create("fetch-status-error",{httpStatus:o.status});let a;try{a=await o.json()}catch(p){throw nr.create("fetch-parse-error",{originalErrorMessage:p?.message})}let l=a.ttl.match(/^([\d.]+)(s)$/);if(!l||!l[2]||isNaN(Number(l[1])))throw nr.create("fetch-parse-error",{originalErrorMessage:`ttl field (timeToLive) is not in standard Protobuf Duration format: ${a.ttl}`});let u=Number(l[1])*1e3,d=Date.now();return{token:a.token,expireTimeMillis:d+u,issuedAtTimeMillis:d}}function cw(n,e){let{projectId:t,appId:r,apiKey:s}=n.options;return{url:`${RS}/projects/${t}/apps/${r}:${PS}?key=${s}`,body:{debug_token:e}}}var NS="firebase-app-check-database",DS=1,Ud="firebase-app-check-store";var Zc=null;function VS(){return Zc||(Zc=new Promise((n,e)=>{try{let t=indexedDB.open(NS,DS);t.onsuccess=r=>{n(r.target.result)},t.onerror=r=>{e(nr.create("storage-open",{originalErrorMessage:r.target.error?.message}))},t.onupgradeneeded=r=>{let s=r.target.result;r.oldVersion===0&&s.createObjectStore(Ud,{keyPath:"compositeKey"})}}catch(t){e(nr.create("storage-open",{originalErrorMessage:t?.message}))}}),Zc)}function OS(n,e){return MS(FS(n),e)}async function MS(n,e){let r=(await VS()).transaction(Ud,"readwrite"),i=r.objectStore(Ud).put({compositeKey:n,value:e});return new Promise((o,a)=>{i.onsuccess=l=>{o()},r.onerror=l=>{a(nr.create("storage-set",{originalErrorMessage:l.target.error?.message}))}})}function FS(n){return`${n.options.appId}-${n.name}`}var ko=new Zn("@firebase/app-check");function Md(n,e){return Gc()?OS(n,e).catch(t=>{ko.warn(`Failed to write token to IndexedDB. Error: ${t}`)}):Promise.resolve()}function lw(){return iw().enabled}async function uw(){let n=iw();if(n.enabled&&n.token)return n.token.promise;throw Error(` Can't get debug token in production mode. `)}var LS={error:"UNKNOWN_ERROR"};function US(n){return qc.encodeString(JSON.stringify(n),!1)}async function Bd(n,e=!1,t=!1){let r=n.app;ow(r);let s=qt(r),i=s.token,o;if(i&&!No(i)&&(s.token=void 0,i=void 0),!i){let u=await s.cachedTokenPromise;u&&(No(u)?i=u:await Md(r,void 0))}if(!e&&i&&No(i))return{token:i.token};let a=!1;if(lw())try{let u=await uw();s.exchangeTokenPromise||(s.exchangeTokenPromise=aw(cw(r,u),n.heartbeatServiceProvider).finally(()=>{s.exchangeTokenPromise=void 0}),a=!0);let d=await s.exchangeTokenPromise;return await Md(r,d),s.token=d,{token:d.token}}catch(u){return u.code==="appCheck/throttled"||u.code==="appCheck/initial-throttle"?ko.warn(u.message):t&&ko.error(u),Fd(u)}try{s.exchangeTokenPromise||(s.exchangeTokenPromise=s.provider.getToken().finally(()=>{s.exchangeTokenPromise=void 0}),a=!0),i=await qt(r).exchangeTokenPromise}catch(u){u.code==="appCheck/throttled"||u.code==="appCheck/initial-throttle"?ko.warn(u.message):t&&ko.error(u),o=u}let l;return i?o?No(i)?l={token:i.token,internalError:o}:l=Fd(o):(l={token:i.token},s.token=i,await Md(r,i)):l=Fd(o),a&&GS(r,l),l}async function BS(n){let e=n.app;ow(e);let{provider:t}=qt(e);if(lw()){let r=await uw(),{token:s}=await aw(cw(e,r),n.heartbeatServiceProvider);return{token:s}}else{let{token:r}=await t.getToken();return{token:r}}}function qS(n,e,t,r){let{app:s}=n,i=qt(s),o={next:t,error:r,type:e};if(i.tokenObservers=[...i.tokenObservers,o],i.token&&No(i.token)){let a=i.token;Promise.resolve().then(()=>{t({token:a.token}),tw(n)}).catch(()=>{})}i.cachedTokenPromise.then(()=>tw(n))}function hw(n,e){let t=qt(n),r=t.tokenObservers.filter(s=>s.next!==e);r.length===0&&t.tokenRefresher&&t.tokenRefresher.isRunning()&&t.tokenRefresher.stop(),t.tokenObservers=r}function tw(n){let{app:e}=n,t=qt(e),r=t.tokenRefresher;r||(r=jS(n),t.tokenRefresher=r),!r.isRunning()&&t.isTokenAutoRefreshEnabled&&r.start()}function jS(n){let{app:e}=n;return new Ld(async()=>{let t=qt(e),r;if(t.token?r=await Bd(n,!0):r=await Bd(n),r.error)throw r.error;if(r.internalError)throw r.internalError},()=>!0,()=>{let t=qt(e);if(t.token){let r=t.token.issuedAtTimeMillis+(t.token.expireTimeMillis-t.token.issuedAtTimeMillis)*.5+3e5,s=t.token.expireTimeMillis-300*1e3;return r=Math.min(r,s),Math.max(0,r-Date.now())}else return 0},ew.RETRIAL_MIN_WAIT,ew.RETRIAL_MAX_WAIT)}function GS(n,e){let t=qt(n).tokenObservers;for(let r of t)try{r.type==="EXTERNAL"&&e.error!=null?r.error(e.error):r.next(e)}catch{}}function No(n){return n.expireTimeMillis-Date.now()>0}function Fd(n){return{token:US(LS),error:n}}var qd=class{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){let{tokenObservers:e}=qt(this.app);for(let t of e)hw(this.app,t.next);return Promise.resolve()}};function zS(n,e){return new qd(n,e)}function KS(n){return{getToken:e=>Bd(n,e),getLimitedUseToken:()=>BS(n),addTokenListener:e=>qS(n,"INTERNAL",e),removeTokenListener:e=>hw(n.app,e)}}var WS="@firebase/app-check",$S="0.11.3";var HS="app-check",nw="app-check-internal";function QS(){Qr(new At(HS,n=>{let e=n.getProvider("app").getImmediate(),t=n.getProvider("heartbeat");return zS(e,t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((n,e,t)=>{n.getProvider(nw).initialize()})),Qr(new At(nw,n=>{let e=n.getProvider("app-check").getImmediate();return KS(e)},"PUBLIC").setInstantiationMode("EXPLICIT")),Bt(WS,$S)}QS();var YS="app-check";var rr=class{constructor(){return Jv(YS)}};var JS=["localhost","0.0.0.0","127.0.0.1"],ZD=typeof window<"u"&&JS.includes(window.location.hostname);var Do=new De("angularfire2.auth.use-emulator"),Vo=new De("angularfire2.auth.settings"),Oo=new De("angularfire2.auth.tenant-id"),Mo=new De("angularfire2.auth.langugage-code"),Fo=new De("angularfire2.auth.use-device-language"),Lo=new De("angularfire.auth.persistence"),Uo=(n,e,t,r,s,i,o,a)=>$s(`${n.name}.auth`,"AngularFireAuth",n.name,()=>{let l=e.runOutsideAngular(()=>n.auth());if(t&&l.useEmulator(...t),r&&(l.tenantId=r),l.languageCode=s,i&&l.useDeviceLanguage(),o)for(let[u,d]of Object.entries(o))l.settings[u]=d;return a&&l.setPersistence(a),l},[t,r,s,i,o,a]),Bo=(()=>{class n{injector=se(An);authState;idToken;user;idTokenResult;credential;constructor(t,r,s,i,o,a,l,u,d,p,m,v){let S=new en,x=tn(void 0).pipe(vo(o.outsideAngular),In(()=>i.runOutsideAngular(()=>import("./chunk-KM2FEHKU.js"))),_e(()=>Xr(t,i,r)),_e(k=>Uo(k,i,a,u,d,p,l,m)),dd({bufferSize:1,refCount:!1}));if(Bc(s))this.authState=this.user=this.idToken=this.idTokenResult=this.credential=tn(null);else{x.pipe(vv()).subscribe();let k=x.pipe(In(L=>L.getRedirectResult().then(H=>H,()=>null)),Pe(this.injector),dd({bufferSize:1,refCount:!1})),q=x.pipe(In(L=>new Zt(H=>({unsubscribe:i.runOutsideAngular(()=>L.onAuthStateChanged(J=>H.next(J),J=>H.error(J),()=>H.complete()))})))),G=x.pipe(In(L=>new Zt(H=>({unsubscribe:i.runOutsideAngular(()=>L.onIdTokenChanged(J=>H.next(J),J=>H.error(J),()=>H.complete()))}))));this.authState=k.pipe(fd(q),Oc(o.outsideAngular),vo(o.insideAngular)),this.user=k.pipe(fd(G),Oc(o.outsideAngular),vo(o.insideAngular)),this.idToken=this.user.pipe(In(L=>L?Qn(L.getIdToken()):tn(null))),this.idTokenResult=this.user.pipe(In(L=>L?Qn(L.getIdTokenResult()):tn(null))),this.credential=wo(k,S,this.authState.pipe(Eo(L=>!L))).pipe(_e(L=>L?.user?L:null),Oc(o.outsideAngular),vo(o.insideAngular))}return Zv(this,x,i,{spy:{apply:(k,q,G)=>{(k.startsWith("signIn")||k.startsWith("createUser"))&&G.then(L=>S.next(L))}}})}static \u0275fac=function(r){return new(r||n)(K(er),K(tr,8),K(Yn),K(Ve),K(Jr),K(Do,8),K(Vo,8),K(Oo,8),K(Mo,8),K(Fo,8),K(Lo,8),K(rr,8))};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"any"})}return n})(),m1=(()=>{class n{constructor(){Ge.registerVersion("angularfire",on.full,"auth-compat")}static \u0275fac=function(r){return new(r||n)};static \u0275mod=rn({type:n});static \u0275inj=nn({providers:[Bo]})}return n})();var fw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},pw={};var Rn,Gd;(function(){var n;function e(E,_){function w(){}w.prototype=_.prototype,E.F=_.prototype,E.prototype=new w,E.prototype.constructor=E,E.D=function(I,T,b){for(var y=Array(arguments.length-2),mt=2;mt>>25),y=b+(T^_&(w^T))+I[1]+3905402710&4294967295,b=_+(y<<12&4294967295|y>>>20),y=T+(w^b&(_^w))+I[2]+606105819&4294967295,T=b+(y<<17&4294967295|y>>>15),y=w+(_^T&(b^_))+I[3]+3250441966&4294967295,w=T+(y<<22&4294967295|y>>>10),y=_+(b^w&(T^b))+I[4]+4118548399&4294967295,_=w+(y<<7&4294967295|y>>>25),y=b+(T^_&(w^T))+I[5]+1200080426&4294967295,b=_+(y<<12&4294967295|y>>>20),y=T+(w^b&(_^w))+I[6]+2821735955&4294967295,T=b+(y<<17&4294967295|y>>>15),y=w+(_^T&(b^_))+I[7]+4249261313&4294967295,w=T+(y<<22&4294967295|y>>>10),y=_+(b^w&(T^b))+I[8]+1770035416&4294967295,_=w+(y<<7&4294967295|y>>>25),y=b+(T^_&(w^T))+I[9]+2336552879&4294967295,b=_+(y<<12&4294967295|y>>>20),y=T+(w^b&(_^w))+I[10]+4294925233&4294967295,T=b+(y<<17&4294967295|y>>>15),y=w+(_^T&(b^_))+I[11]+2304563134&4294967295,w=T+(y<<22&4294967295|y>>>10),y=_+(b^w&(T^b))+I[12]+1804603682&4294967295,_=w+(y<<7&4294967295|y>>>25),y=b+(T^_&(w^T))+I[13]+4254626195&4294967295,b=_+(y<<12&4294967295|y>>>20),y=T+(w^b&(_^w))+I[14]+2792965006&4294967295,T=b+(y<<17&4294967295|y>>>15),y=w+(_^T&(b^_))+I[15]+1236535329&4294967295,w=T+(y<<22&4294967295|y>>>10),y=_+(T^b&(w^T))+I[1]+4129170786&4294967295,_=w+(y<<5&4294967295|y>>>27),y=b+(w^T&(_^w))+I[6]+3225465664&4294967295,b=_+(y<<9&4294967295|y>>>23),y=T+(_^w&(b^_))+I[11]+643717713&4294967295,T=b+(y<<14&4294967295|y>>>18),y=w+(b^_&(T^b))+I[0]+3921069994&4294967295,w=T+(y<<20&4294967295|y>>>12),y=_+(T^b&(w^T))+I[5]+3593408605&4294967295,_=w+(y<<5&4294967295|y>>>27),y=b+(w^T&(_^w))+I[10]+38016083&4294967295,b=_+(y<<9&4294967295|y>>>23),y=T+(_^w&(b^_))+I[15]+3634488961&4294967295,T=b+(y<<14&4294967295|y>>>18),y=w+(b^_&(T^b))+I[4]+3889429448&4294967295,w=T+(y<<20&4294967295|y>>>12),y=_+(T^b&(w^T))+I[9]+568446438&4294967295,_=w+(y<<5&4294967295|y>>>27),y=b+(w^T&(_^w))+I[14]+3275163606&4294967295,b=_+(y<<9&4294967295|y>>>23),y=T+(_^w&(b^_))+I[3]+4107603335&4294967295,T=b+(y<<14&4294967295|y>>>18),y=w+(b^_&(T^b))+I[8]+1163531501&4294967295,w=T+(y<<20&4294967295|y>>>12),y=_+(T^b&(w^T))+I[13]+2850285829&4294967295,_=w+(y<<5&4294967295|y>>>27),y=b+(w^T&(_^w))+I[2]+4243563512&4294967295,b=_+(y<<9&4294967295|y>>>23),y=T+(_^w&(b^_))+I[7]+1735328473&4294967295,T=b+(y<<14&4294967295|y>>>18),y=w+(b^_&(T^b))+I[12]+2368359562&4294967295,w=T+(y<<20&4294967295|y>>>12),y=_+(w^T^b)+I[5]+4294588738&4294967295,_=w+(y<<4&4294967295|y>>>28),y=b+(_^w^T)+I[8]+2272392833&4294967295,b=_+(y<<11&4294967295|y>>>21),y=T+(b^_^w)+I[11]+1839030562&4294967295,T=b+(y<<16&4294967295|y>>>16),y=w+(T^b^_)+I[14]+4259657740&4294967295,w=T+(y<<23&4294967295|y>>>9),y=_+(w^T^b)+I[1]+2763975236&4294967295,_=w+(y<<4&4294967295|y>>>28),y=b+(_^w^T)+I[4]+1272893353&4294967295,b=_+(y<<11&4294967295|y>>>21),y=T+(b^_^w)+I[7]+4139469664&4294967295,T=b+(y<<16&4294967295|y>>>16),y=w+(T^b^_)+I[10]+3200236656&4294967295,w=T+(y<<23&4294967295|y>>>9),y=_+(w^T^b)+I[13]+681279174&4294967295,_=w+(y<<4&4294967295|y>>>28),y=b+(_^w^T)+I[0]+3936430074&4294967295,b=_+(y<<11&4294967295|y>>>21),y=T+(b^_^w)+I[3]+3572445317&4294967295,T=b+(y<<16&4294967295|y>>>16),y=w+(T^b^_)+I[6]+76029189&4294967295,w=T+(y<<23&4294967295|y>>>9),y=_+(w^T^b)+I[9]+3654602809&4294967295,_=w+(y<<4&4294967295|y>>>28),y=b+(_^w^T)+I[12]+3873151461&4294967295,b=_+(y<<11&4294967295|y>>>21),y=T+(b^_^w)+I[15]+530742520&4294967295,T=b+(y<<16&4294967295|y>>>16),y=w+(T^b^_)+I[2]+3299628645&4294967295,w=T+(y<<23&4294967295|y>>>9),y=_+(T^(w|~b))+I[0]+4096336452&4294967295,_=w+(y<<6&4294967295|y>>>26),y=b+(w^(_|~T))+I[7]+1126891415&4294967295,b=_+(y<<10&4294967295|y>>>22),y=T+(_^(b|~w))+I[14]+2878612391&4294967295,T=b+(y<<15&4294967295|y>>>17),y=w+(b^(T|~_))+I[5]+4237533241&4294967295,w=T+(y<<21&4294967295|y>>>11),y=_+(T^(w|~b))+I[12]+1700485571&4294967295,_=w+(y<<6&4294967295|y>>>26),y=b+(w^(_|~T))+I[3]+2399980690&4294967295,b=_+(y<<10&4294967295|y>>>22),y=T+(_^(b|~w))+I[10]+4293915773&4294967295,T=b+(y<<15&4294967295|y>>>17),y=w+(b^(T|~_))+I[1]+2240044497&4294967295,w=T+(y<<21&4294967295|y>>>11),y=_+(T^(w|~b))+I[8]+1873313359&4294967295,_=w+(y<<6&4294967295|y>>>26),y=b+(w^(_|~T))+I[15]+4264355552&4294967295,b=_+(y<<10&4294967295|y>>>22),y=T+(_^(b|~w))+I[6]+2734768916&4294967295,T=b+(y<<15&4294967295|y>>>17),y=w+(b^(T|~_))+I[13]+1309151649&4294967295,w=T+(y<<21&4294967295|y>>>11),y=_+(T^(w|~b))+I[4]+4149444226&4294967295,_=w+(y<<6&4294967295|y>>>26),y=b+(w^(_|~T))+I[11]+3174756917&4294967295,b=_+(y<<10&4294967295|y>>>22),y=T+(_^(b|~w))+I[2]+718787259&4294967295,T=b+(y<<15&4294967295|y>>>17),y=w+(b^(T|~_))+I[9]+3951481745&4294967295,E.g[0]=E.g[0]+_&4294967295,E.g[1]=E.g[1]+(T+(y<<21&4294967295|y>>>11))&4294967295,E.g[2]=E.g[2]+T&4294967295,E.g[3]=E.g[3]+b&4294967295}r.prototype.v=function(E,_){_===void 0&&(_=E.length);let w=_-this.blockSize,I=this.C,T=this.h,b=0;for(;b<_;){if(T==0)for(;b<=w;)s(this,E,b),b+=this.blockSize;if(typeof E=="string"){for(;b<_;)if(I[T++]=E.charCodeAt(b++),T==this.blockSize){s(this,I),T=0;break}}else for(;b<_;)if(I[T++]=E[b++],T==this.blockSize){s(this,I),T=0;break}}this.h=T,this.o+=_},r.prototype.A=function(){var E=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);E[0]=128;for(var _=1;_>>I&255;return E};function i(E,_){var w=a;return Object.prototype.hasOwnProperty.call(w,E)?w[E]:w[E]=_(E)}function o(E,_){this.h=_;let w=[],I=!0;for(let T=E.length-1;T>=0;T--){let b=E[T]|0;I&&b==_||(w[T]=b,I=!1)}this.g=w}var a={};function l(E){return-128<=E&&E<128?i(E,function(_){return new o([_|0],_<0?-1:0)}):new o([E|0],E<0?-1:0)}function u(E){if(isNaN(E)||!isFinite(E))return p;if(E<0)return k(u(-E));let _=[],w=1;for(let I=0;E>=w;I++)_[I]=E/w|0,w*=4294967296;return new o(_,0)}function d(E,_){if(E.length==0)throw Error("number format error: empty string");if(_=_||10,_<2||36<_)throw Error("radix out of range: "+_);if(E.charAt(0)=="-")return k(d(E.substring(1),_));if(E.indexOf("-")>=0)throw Error('number format error: interior "-" character');let w=u(Math.pow(_,8)),I=p;for(let b=0;b=0?I:4294967296+I)*_,_*=4294967296}return E},n.toString=function(E){if(E=E||10,E<2||360?w.g[0]:w.h)>>>0).toString(E);if(w=T,S(w))return b+I;for(;b.length<6;)b="0"+b;I=b+I}},n.i=function(E){return E<0?0:E>>16)+(this.i(T)>>>16)+(E.i(T)>>>16);I=y>>>16,b&=65535,y&=65535,w[T]=y<<16|b}return new o(w,w[w.length-1]&-2147483648?-1:0)};function q(E,_){return E.add(k(_))}n.j=function(E){if(S(this)||S(E))return p;if(x(this))return x(E)?k(this).j(k(E)):k(k(this).j(E));if(x(E))return k(this.j(k(E)));if(this.l(v)<0&&E.l(v)<0)return u(this.m()*E.m());let _=this.g.length+E.g.length,w=[];for(var I=0;I<2*_;I++)w[I]=0;for(I=0;I>>16,y=this.i(I)&65535,mt=E.i(T)>>>16,jn=E.i(T)&65535;w[2*I+2*T]+=y*jn,G(w,2*I+2*T),w[2*I+2*T+1]+=b*jn,G(w,2*I+2*T+1),w[2*I+2*T+1]+=y*mt,G(w,2*I+2*T+1),w[2*I+2*T+2]+=b*mt,G(w,2*I+2*T+2)}for(E=0;E<_;E++)w[E]=w[2*E+1]<<16|w[2*E];for(E=_;E<2*_;E++)w[E]=0;return new o(w,0)};function G(E,_){for(;(E[_]&65535)!=E[_];)E[_+1]+=E[_]>>>16,E[_]&=65535,_++}function L(E,_){this.g=E,this.h=_}function H(E,_){if(S(_))throw Error("division by zero");if(S(E))return new L(p,p);if(x(E))return _=H(k(E),_),new L(k(_.g),k(_.h));if(x(_))return _=H(E,k(_)),new L(k(_.g),_.h);if(E.g.length>30){if(x(E)||x(_))throw Error("slowDivide_ only works with positive integers.");for(var w=m,I=_;I.l(E)<=0;)w=J(w),I=J(I);var T=oe(w,1),b=oe(I,1);for(I=oe(I,2),w=oe(w,2);!S(I);){var y=b.add(I);y.l(E)<=0&&(T=T.add(w),b=y),I=oe(I,1),w=oe(w,1)}return _=q(E,T.j(_)),new L(T,_)}for(T=p;E.l(_)>=0;){for(w=Math.max(1,Math.floor(E.m()/_.m())),I=Math.ceil(Math.log(w)/Math.LN2),I=I<=48?1:Math.pow(2,I-48),b=u(w),y=b.j(_);x(y)||y.l(E)>0;)w-=I,b=u(w),y=b.j(_);S(b)&&(b=m),T=T.add(b),E=q(E,y)}return new L(T,E)}n.B=function(E){return H(this,E).h},n.and=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let I=0;I<_;I++)w[I]=this.i(I)&E.i(I);return new o(w,this.h&E.h)},n.or=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let I=0;I<_;I++)w[I]=this.i(I)|E.i(I);return new o(w,this.h|E.h)},n.xor=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let I=0;I<_;I++)w[I]=this.i(I)^E.i(I);return new o(w,this.h^E.h)};function J(E){let _=E.g.length+1,w=[];for(let I=0;I<_;I++)w[I]=E.i(I)<<1|E.i(I-1)>>>31;return new o(w,E.h)}function oe(E,_){let w=_>>5;_%=32;let I=E.g.length-w,T=[];for(let b=0;b0?E.i(b+w)>>>_|E.i(b+w+1)<<32-_:E.i(b+w);return new o(T,E.h)}r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,Gd=pw.Md5=r,o.prototype.add=o.prototype.add,o.prototype.multiply=o.prototype.j,o.prototype.modulo=o.prototype.B,o.prototype.compare=o.prototype.l,o.prototype.toNumber=o.prototype.m,o.prototype.toString=o.prototype.toString,o.prototype.getBits=o.prototype.i,o.fromNumber=u,o.fromString=d,Rn=pw.Integer=o}).apply(typeof fw<"u"?fw:typeof self<"u"?self:typeof window<"u"?window:{});var el=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Pn={};var zd,XS,Hs,Kd,qo,tl,Wd,$d,Hd;(function(){var n,e=Object.defineProperty;function t(c){c=[typeof globalThis=="object"&&globalThis,c,typeof window=="object"&&window,typeof self=="object"&&self,typeof el=="object"&&el];for(var h=0;hc&&AsyncContext.Snapshot.wrap(c):c=>c;function v(c){let h=c.length;if(h>0){let f=Array(h);for(let g=0;g0?(this.h--,h=this.g,this.g=h.next,h.next=null):h=this.i(),h}}function k(c){o.setTimeout(()=>{throw c},0)}function q(){var c=E;let h=null;return c.g&&(h=c.g,c.g=c.g.next,c.g||(c.h=null),h.next=null),h}class G{constructor(){this.h=this.g=null}add(h,f){let g=L.get();g.set(h,f),this.h?this.h.next=g:this.g=g,this.h=g}}var L=new x(()=>new H,c=>c.reset());class H{constructor(){this.next=this.g=this.h=null}set(h,f){this.h=h,this.g=f,this.next=null}reset(){this.next=this.g=this.h=null}}let J,oe=!1,E=new G,_=()=>{let c=Promise.resolve(void 0);J=()=>{c.then(w)}};function w(){for(var c;c=q();){try{c.h.call(c.g)}catch(f){k(f)}var h=L;h.j(c),h.h<100&&(h.h++,c.next=h.g,h.g=c)}oe=!1}function I(){this.u=this.u,this.C=this.C}I.prototype.u=!1,I.prototype.dispose=function(){this.u||(this.u=!0,this.N())},I.prototype[Symbol.dispose]=function(){this.dispose()},I.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function T(c,h){this.type=c,this.g=this.target=h,this.defaultPrevented=!1}T.prototype.h=function(){this.defaultPrevented=!0};var b=(function(){if(!o.addEventListener||!Object.defineProperty)return!1;var c=!1,h=Object.defineProperty({},"passive",{get:function(){c=!0}});try{let f=()=>{};o.addEventListener("test",f,h),o.removeEventListener("test",f,h)}catch{}return c})();function y(c){return/^[\s\xa0]*$/.test(c)}function mt(c,h){T.call(this,c?c.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,c&&this.init(c,h)}p(mt,T),mt.prototype.init=function(c,h){let f=this.type=c.type,g=c.changedTouches&&c.changedTouches.length?c.changedTouches[0]:null;this.target=c.target||c.srcElement,this.g=h,h=c.relatedTarget,h||(f=="mouseover"?h=c.fromElement:f=="mouseout"&&(h=c.toElement)),this.relatedTarget=h,g?(this.clientX=g.clientX!==void 0?g.clientX:g.pageX,this.clientY=g.clientY!==void 0?g.clientY:g.pageY,this.screenX=g.screenX||0,this.screenY=g.screenY||0):(this.clientX=c.clientX!==void 0?c.clientX:c.pageX,this.clientY=c.clientY!==void 0?c.clientY:c.pageY,this.screenX=c.screenX||0,this.screenY=c.screenY||0),this.button=c.button,this.key=c.key||"",this.ctrlKey=c.ctrlKey,this.altKey=c.altKey,this.shiftKey=c.shiftKey,this.metaKey=c.metaKey,this.pointerId=c.pointerId||0,this.pointerType=c.pointerType,this.state=c.state,this.i=c,c.defaultPrevented&&mt.Z.h.call(this)},mt.prototype.h=function(){mt.Z.h.call(this);let c=this.i;c.preventDefault?c.preventDefault():c.returnValue=!1};var jn="closure_listenable_"+(Math.random()*1e6|0),UC=0;function BC(c,h,f,g,A){this.listener=c,this.proxy=null,this.src=h,this.type=f,this.capture=!!g,this.ha=A,this.key=++UC,this.da=this.fa=!1}function vc(c){c.da=!0,c.listener=null,c.proxy=null,c.src=null,c.ha=null}function wc(c,h,f){for(let g in c)h.call(f,c[g],g,c)}function qC(c,h){for(let f in c)h.call(void 0,c[f],f,c)}function my(c){let h={};for(let f in c)h[f]=c[f];return h}let gy="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function _y(c,h){let f,g;for(let A=1;A-1?(h=c[M],f||(h.fa=!1)):(h=new BC(h,this.src,P,!!g,A),h.fa=f,c.push(h)),h};function qh(c,h){let f=h.type;if(f in c.g){var g=c.g[f],A=Array.prototype.indexOf.call(g,h,void 0),P;(P=A>=0)&&Array.prototype.splice.call(g,A,1),P&&(vc(h),c.g[f].length==0&&(delete c.g[f],c.h--))}}function jh(c,h,f,g){for(let A=0;A-1&&(vc(h[f]),Array.prototype.splice.call(h,f,1),h.length==0&&(delete c.g[P],c.h--)))):c&&(c=Wh(c))&&(h=c.g[h.toString()],c=-1,h&&(c=jh(h,f,g,A)),(f=c>-1?h[c]:null)&&Kh(f))}function Kh(c){if(typeof c!="number"&&c&&!c.da){var h=c.src;if(h&&h[jn])qh(h.i,c);else{var f=c.type,g=c.proxy;h.removeEventListener?h.removeEventListener(f,g,c.capture):h.detachEvent?h.detachEvent(Ty(f),g):h.addListener&&h.removeListener&&h.removeListener(g),(f=Wh(h))?(qh(f,c),f.h==0&&(f.src=null,h[Gh]=null)):vc(c)}}}function Ty(c){return c in zh?zh[c]:zh[c]="on"+c}function GC(c,h){if(c.da)c=!0;else{h=new mt(h,this);let f=c.listener,g=c.ha||c.src;c.fa&&Kh(c),c=f.call(g,h)}return c}function Wh(c){return c=c[Gh],c instanceof Ec?c:null}var $h="__closure_events_fn_"+(Math.random()*1e9>>>0);function Hh(c){return typeof c=="function"?c:(c[$h]||(c[$h]=function(h){return c.handleEvent(h)}),c[$h])}function et(){I.call(this),this.i=new Ec(this),this.M=this,this.G=null}p(et,I),et.prototype[jn]=!0,et.prototype.removeEventListener=function(c,h,f,g){Ey(this,c,h,f,g)};function it(c,h){var f,g=c.G;if(g)for(f=[];g;g=g.G)f.push(g);if(c=c.M,g=h.type||h,typeof h=="string")h=new T(h,c);else if(h instanceof T)h.target=h.target||c;else{var A=h;h=new T(g,c),_y(h,A)}A=!0;let P,M;if(f)for(M=f.length-1;M>=0;M--)P=h.g=f[M],A=Tc(P,g,!0,h)&&A;if(P=h.g=c,A=Tc(P,g,!0,h)&&A,A=Tc(P,g,!1,h)&&A,f)for(M=0;M2147483647?-1:o.setTimeout(c,h||0)}function Iy(c){c.g=zC(()=>{c.g=null,c.i&&(c.i=!1,Iy(c))},c.l);let h=c.h;c.h=null,c.m.apply(null,h)}class KC extends I{constructor(h,f){super(),this.m=h,this.l=f,this.h=null,this.i=!1,this.g=null}j(h){this.h=arguments,this.g?this.i=!0:Iy(this)}N(){super.N(),this.g&&(o.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function no(c){I.call(this),this.h=c,this.g={}}p(no,I);var Ay=[];function by(c){wc(c.g,function(h,f){this.g.hasOwnProperty(f)&&Kh(h)},c),c.g={}}no.prototype.N=function(){no.Z.N.call(this),by(this)},no.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Qh=o.JSON.stringify,WC=o.JSON.parse,$C=class{stringify(c){return o.JSON.stringify(c,void 0)}parse(c){return o.JSON.parse(c,void 0)}};function Cy(){}function Sy(){}var ro={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Yh(){T.call(this,"d")}p(Yh,T);function Jh(){T.call(this,"c")}p(Jh,T);var qr={},Ry=null;function Ic(){return Ry=Ry||new et}qr.Ia="serverreachability";function Py(c){T.call(this,qr.Ia,c)}p(Py,T);function so(c){let h=Ic();it(h,new Py(h))}qr.STAT_EVENT="statevent";function xy(c,h){T.call(this,qr.STAT_EVENT,c),this.stat=h}p(xy,T);function ot(c){let h=Ic();it(h,new xy(h,c))}qr.Ja="timingevent";function ky(c,h){T.call(this,qr.Ja,c),this.size=h}p(ky,T);function io(c,h){if(typeof c!="function")throw Error("Fn must not be null and must be a function");return o.setTimeout(function(){c()},h)}function oo(){this.g=!0}oo.prototype.ua=function(){this.g=!1};function HC(c,h,f,g,A,P){c.info(function(){if(c.g)if(P){var M="",X=P.split("&");for(let pe=0;pe1){let He=Be[0];Be=Be[1];let Xt=He.split("_");M=Xt.length>=2&&Xt[1]=="type"?M+(He+"="+Be+"&"):M+(He+"=redacted&")}}}else M=null;else M=P;return"XMLHTTP REQ ("+g+") [attempt "+A+"]: "+h+` `+f+` `+M})}function QC(c,h,f,g,A,P,M){c.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+A+"]: "+h+` `+f+` `+P+" "+M})}function Us(c,h,f,g){c.info(function(){return"XMLHTTP TEXT ("+h+"): "+JC(c,f)+(g?" "+g:"")})}function YC(c,h){c.info(function(){return"TIMEOUT: "+h})}oo.prototype.info=function(){};function JC(c,h){if(!c.g)return h;if(!h)return null;try{let P=JSON.parse(h);if(P){for(c=0;c0&&c.length;)f.push(c.shift()),h--;return c.length&&f.push(c.join(":")),f}function Gn(c,h,f,g){this.j=c,this.i=h,this.l=f,this.S=g||1,this.V=new no(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Vy}function Vy(){this.i=null,this.g="",this.h=!1}var Oy={},Zh={};function ed(c,h,f){c.M=1,c.A=Cc(Jt(h)),c.u=f,c.R=!0,My(c,null)}function My(c,h){c.F=Date.now(),bc(c),c.B=Jt(c.A);var f=c.B,g=c.S;Array.isArray(g)||(g=[String(g)]),Qy(f.i,"t",g),c.C=0,f=c.j.L,c.h=new Vy,c.g=fv(c.j,f?h:null,!c.u),c.P>0&&(c.O=new KC(u(c.Y,c,c.g),c.P)),h=c.V,f=c.g,g=c.ba;var A="readystatechange";Array.isArray(A)||(A&&(Ay[0]=A.toString()),A=Ay);for(let P=0;P0&&!this.W){this.W=!0;var M=this.j;M.g==this&&M.aa&&!M.P&&(M.j.info("Great, no buffering proxy detected. Bytes received: "+f.length),ld(M),M.P=!0,ot(11))}}else Us(this.i,this.l,f,null),nd(this,f);X==4&&jr(this),this.o&&!this.K&&(X==4?lv(this.j,this):(this.o=!1,bc(this)))}else pS(this.g),h==400&&f.indexOf("Unknown SID")>0?(this.m=3,ot(12)):(this.m=0,ot(13)),jr(this),co(this)}}}catch{}};function ZC(c){if(!Fy(c))return c.g.la();let h=nv(c.g);if(h==="")return"";let f="",g=h.length,A=Wn(c.g)==4;if(!c.h.i){if(typeof TextDecoder>"u")return jr(c),co(c),"";c.h.i=new o.TextDecoder}for(let P=0;Ph.length?Zh:(h=h.slice(g,g+f),c.C=g+f,h)))}Gn.prototype.cancel=function(){this.K=!0,jr(this)};function bc(c){c.T=Date.now()+c.H,Ly(c,c.H)}function Ly(c,h){if(c.D!=null)throw Error("WatchDog timer not null");c.D=io(u(c.aa,c),h)}function td(c){c.D&&(o.clearTimeout(c.D),c.D=null)}Gn.prototype.aa=function(){this.D=null;let c=Date.now();c-this.T>=0?(YC(this.i,this.B),this.M!=2&&(so(),ot(17)),jr(this),this.m=2,co(this)):Ly(this,this.T-c)};function co(c){c.j.I==0||c.K||lv(c.j,c)}function jr(c){td(c);var h=c.O;h&&typeof h.dispose=="function"&&h.dispose(),c.O=null,by(c.V),c.g&&(h=c.g,c.g=null,h.abort(),h.dispose())}function nd(c,h){try{var f=c.j;if(f.I!=0&&(f.g==c||rd(f.h,c))){if(!c.L&&rd(f.h,c)&&f.I==3){try{var g=f.Ba.g.parse(h)}catch{g=null}if(Array.isArray(g)&&g.length==3){var A=g;if(A[0]==0){e:if(!f.v){if(f.g)if(f.g.F+3e30&&(g=1.5*$n,f.O=g,f.j.info("backChannelRequestTimeoutMs_="+g)),g=f;let Hn=c.g;if(Hn){let Vc=Hn.g?Hn.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Vc){var P=g.h;P.g||Vc.indexOf("spdy")==-1&&Vc.indexOf("quic")==-1&&Vc.indexOf("h2")==-1||(P.j=P.l,P.g=new Set,P.h&&(sd(P,P.h),P.h=null))}if(g.G){let ud=Hn.g?Hn.g.getResponseHeader("X-HTTP-Session-Id"):null;ud&&(g.wa=ud,we(g.J,g.G,ud))}}f.I=3,f.l&&f.l.ra(),f.aa&&(f.T=Date.now()-c.F,f.j.info("Handshake RTT: "+f.T+"ms")),g=f;var M=c;if(g.na=dv(g,g.L?g.ba:null,g.W),M.L){jy(g.h,M);var X=M,Be=g.O;Be&&(X.H=Be),X.D&&(td(X),bc(X)),g.g=M}else av(g);f.i.length>0&&kc(f)}else pe[0]!="stop"&&pe[0]!="close"||zr(f,7);else f.I==3&&(pe[0]=="stop"||pe[0]=="close"?pe[0]=="stop"?zr(f,7):ad(f):pe[0]!="noop"&&f.l&&f.l.qa(pe),f.A=0)}}so(4)}catch{}}var tS=class{constructor(c,h){this.g=c,this.map=h}};function Uy(c){this.l=c||10,o.PerformanceNavigationTiming?(c=o.performance.getEntriesByType("navigation"),c=c.length>0&&(c[0].nextHopProtocol=="hq"||c[0].nextHopProtocol=="h2")):c=!!(o.chrome&&o.chrome.loadTimes&&o.chrome.loadTimes()&&o.chrome.loadTimes().wasFetchedViaSpdy),this.j=c?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function By(c){return c.h?!0:c.g?c.g.size>=c.j:!1}function qy(c){return c.h?1:c.g?c.g.size:0}function rd(c,h){return c.h?c.h==h:c.g?c.g.has(h):!1}function sd(c,h){c.g?c.g.add(h):c.h=h}function jy(c,h){c.h&&c.h==h?c.h=null:c.g&&c.g.has(h)&&c.g.delete(h)}Uy.prototype.cancel=function(){if(this.i=Gy(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(let c of this.g.values())c.cancel();this.g.clear()}};function Gy(c){if(c.h!=null)return c.i.concat(c.h.G);if(c.g!=null&&c.g.size!==0){let h=c.i;for(let f of c.g.values())h=h.concat(f.G);return h}return v(c.i)}var zy=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function nS(c,h){if(c){c=c.split("&");for(let f=0;f=0?(A=c[f].substring(0,g),P=c[f].substring(g+1)):A=c[f],h(A,P?decodeURIComponent(P.replace(/\+/g," ")):"")}}}function zn(c){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let h;c instanceof zn?(this.l=c.l,lo(this,c.j),this.o=c.o,this.g=c.g,uo(this,c.u),this.h=c.h,id(this,Yy(c.i)),this.m=c.m):c&&(h=String(c).match(zy))?(this.l=!1,lo(this,h[1]||"",!0),this.o=ho(h[2]||""),this.g=ho(h[3]||"",!0),uo(this,h[4]),this.h=ho(h[5]||"",!0),id(this,h[6]||"",!0),this.m=ho(h[7]||"")):(this.l=!1,this.i=new po(null,this.l))}zn.prototype.toString=function(){let c=[];var h=this.j;h&&c.push(fo(h,Ky,!0),":");var f=this.g;return(f||h=="file")&&(c.push("//"),(h=this.o)&&c.push(fo(h,Ky,!0),"@"),c.push(ao(f).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),f=this.u,f!=null&&c.push(":",String(f))),(f=this.h)&&(this.g&&f.charAt(0)!="/"&&c.push("/"),c.push(fo(f,f.charAt(0)=="/"?iS:sS,!0))),(f=this.i.toString())&&c.push("?",f),(f=this.m)&&c.push("#",fo(f,aS)),c.join("")},zn.prototype.resolve=function(c){let h=Jt(this),f=!!c.j;f?lo(h,c.j):f=!!c.o,f?h.o=c.o:f=!!c.g,f?h.g=c.g:f=c.u!=null;var g=c.h;if(f)uo(h,c.u);else if(f=!!c.h){if(g.charAt(0)!="/")if(this.g&&!this.h)g="/"+g;else{var A=h.h.lastIndexOf("/");A!=-1&&(g=h.h.slice(0,A+1)+g)}if(A=g,A==".."||A==".")g="";else if(A.indexOf("./")!=-1||A.indexOf("/.")!=-1){g=A.lastIndexOf("/",0)==0,A=A.split("/");let P=[];for(let M=0;M1||P.length==1&&P[0]!="")&&P.pop(),g&&M==A.length&&P.push("")):(P.push(X),g=!0)}g=P.join("/")}else g=A}return f?h.h=g:f=c.i.toString()!=="",f?id(h,Yy(c.i)):f=!!c.m,f&&(h.m=c.m),h};function Jt(c){return new zn(c)}function lo(c,h,f){c.j=f?ho(h,!0):h,c.j&&(c.j=c.j.replace(/:$/,""))}function uo(c,h){if(h){if(h=Number(h),isNaN(h)||h<0)throw Error("Bad port number "+h);c.u=h}else c.u=null}function id(c,h,f){h instanceof po?(c.i=h,cS(c.i,c.l)):(f||(h=fo(h,oS)),c.i=new po(h,c.l))}function we(c,h,f){c.i.set(h,f)}function Cc(c){return we(c,"zx",Math.floor(Math.random()*2147483648).toString(36)+Math.abs(Math.floor(Math.random()*2147483648)^Date.now()).toString(36)),c}function ho(c,h){return c?h?decodeURI(c.replace(/%25/g,"%2525")):decodeURIComponent(c):""}function fo(c,h,f){return typeof c=="string"?(c=encodeURI(c).replace(h,rS),f&&(c=c.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c):null}function rS(c){return c=c.charCodeAt(0),"%"+(c>>4&15).toString(16)+(c&15).toString(16)}var Ky=/[#\/\?@]/g,sS=/[#\?:]/g,iS=/[#\?]/g,oS=/[#\?@]/g,aS=/#/g;function po(c,h){this.h=this.g=null,this.i=c||null,this.j=!!h}function Gr(c){c.g||(c.g=new Map,c.h=0,c.i&&nS(c.i,function(h,f){c.add(decodeURIComponent(h.replace(/\+/g," ")),f)}))}n=po.prototype,n.add=function(c,h){Gr(this),this.i=null,c=Bs(this,c);let f=this.g.get(c);return f||this.g.set(c,f=[]),f.push(h),this.h+=1,this};function Wy(c,h){Gr(c),h=Bs(c,h),c.g.has(h)&&(c.i=null,c.h-=c.g.get(h).length,c.g.delete(h))}function $y(c,h){return Gr(c),h=Bs(c,h),c.g.has(h)}n.forEach=function(c,h){Gr(this),this.g.forEach(function(f,g){f.forEach(function(A){c.call(h,A,g,this)},this)},this)};function Hy(c,h){Gr(c);let f=[];if(typeof h=="string")$y(c,h)&&(f=f.concat(c.g.get(Bs(c,h))));else for(c=Array.from(c.g.values()),h=0;h0?String(c[0]):h):h};function Qy(c,h,f){Wy(c,h),f.length>0&&(c.i=null,c.g.set(Bs(c,h),v(f)),c.h+=f.length)}n.toString=function(){if(this.i)return this.i;if(!this.g)return"";let c=[],h=Array.from(this.g.keys());for(let g=0;g{g.abort(),Kn(f,"TestPingServer: timeout",!1,h)},1e4);fetch(c,{signal:g.signal}).then(P=>{clearTimeout(A),P.ok?Kn(f,"TestPingServer: ok",!0,h):Kn(f,"TestPingServer: server error",!1,h)}).catch(()=>{clearTimeout(A),Kn(f,"TestPingServer: error",!1,h)})}function Kn(c,h,f,g,A){try{A&&(A.onload=null,A.onerror=null,A.onabort=null,A.ontimeout=null),g(f)}catch{}}function hS(){this.g=new $C}function Sc(c){this.i=c.Sb||null,this.h=c.ab||!1}p(Sc,Cy),Sc.prototype.g=function(){return new Rc(this.i,this.h)};function Rc(c,h){et.call(this),this.H=c,this.o=h,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}p(Rc,et),n=Rc.prototype,n.open=function(c,h){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.F=c,this.D=h,this.readyState=1,go(this)},n.send=function(c){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;let h={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};c&&(h.body=c),(this.H||o).fetch(new Request(this.D,h)).then(this.Pa.bind(this),this.ga.bind(this))},n.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&this.readyState!=4&&(this.g=!1,mo(this)),this.readyState=0},n.Pa=function(c){if(this.g&&(this.l=c,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=c.headers,this.readyState=2,go(this)),this.g&&(this.readyState=3,go(this),this.g)))if(this.responseType==="arraybuffer")c.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(typeof o.ReadableStream<"u"&&"body"in c){if(this.j=c.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.B=new TextDecoder;Jy(this)}else c.text().then(this.Oa.bind(this),this.ga.bind(this))};function Jy(c){c.j.read().then(c.Ma.bind(c)).catch(c.ga.bind(c))}n.Ma=function(c){if(this.g){if(this.o&&c.value)this.response.push(c.value);else if(!this.o){var h=c.value?c.value:new Uint8Array(0);(h=this.B.decode(h,{stream:!c.done}))&&(this.response=this.responseText+=h)}c.done?mo(this):go(this),this.readyState==3&&Jy(this)}},n.Oa=function(c){this.g&&(this.response=this.responseText=c,mo(this))},n.Na=function(c){this.g&&(this.response=c,mo(this))},n.ga=function(){this.g&&mo(this)};function mo(c){c.readyState=4,c.l=null,c.j=null,c.B=null,go(c)}n.setRequestHeader=function(c,h){this.A.append(c,h)},n.getResponseHeader=function(c){return this.h&&this.h.get(c.toLowerCase())||""},n.getAllResponseHeaders=function(){if(!this.h)return"";let c=[],h=this.h.entries();for(var f=h.next();!f.done;)f=f.value,c.push(f[0]+": "+f[1]),f=h.next();return c.join(`\r `)};function go(c){c.onreadystatechange&&c.onreadystatechange.call(c)}Object.defineProperty(Rc.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(c){this.m=c?"include":"same-origin"}});function Xy(c){let h="";return wc(c,function(f,g){h+=g,h+=":",h+=f,h+=`\r `}),h}function od(c,h,f){e:{for(g in f){var g=!1;break e}g=!0}g||(f=Xy(f),typeof c=="string"?f!=null&&ao(f):we(c,h,f))}function Ce(c){et.call(this),this.headers=new Map,this.L=c||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}p(Ce,et);var dS=/^https?$/i,fS=["POST","PUT"];n=Ce.prototype,n.Fa=function(c){this.H=c},n.ea=function(c,h,f,g){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+c);h=h?h.toUpperCase():"GET",this.D=c,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():Dy.g(),this.g.onreadystatechange=m(u(this.Ca,this));try{this.B=!0,this.g.open(h,String(c),!0),this.B=!1}catch(P){Zy(this,P);return}if(c=f||"",f=new Map(this.headers),g)if(Object.getPrototypeOf(g)===Object.prototype)for(var A in g)f.set(A,g[A]);else if(typeof g.keys=="function"&&typeof g.get=="function")for(let P of g.keys())f.set(P,g.get(P));else throw Error("Unknown input type for opt_headers: "+String(g));g=Array.from(f.keys()).find(P=>P.toLowerCase()=="content-type"),A=o.FormData&&c instanceof o.FormData,!(Array.prototype.indexOf.call(fS,h,void 0)>=0)||g||A||f.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(let[P,M]of f)this.g.setRequestHeader(P,M);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(c),this.v=!1}catch(P){Zy(this,P)}};function Zy(c,h){c.h=!1,c.g&&(c.j=!0,c.g.abort(),c.j=!1),c.l=h,c.o=5,ev(c),Pc(c)}function ev(c){c.A||(c.A=!0,it(c,"complete"),it(c,"error"))}n.abort=function(c){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=c||7,it(this,"complete"),it(this,"abort"),Pc(this))},n.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Pc(this,!0)),Ce.Z.N.call(this)},n.Ca=function(){this.u||(this.B||this.v||this.j?tv(this):this.Xa())},n.Xa=function(){tv(this)};function tv(c){if(c.h&&typeof i<"u"){if(c.v&&Wn(c)==4)setTimeout(c.Ca.bind(c),0);else if(it(c,"readystatechange"),Wn(c)==4){c.h=!1;try{let P=c.ca();e:switch(P){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var h=!0;break e;default:h=!1}var f;if(!(f=h)){var g;if(g=P===0){let M=String(c.D).match(zy)[1]||null;!M&&o.self&&o.self.location&&(M=o.self.location.protocol.slice(0,-1)),g=!dS.test(M?M.toLowerCase():"")}f=g}if(f)it(c,"complete"),it(c,"success");else{c.o=6;try{var A=Wn(c)>2?c.g.statusText:""}catch{A=""}c.l=A+" ["+c.ca()+"]",ev(c)}}finally{Pc(c)}}}}function Pc(c,h){if(c.g){c.m&&(clearTimeout(c.m),c.m=null);let f=c.g;c.g=null,h||it(c,"ready");try{f.onreadystatechange=null}catch{}}}n.isActive=function(){return!!this.g};function Wn(c){return c.g?c.g.readyState:0}n.ca=function(){try{return Wn(this)>2?this.g.status:-1}catch{return-1}},n.la=function(){try{return this.g?this.g.responseText:""}catch{return""}},n.La=function(c){if(this.g){var h=this.g.responseText;return c&&h.indexOf(c)==0&&(h=h.substring(c.length)),WC(h)}};function nv(c){try{if(!c.g)return null;if("response"in c.g)return c.g.response;switch(c.F){case"":case"text":return c.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in c.g)return c.g.mozResponseArrayBuffer}return null}catch{return null}}function pS(c){let h={};c=(c.g&&Wn(c)>=2&&c.g.getAllResponseHeaders()||"").split(`\r `);for(let g=0;g0&&(this.ia=c.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}n=rv.prototype,n.ka=8,n.I=1,n.connect=function(c,h,f,g){ot(0),this.W=c,this.H=h||{},f&&g!==void 0&&(this.H.OSID=f,this.H.OAID=g),this.F=this.X,this.J=dv(this,null,this.W),kc(this)};function ad(c){if(sv(c),c.I==3){var h=c.V++,f=Jt(c.J);if(we(f,"SID",c.M),we(f,"RID",h),we(f,"TYPE","terminate"),yo(c,f),h=new Gn(c,c.j,h),h.M=2,h.A=Cc(Jt(f)),f=!1,o.navigator&&o.navigator.sendBeacon)try{f=o.navigator.sendBeacon(h.A.toString(),"")}catch{}!f&&o.Image&&(new Image().src=h.A,f=!0),f||(h.g=fv(h.j,null),h.g.ea(h.A)),h.F=Date.now(),bc(h)}hv(c)}function xc(c){c.g&&(ld(c),c.g.cancel(),c.g=null)}function sv(c){xc(c),c.v&&(o.clearTimeout(c.v),c.v=null),Nc(c),c.h.cancel(),c.m&&(typeof c.m=="number"&&o.clearTimeout(c.m),c.m=null)}function kc(c){if(!By(c.h)&&!c.m){c.m=!0;var h=c.Ea;J||_(),oe||(J(),oe=!0),E.add(h,c),c.D=0}}function mS(c,h){return qy(c.h)>=c.h.j-(c.m?1:0)?!1:c.m?(c.i=h.G.concat(c.i),!0):c.I==1||c.I==2||c.D>=(c.Sa?0:c.Ta)?!1:(c.m=io(u(c.Ea,c,h),uv(c,c.D)),c.D++,!0)}n.Ea=function(c){if(this.m)if(this.m=null,this.I==1){if(!c){this.V=Math.floor(Math.random()*1e5),c=this.V++;let A=new Gn(this,this.j,c),P=this.o;if(this.U&&(P?(P=my(P),_y(P,this.U)):P=this.U),this.u!==null||this.R||(A.J=P,P=null),this.S)e:{for(var h=0,f=0;f4096){h=f;break e}if(h===4096||f===this.i.length-1){h=f+1;break e}}h=1e3}else h=1e3;h=ov(this,A,h),f=Jt(this.J),we(f,"RID",c),we(f,"CVER",22),this.G&&we(f,"X-HTTP-Session-Id",this.G),yo(this,f),P&&(this.R?h="headers="+ao(Xy(P))+"&"+h:this.u&&od(f,this.u,P)),sd(this.h,A),this.Ra&&we(f,"TYPE","init"),this.S?(we(f,"$req",h),we(f,"SID","null"),A.U=!0,ed(A,f,null)):ed(A,f,h),this.I=2}}else this.I==3&&(c?iv(this,c):this.i.length==0||By(this.h)||iv(this))};function iv(c,h){var f;h?f=h.l:f=c.V++;let g=Jt(c.J);we(g,"SID",c.M),we(g,"RID",f),we(g,"AID",c.K),yo(c,g),c.u&&c.o&&od(g,c.u,c.o),f=new Gn(c,c.j,f,c.D+1),c.u===null&&(f.J=c.o),h&&(c.i=h.G.concat(c.i)),h=ov(c,f,1e3),f.H=Math.round(c.va*.5)+Math.round(c.va*.5*Math.random()),sd(c.h,f),ed(f,g,h)}function yo(c,h){c.H&&wc(c.H,function(f,g){we(h,g,f)}),c.l&&wc({},function(f,g){we(h,g,f)})}function ov(c,h,f){f=Math.min(c.i.length,f);let g=c.l?u(c.l.Ka,c.l,c):null;e:{var A=c.i;let X=-1;for(;;){let Be=["count="+f];X==-1?f>0?(X=A[0].g,Be.push("ofs="+X)):X=0:Be.push("ofs="+X);let pe=!0;for(let He=0;He=3?!1:(c.Y++,c.v=io(u(c.Da,c),uv(c,c.A)),c.A++,!0)}n.Da=function(){if(this.v=null,cv(this),this.aa&&!(this.P||this.g==null||this.T<=0)){var c=4*this.T;this.j.info("BP detection timer enabled: "+c),this.B=io(u(this.Wa,this),c)}},n.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,ot(10),xc(this),cv(this))};function ld(c){c.B!=null&&(o.clearTimeout(c.B),c.B=null)}function cv(c){c.g=new Gn(c,c.j,"rpc",c.Y),c.u===null&&(c.g.J=c.o),c.g.P=0;var h=Jt(c.na);we(h,"RID","rpc"),we(h,"SID",c.M),we(h,"AID",c.K),we(h,"CI",c.F?"0":"1"),!c.F&&c.ia&&we(h,"TO",c.ia),we(h,"TYPE","xmlhttp"),yo(c,h),c.u&&c.o&&od(h,c.u,c.o),c.O&&(c.g.H=c.O);var f=c.g;c=c.ba,f.M=1,f.A=Cc(Jt(h)),f.u=null,f.R=!0,My(f,c)}n.Va=function(){this.C!=null&&(this.C=null,xc(this),cd(this),ot(19))};function Nc(c){c.C!=null&&(o.clearTimeout(c.C),c.C=null)}function lv(c,h){var f=null;if(c.g==h){Nc(c),ld(c),c.g=null;var g=2}else if(rd(c.h,h))f=h.G,jy(c.h,h),g=1;else return;if(c.I!=0){if(h.o)if(g==1){f=h.u?h.u.length:0,h=Date.now()-h.F;var A=c.D;g=Ic(),it(g,new ky(g,f)),kc(c)}else av(c);else if(A=h.m,A==3||A==0&&h.X>0||!(g==1&&mS(c,h)||g==2&&cd(c)))switch(f&&f.length>0&&(h=c.h,h.i=h.i.concat(f)),A){case 1:zr(c,5);break;case 4:zr(c,10);break;case 3:zr(c,6);break;default:zr(c,2)}}}function uv(c,h){let f=c.Qa+Math.floor(Math.random()*c.Za);return c.isActive()||(f*=2),f*h}function zr(c,h){if(c.j.info("Error code "+h),h==2){var f=u(c.bb,c),g=c.Ua;let A=!g;g=new zn(g||"//www.google.com/images/cleardot.gif"),o.location&&o.location.protocol=="http"||lo(g,"https"),Cc(g),A?lS(g.toString(),f):uS(g.toString(),f)}else ot(2);c.I=0,c.l&&c.l.pa(h),hv(c),sv(c)}n.bb=function(c){c?(this.j.info("Successfully pinged google.com"),ot(2)):(this.j.info("Failed to ping google.com"),ot(1))};function hv(c){if(c.I=0,c.ja=[],c.l){let h=Gy(c.h);(h.length!=0||c.i.length!=0)&&(S(c.ja,h),S(c.ja,c.i),c.h.i.length=0,v(c.i),c.i.length=0),c.l.oa()}}function dv(c,h,f){var g=f instanceof zn?Jt(f):new zn(f);if(g.g!="")h&&(g.g=h+"."+g.g),uo(g,g.u);else{var A=o.location;g=A.protocol,h=h?h+"."+A.hostname:A.hostname,A=+A.port;let P=new zn(null);g&&lo(P,g),h&&(P.g=h),A&&uo(P,A),f&&(P.h=f),g=P}return f=c.G,h=c.wa,f&&h&&we(g,f,h),we(g,"VER",c.ka),yo(c,g),g}function fv(c,h,f){if(h&&!c.L)throw Error("Can't create secondary domain capable XhrIo object.");return h=c.Aa&&!c.ma?new Ce(new Sc({ab:f})):new Ce(c.ma),h.Fa(c.L),h}n.isActive=function(){return!!this.l&&this.l.isActive(this)};function pv(){}n=pv.prototype,n.ra=function(){},n.qa=function(){},n.pa=function(){},n.oa=function(){},n.isActive=function(){return!0},n.Ka=function(){};function Dc(){}Dc.prototype.g=function(c,h){return new Et(c,h)};function Et(c,h){et.call(this),this.g=new rv(h),this.l=c,this.h=h&&h.messageUrlParams||null,c=h&&h.messageHeaders||null,h&&h.clientProtocolHeaderRequired&&(c?c["X-Client-Protocol"]="webchannel":c={"X-Client-Protocol":"webchannel"}),this.g.o=c,c=h&&h.initMessageHeaders||null,h&&h.messageContentType&&(c?c["X-WebChannel-Content-Type"]=h.messageContentType:c={"X-WebChannel-Content-Type":h.messageContentType}),h&&h.sa&&(c?c["X-WebChannel-Client-Profile"]=h.sa:c={"X-WebChannel-Client-Profile":h.sa}),this.g.U=c,(c=h&&h.Qb)&&!y(c)&&(this.g.u=c),this.A=h&&h.supportsCrossDomainXhr||!1,this.v=h&&h.sendRawJson||!1,(h=h&&h.httpSessionIdParam)&&!y(h)&&(this.g.G=h,c=this.h,c!==null&&h in c&&(c=this.h,h in c&&delete c[h])),this.j=new qs(this)}p(Et,et),Et.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},Et.prototype.close=function(){ad(this.g)},Et.prototype.o=function(c){var h=this.g;if(typeof c=="string"){var f={};f.__data__=c,c=f}else this.v&&(f={},f.__data__=Qh(c),c=f);h.i.push(new tS(h.Ya++,c)),h.I==3&&kc(h)},Et.prototype.N=function(){this.g.l=null,delete this.j,ad(this.g),delete this.g,Et.Z.N.call(this)};function mv(c){Yh.call(this),c.__headers__&&(this.headers=c.__headers__,this.statusCode=c.__status__,delete c.__headers__,delete c.__status__);var h=c.__sm__;if(h){e:{for(let f in h){c=f;break e}c=void 0}(this.i=c)&&(c=this.i,h=h!==null&&c in h?h[c]:void 0),this.data=h}else this.data=c}p(mv,Yh);function gv(){Jh.call(this),this.status=1}p(gv,Jh);function qs(c){this.g=c}p(qs,pv),qs.prototype.ra=function(){it(this.g,"a")},qs.prototype.qa=function(c){it(this.g,new mv(c))},qs.prototype.pa=function(c){it(this.g,new gv)},qs.prototype.oa=function(){it(this.g,"b")},Dc.prototype.createWebChannel=Dc.prototype.g,Et.prototype.send=Et.prototype.o,Et.prototype.open=Et.prototype.m,Et.prototype.close=Et.prototype.close,Hd=Pn.createWebChannelTransport=function(){return new Dc},$d=Pn.getStatEventTarget=function(){return Ic()},Wd=Pn.Event=qr,tl=Pn.Stat={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Ac.NO_ERROR=0,Ac.TIMEOUT=8,Ac.HTTP_ERROR=6,qo=Pn.ErrorCode=Ac,Ny.COMPLETE="complete",Kd=Pn.EventType=Ny,Sy.EventType=ro,ro.OPEN="a",ro.CLOSE="b",ro.ERROR="c",ro.MESSAGE="d",et.prototype.listen=et.prototype.J,Hs=Pn.WebChannel=Sy,XS=Pn.FetchXmlHttpFactory=Sc,Ce.prototype.listenOnce=Ce.prototype.K,Ce.prototype.getLastError=Ce.prototype.Ha,Ce.prototype.getLastErrorCode=Ce.prototype.ya,Ce.prototype.getStatus=Ce.prototype.ca,Ce.prototype.getResponseJson=Ce.prototype.La,Ce.prototype.getResponseText=Ce.prototype.la,Ce.prototype.send=Ce.prototype.ea,Ce.prototype.setWithCredentials=Ce.prototype.Fa,zd=Pn.XhrIo=Ce}).apply(typeof el<"u"?el:typeof self<"u"?self:typeof window<"u"?window:{});var Le=class{constructor(e){this.uid=e}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}};Le.UNAUTHENTICATED=new Le(null),Le.GOOGLE_CREDENTIALS=new Le("google-credentials-uid"),Le.FIRST_PARTY=new Le("first-party-uid"),Le.MOCK_USER=new Le("mock-user");var Ri="12.13.0";function bE(n){Ri=n}var ur=new Zn("@firebase/firestore");function ti(){return ur.logLevel}function Hp(n){ur.setLogLevel(n)}function D(n,...e){if(ur.logLevel<=Dt.DEBUG){let t=e.map(Qp);ur.debug(`Firestore (${Ri}): ${n}`,...t)}}function xe(n,...e){if(ur.logLevel<=Dt.ERROR){let t=e.map(Qp);ur.error(`Firestore (${Ri}): ${n}`,...t)}}function vt(n,...e){if(ur.logLevel<=Dt.WARN){let t=e.map(Qp);ur.warn(`Firestore (${Ri}): ${n}`,...t)}}function Qp(n){if(typeof n=="string")return n;try{return(function(t){return JSON.stringify(t)})(n)}catch{return n}}function U(n,e,t){let r="Unexpected state";typeof e=="string"?r=e:t=e,CE(n,r,t)}function CE(n,e,t){let r=`FIRESTORE (${Ri}) INTERNAL ASSERTION FAILED: ${e} (ID: ${n.toString(16)})`;if(t!==void 0)try{r+=" CONTEXT: "+JSON.stringify(t)}catch{r+=" CONTEXT: "+t}throw xe(r),new Error(r)}function B(n,e,t,r){let s="Unexpected state";typeof t=="string"?s=t:r=t,n||CE(e,s,r)}function Yp(n,e){n||U(57014,e)}function F(n,e){return n}var R={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"},N=class extends qv{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var ze=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};var ml=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},gl=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Le.UNAUTHENTICATED))}shutdown(){}},rf=class{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}},_l=class{constructor(e){this.t=e,this.currentUser=Le.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){B(this.o===void 0,42304);let r=this.i,s=l=>this.i!==r?(r=this.i,t(l)):Promise.resolve(),i=new ze;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new ze,e.enqueueRetryable(()=>s(this.currentUser))};let o=()=>{let l=i;e.enqueueRetryable(async()=>{await l.promise,await s(this.currentUser)})},a=l=>{D("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=l,this.o&&(this.auth.addAuthTokenListener(this.o),o())};this.t.onInit(l=>a(l)),setTimeout(()=>{if(!this.auth){let l=this.t.getImmediate({optional:!0});l?a(l):(D("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new ze)}},0),o()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(r=>this.i!==e?(D("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):r?(B(typeof r.accessToken=="string",31837,{l:r}),new ml(r.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(){let e=this.auth&&this.auth.getUid();return B(e===null||typeof e=="string",2055,{h:e}),new Le(e)}},sf=class{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=Le.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);let e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}},of=class{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new sf(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(Le.FIRST_PARTY))}shutdown(){}invalidateToken(){}},yl=class{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}},vl=class{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,Hc(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){B(this.o===void 0,3512);let r=i=>{i.error!=null&&D("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);let o=i.token!==this.m;return this.m=i.token,D("FirebaseAppCheckTokenProvider",`Received ${o?"new":"existing"} token.`),o?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>r(i))};let s=i=>{D("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(i=>s(i)),setTimeout(()=>{if(!this.appCheck){let i=this.V.getImmediate({optional:!0});i?s(i):D("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new yl(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(t=>t?(B(typeof t.token=="string",44558,{tokenResult:t}),this.m=t.token,new yl(t.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}};function e0(n){let e=typeof self<"u"&&(self.crypto||self.msCrypto),t=new Uint8Array(n);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let r=0;re?1:0}function af(n,e){let t=Math.min(n.length,e.length);for(let r=0;r=t0&&e<=n0}function ci(n,e,t){return n.length===e.length&&n.every((r,s)=>t(r,e[s]))}function SE(n){return n+"\0"}var mw="__name__",wl=class n{constructor(e,t,r){t===void 0?t=0:t>e.length&&U(637,{offset:t,range:e.length}),r===void 0?r=e.length-t:r>e.length-t&&U(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return n.comparator(this,e)===0}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof n?e.forEach(r=>{t.push(r)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=e===void 0?1:e,this.construct(this.segments,this.offset+e,this.length-e)}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(e){return this.segments[this.offset+e]}isEmpty(){return this.length===0}isPrefixOf(e){if(e.length=0)throw new N(R.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(s=>s.length>0))}return new n(t)}static emptyPath(){return new n([])}},r0=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Se=class n extends wl{construct(e,t,r){return new n(e,t,r)}static isValidIdentifier(e){return r0.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),n.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===mw}static keyField(){return new n([mw])}static fromServerFormat(e){let t=[],r="",s=0,i=()=>{if(r.length===0)throw new N(R.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""},o=!1;for(;s=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return e!==null&&ie.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return ie.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new n(new ie(e.slice()))}};function Jp(n,e,t){if(!t)throw new N(R.INVALID_ARGUMENT,`Function ${n}() cannot be called with an empty ${e}.`)}function gu(n,e,t,r){if(e===!0&&r===!0)throw new N(R.INVALID_ARGUMENT,`${n} and ${t} cannot be used together.`)}function gw(n){if(!O.isDocumentKey(n))throw new N(R.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${n} has ${n.length}.`)}function _w(n){if(O.isDocumentKey(n))throw new N(R.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${n} has ${n.length}.`)}function RE(n){return typeof n=="object"&&n!==null&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function Sa(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="string")return n.length>20&&(n=`${n.substring(0,20)}...`),JSON.stringify(n);if(typeof n=="number"||typeof n=="boolean")return""+n;if(typeof n=="object"){if(n instanceof Array)return"an array";{let e=(function(r){return r.constructor?r.constructor.name:null})(n);return e?`a custom ${e} object`:"an object"}}return typeof n=="function"?"a function":U(12329,{type:typeof n})}function ae(n,e){if("_delegate"in n&&(n=n._delegate),!(n instanceof e)){if(e.name===n.constructor.name)throw new N(R.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let t=Sa(n);throw new N(R.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return n}function Xp(n,e){if(e<=0)throw new N(R.INVALID_ARGUMENT,`Function ${n}() requires a positive number, but it was: ${e}.`)}function ke(n,e){let t={typeString:n};return e&&(t.value=e),t}function Pi(n,e){if(!RE(n))throw new N(R.INVALID_ARGUMENT,"JSON must be an object");let t;for(let r in e)if(e[r]){let s=e[r].typeString,i="value"in e[r]?{value:e[r].value}:void 0;if(!(r in n)){t=`JSON missing required field: '${r}'`;break}let o=n[r];if(s&&typeof o!==s){t=`JSON field '${r}' must be a ${s}.`;break}if(i!==void 0&&o!==i.value){t=`Expected '${r}' field to equal '${i.value}'`;break}}if(t)throw new N(R.INVALID_ARGUMENT,t);return!0}var yw=-62135596800,vw=1e6,me=class n{static now(){return n.fromMillis(Date.now())}static fromDate(e){return n.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*vw);return new n(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new N(R.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new N(R.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e=253402300800)throw new N(R.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/vw}_compareTo(e){return this.seconds===e.seconds?W(this.nanoseconds,e.nanoseconds):W(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:n._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(Pi(e,n._jsonSchema))return new n(e.seconds,e.nanoseconds)}valueOf(){let e=this.seconds-yw;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};me._jsonSchemaVersion="firestore/timestamp/1.0",me._jsonSchema={type:ke("string",me._jsonSchemaVersion),seconds:ke("number"),nanoseconds:ke("number")};var j=class n{static fromTimestamp(e){return new n(e)}static min(){return new n(new me(0,0))}static max(){return new n(new me(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}};var li=-1,fs=class{constructor(e,t,r,s){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=s}};function cf(n){return n.fields.find(e=>e.kind===2)}function es(n){return n.fields.filter(e=>e.kind!==2)}fs.UNKNOWN_ID=-1;var cs=class{constructor(e,t){this.fieldPath=e,this.kind=t}};var ui=class n{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new n(0,Vt.min())}};function PE(n,e){let t=n.toTimestamp().seconds,r=n.toTimestamp().nanoseconds+1,s=j.fromTimestamp(r===1e9?new me(t+1,0):new me(t,r));return new Vt(s,O.empty(),e)}function xE(n){return new Vt(n.readTime,n.key,li)}var Vt=class n{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new n(j.min(),O.empty(),li)}static max(){return new n(j.max(),O.empty(),li)}};function Zp(n,e){let t=n.readTime.compareTo(e.readTime);return t!==0?t:(t=O.comparator(n.documentKey,e.documentKey),t!==0?t:W(n.largestBatchId,e.largestBatchId))}var kE="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",El=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};async function Ir(n){if(n.code!==R.FAILED_PRECONDITION||n.message!==kE)throw n;D("LocalStore","Unexpectedly lost primary lease")}var C=class n{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&U(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new n((r,s)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(r,s)},this.catchCallback=i=>{this.wrapFailure(t,i).next(r,s)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof n?t:n.resolve(t)}catch(t){return n.reject(t)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):n.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):n.reject(t)}static resolve(e){return new n((t,r)=>{t(e)})}static reject(e){return new n((t,r)=>{r(e)})}static waitFor(e){return new n((t,r)=>{let s=0,i=0,o=!1;e.forEach(a=>{++s,a.next(()=>{++i,o&&i===s&&t()},l=>r(l))}),o=!0,i===s&&t()})}static or(e){let t=n.resolve(!1);for(let r of e)t=t.next(s=>s?n.resolve(s):r());return t}static forEach(e,t){let r=[];return e.forEach((s,i)=>{r.push(t.call(this,s,i))}),this.waitFor(r)}static mapArray(e,t){return new n((r,s)=>{let i=e.length,o=new Array(i),a=0;for(let l=0;l{o[u]=d,++a,a===i&&r(o)},d=>s(d))}})}static doWhile(e,t){return new n((r,s)=>{let i=()=>{e()===!0?t().next(()=>{i()},s):r()};i()})}};var bt="SimpleDb",Tl=class n{static open(e,t,r,s){try{return new n(t,e.transaction(s,r))}catch(i){throw new ls(t,i)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.S=new ze,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{t.error?this.S.reject(new ls(e,t.error)):this.S.resolve()},this.transaction.onerror=r=>{let s=em(r.target.error);this.S.reject(new ls(e,s))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(D(bt,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}C(){let e=this.transaction;this.aborted||typeof e.commit!="function"||e.commit()}store(e){let t=this.transaction.objectStore(e);return new uf(t)}},hr=class n{static delete(e){return D(bt,"Removing database:",e),ns(Rd().indexedDB.deleteDatabase(e)).toPromise()}static v(){if(!Gc())return!1;if(n.F())return!0;let e=So(),t=n.M(e),r=00||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||r||i)}static F(){return typeof process<"u"&&process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE==="YES"}static O(e,t){return e.store(t)}static M(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),r=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(r)}constructor(e,t,r){this.name=e,this.version=t,this.N=r,this.B=null,n.M(So())===12.2&&xe("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async L(e){return this.db||(D(bt,"Opening database:",this.name),this.db=await new Promise((t,r)=>{let s=indexedDB.open(this.name,this.version);s.onsuccess=i=>{let o=i.target.result;t(o)},s.onblocked=()=>{r(new ls(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=i=>{let o=i.target.error;o.name==="VersionError"?r(new N(R.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.")):o.name==="InvalidStateError"?r(new N(R.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: "+o)):r(new ls(e,o))},s.onupgradeneeded=i=>{D(bt,'Database "'+this.name+'" requires upgrade from version:',i.oldVersion);let o=i.target.result;this.N.k(o,s.transaction,i.oldVersion,this.version).next(()=>{D(bt,"Database upgrade to version "+this.version+" complete")})}})),this.K&&(this.db.onversionchange=t=>this.K(t)),this.db}q(e){this.K=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,r,s){let i=t==="readonly",o=0;for(;;){++o;try{this.db=await this.L(e);let a=Tl.open(this.db,e,i?"readonly":"readwrite",r),l=s(a).next(u=>(a.C(),u)).catch(u=>(a.abort(u),C.reject(u))).toPromise();return l.catch(()=>{}),await a.D,l}catch(a){let l=a,u=l.name!=="FirebaseError"&&o<3;if(D(bt,"Transaction failed with error:",l.message,"Retrying:",u),this.close(),!u)return Promise.reject(l)}}}close(){this.db&&this.db.close(),this.db=void 0}};function NE(n){let e=n.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}var lf=class{constructor(e){this.U=e,this.$=!1,this.W=null}get isDone(){return this.$}get G(){return this.W}set cursor(e){this.U=e}done(){this.$=!0}j(e){this.W=e}delete(){return ns(this.U.delete())}},ls=class extends N{constructor(e,t){super(R.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}};function Ar(n){return n.name==="IndexedDbTransactionError"}var uf=class{constructor(e){this.store=e}put(e,t){let r;return t!==void 0?(D(bt,"PUT",this.store.name,e,t),r=this.store.put(t,e)):(D(bt,"PUT",this.store.name,"",e),r=this.store.put(e)),ns(r)}add(e){return D(bt,"ADD",this.store.name,e,e),ns(this.store.add(e))}get(e){return ns(this.store.get(e)).next(t=>(t===void 0&&(t=null),D(bt,"GET",this.store.name,e,t),t))}delete(e){return D(bt,"DELETE",this.store.name,e),ns(this.store.delete(e))}count(){return D(bt,"COUNT",this.store.name),ns(this.store.count())}J(e,t){let r=this.options(e,t),s=r.index?this.store.index(r.index):this.store;if(typeof s.getAll=="function"){let i=s.getAll(r.range);return new C((o,a)=>{i.onerror=l=>{a(l.target.error)},i.onsuccess=l=>{o(l.target.result)}})}{let i=this.cursor(r),o=[];return this.H(i,(a,l)=>{o.push(l)}).next(()=>o)}}Z(e,t){let r=this.store.getAll(e,t===null?void 0:t);return new C((s,i)=>{r.onerror=o=>{i(o.target.error)},r.onsuccess=o=>{s(o.target.result)}})}X(e,t){D(bt,"DELETE ALL",this.store.name);let r=this.options(e,t);r.Y=!1;let s=this.cursor(r);return this.H(s,(i,o,a)=>a.delete())}ee(e,t){let r;t?r=e:(r={},t=e);let s=this.cursor(r);return this.H(s,t)}te(e){let t=this.cursor({});return new C((r,s)=>{t.onerror=i=>{let o=em(i.target.error);s(o)},t.onsuccess=i=>{let o=i.target.result;o?e(o.primaryKey,o.value).next(a=>{a?o.continue():r()}):r()}})}H(e,t){let r=[];return new C((s,i)=>{e.onerror=o=>{i(o.target.error)},e.onsuccess=o=>{let a=o.target.result;if(!a)return void s();let l=new lf(a),u=t(a.primaryKey,a.value,l);if(u instanceof C){let d=u.catch(p=>(l.done(),C.reject(p)));r.push(d)}l.isDone?s():l.G===null?a.continue():a.continue(l.G)}}).next(()=>C.waitFor(r))}options(e,t){let r;return e!==void 0&&(typeof e=="string"?r=e:t=e),{index:r,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){let r=this.store.index(e.index);return e.Y?r.openKeyCursor(e.range,t):r.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}};function ns(n){return new C((e,t)=>{n.onsuccess=r=>{let s=r.target.result;e(s)},n.onerror=r=>{let s=em(r.target.error);t(s)}})}var ww=!1;function em(n){let e=hr.M(So());if(e>=12.2&&e<13){let t="An internal error was encountered in the Indexed Database server";if(n.message.indexOf(t)>=0){let r=new N("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return ww||(ww=!0,setTimeout(()=>{throw r},0)),r}}return n}var Qo="IndexBackfiller",hf=class{constructor(e,t){this.asyncQueue=e,this.ne=t,this.task=null}start(){this.re(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return this.task!==null}re(e){D(Qo,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let t=await this.ne.ie();D(Qo,`Documents written: ${t}`)}catch(t){Ar(t)?D(Qo,"Ignoring IndexedDB error during index backfill: ",t):await Ir(t)}await this.re(6e4)})}},df=class{constructor(e,t){this.localStore=e,this.persistence=t}async ie(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.se(t,e))}se(e,t){let r=new Set,s=t,i=!0;return C.doWhile(()=>i===!0&&s>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(o=>{if(o!==null&&!r.has(o))return D(Qo,`Processing collection: ${o}`),this.oe(e,o,s).next(a=>{s-=a,r.add(o)});i=!1})).next(()=>t-s)}oe(e,t,r){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(s=>this.localStore.localDocuments.getNextDocuments(e,t,s,r).next(i=>{let o=i.changes;return this.localStore.indexManager.updateIndexEntries(e,o).next(()=>this._e(s,i)).next(a=>(D(Qo,`Updating offset: ${a}`),this.localStore.indexManager.updateCollectionGroup(e,t,a))).next(()=>o.size)}))}_e(e,t){let r=e;return t.changes.forEach((s,i)=>{let o=xE(i);Zp(o,r)>0&&(r=o)}),new Vt(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}};var Ct=(()=>{class n{constructor(t,r){this.previousValue=t,r&&(r.sequenceNumberHandler=s=>this.ae(s),this.ue=s=>r.writeSequenceNumber(s))}ae(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){let t=++this.previousValue;return this.ue&&this.ue(t),t}}n.ce=-1;return n})(),lr=-1;function Ra(n){return n==null}function ra(n){return n===0&&1/n==-1/0}function DE(n){return typeof n=="number"&&Number.isInteger(n)&&!ra(n)&&n<=Number.MAX_SAFE_INTEGER&&n>=Number.MIN_SAFE_INTEGER}var Il="";function rt(n){let e="";for(let t=0;t0&&(e=Ew(e)),e=s0(n.get(t),e);return Ew(e)}function s0(n,e){let t=e,r=n.length;for(let s=0;s=2,64408,{path:n}),e===2)return B(n.charAt(0)===Il&&n.charAt(1)==="",56145,{path:n}),ie.emptyPath();let t=e-2,r=[],s="";for(let i=0;it)&&U(50515,{path:n}),n.charAt(o+1)){case"":let a=n.substring(i,o),l;s.length===0?l=a:(s+=a,l=s,s=""),r.push(l);break;case"":s+=n.substring(i,o),s+="\0";break;case"":s+=n.substring(i,o+1);break;default:U(61167,{path:n})}i=o+2}return new ie(r)}var ts="remoteDocuments",Pa="owner",Qs="owner",sa="mutationQueues",i0="userId",jt="mutations",Tw="batchId",os="userMutationsIndex",Iw=["userId","batchId"];function al(n,e){return[n,rt(e)]}function VE(n,e,t){return[n,rt(e),t]}var o0={},hi="documentMutations",Al="remoteDocumentsV14",a0=["prefixPath","collectionGroup","readTime","documentId"],cl="documentKeyIndex",c0=["prefixPath","collectionGroup","documentId"],OE="collectionGroupIndex",l0=["collectionGroup","readTime","prefixPath","documentId"],ia="remoteDocumentGlobal",ff="remoteDocumentGlobalKey",di="targets",ME="queryTargetsIndex",u0=["canonicalId","targetId"],fi="targetDocuments",h0=["targetId","path"],tm="documentTargetsIndex",d0=["path","targetId"],bl="targetGlobalKey",us="targetGlobal",oa="collectionParents",f0=["collectionId","parent"],pi="clientMetadata",p0="clientId",_u="bundles",m0="bundleId",yu="namedQueries",g0="name",nm="indexConfiguration",_0="indexId",pf="collectionGroupIndex",y0="collectionGroup",Yo="indexState",v0=["indexId","uid"],FE="sequenceNumberIndex",w0=["uid","sequenceNumber"],Jo="indexEntries",E0=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],LE="documentKeyIndex",T0=["indexId","uid","orderedDocumentKey"],vu="documentOverlays",I0=["userId","collectionPath","documentId"],mf="collectionPathOverlayIndex",A0=["userId","collectionPath","largestBatchId"],UE="collectionGroupOverlayIndex",b0=["userId","collectionGroup","largestBatchId"],rm="globals",C0="name",BE=[sa,jt,hi,ts,di,Pa,us,fi,pi,ia,oa,_u,yu],S0=[...BE,vu],qE=[sa,jt,hi,Al,di,Pa,us,fi,pi,ia,oa,_u,yu,vu],jE=qE,sm=[...jE,nm,Yo,Jo],R0=sm,GE=[...sm,rm],P0=GE;var aa=class extends El{constructor(e,t){super(),this.le=e,this.currentSequenceNumber=t}};function We(n,e){let t=F(n);return hr.O(t.le,e)}function Aw(n){let e=0;for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}function br(n,e){for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&e(t,n[t])}function zE(n){for(let e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}var ye=class n{constructor(e,t){this.comparator=e,this.root=t||un.EMPTY}insert(e,t){return new n(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,un.BLACK,null,null))}remove(e){return new n(this.comparator,this.root.remove(e,this.comparator).copy(null,null,un.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let r=this.comparator(e,t.key);if(r===0)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){let s=this.comparator(e,r.key);if(s===0)return t+r.left.size;s<0?r=r.left:(t+=r.left.size+1,r=r.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(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,r)=>(e(t,r),!1))}toString(){let e=[];return this.inorderTraversal((t,r)=>(e.push(`${t}:${r}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new oi(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new oi(this.root,e,this.comparator,!1)}getReverseIterator(){return new oi(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new oi(this.root,e,this.comparator,!0)}},oi=class{constructor(e,t,r,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&s&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(i===0){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}},un=class n{constructor(e,t,r,s,i){this.key=e,this.value=t,this.color=r??n.RED,this.left=s??n.EMPTY,this.right=i??n.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,s,i){return new n(e??this.key,t??this.value,r??this.color,s??this.left,i??this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}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(e,t,r){let s=this,i=r(e,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(e,t,r),null):i===0?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,r)),s.fixUp()}removeMin(){if(this.left.isEmpty())return n.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let r,s=this;if(t(e,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(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),t(e,s.key)===0){if(s.right.isEmpty())return n.EMPTY;r=s.right.min(),s=s.copy(r.key,r.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){let e=this.copy(null,null,n.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,n.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){let e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw U(43730,{key:this.key,value:this.value});if(this.right.isRed())throw U(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw U(27949);return e+(this.isRed()?0:1)}};un.EMPTY=null,un.RED=!0,un.BLACK=!1;un.EMPTY=new class{constructor(){this.size=0}get key(){throw U(57766)}get value(){throw U(16141)}get color(){throw U(16727)}get left(){throw U(29726)}get right(){throw U(36894)}copy(e,t,r,s,i){return this}insert(e,t,r){return new un(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};var fe=class n{constructor(e){this.comparator=e,this.data=new ye(this.comparator)}has(e){return this.data.get(e)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,r)=>(e(t),!1))}forEachInRange(e,t){let r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){let s=r.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let r;for(r=t!==void 0?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Cl(this.data.getIterator())}getIteratorFrom(e){return new Cl(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(r)}),t}isEqual(e){if(!(e instanceof n)||this.size!==e.size)return!1;let t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=r.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new n(this.comparator);return t.data=e,t}},Cl=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};function Ys(n){return n.hasNext()?n.getNext():void 0}var St=class n{constructor(e){this.fields=e,e.sort(Se.comparator)}static empty(){return new n([])}unionWith(e){let t=new fe(Se.comparator);for(let r of this.fields)t=t.add(r);for(let r of e)t=t.add(r);return new n(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return ci(this.fields,e.fields,(t,r)=>t.isEqual(r))}};var Sl=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};function im(){return typeof atob<"u"}var Re=class n{constructor(e){this.binaryString=e}static fromBase64String(e){let t=(function(s){try{return atob(s)}catch(i){throw typeof DOMException<"u"&&i instanceof DOMException?new Sl("Invalid base64 string: "+i):i}})(e);return new n(t)}static fromUint8Array(e){let t=(function(s){let i="";for(let o=0;oefn(t,e))!==void 0}function fr(n,e){if(n===e)return 0;let t=dr(n),r=dr(e);if(t!==r)return W(t,r);switch(t){case 0:case 9007199254740991:return 0;case 1:return W(n.booleanValue,e.booleanValue);case 2:return(function(i,o){let a=Te(i.integerValue||i.doubleValue),l=Te(o.integerValue||o.doubleValue);return al?1:a===l?0:isNaN(a)?isNaN(l)?0:-1:1})(n,e);case 3:return bw(n.timestampValue,e.timestampValue);case 4:return bw(ca(n),ca(e));case 5:return af(n.stringValue,e.stringValue);case 6:return(function(i,o){let a=Nn(i),l=Nn(o);return a.compareTo(l)})(n.bytesValue,e.bytesValue);case 7:return(function(i,o){let a=i.split("/"),l=o.split("/");for(let u=0;us+ul(i),0)})(n.arrayValue);case 10:case 11:return(function(r){let s=0;return br(r.fields,(i,o)=>{s+=i.length+ul(o)}),s})(n.mapValue);default:throw U(13486,{value:n})}}function Cr(n,e){return{referenceValue:`projects/${n.projectId}/databases/${n.database}/documents/${e.path.canonicalString()}`}}function vf(n){return!!n&&"integerValue"in n}function ua(n){return!!n&&"arrayValue"in n}function Sw(n){return!!n&&"nullValue"in n}function Rw(n){return!!n&&"doubleValue"in n&&isNaN(Number(n.doubleValue))}function hl(n){return!!n&&"mapValue"in n}function Eu(n){return(n?.mapValue?.fields||{})[om]?.stringValue===am}function Xo(n){if(n.geoPointValue)return{geoPointValue:Q({},n.geoPointValue)};if(n.timestampValue&&typeof n.timestampValue=="object")return{timestampValue:Q({},n.timestampValue)};if(n.mapValue){let e={mapValue:{fields:{}}};return br(n.mapValue.fields,(t,r)=>e.mapValue.fields[t]=Xo(r)),e}if(n.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(n.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Xo(n.arrayValue.values[t]);return e}return Q({},n)}function JE(n){return(((n.mapValue||{}).fields||{}).__type__||{}).stringValue===YE}var XE={mapValue:{fields:{[om]:{stringValue:am},[mi]:{arrayValue:{}}}}};function k0(n){return"nullValue"in n?ll:"booleanValue"in n?{booleanValue:!1}:"integerValue"in n||"doubleValue"in n?{doubleValue:NaN}:"timestampValue"in n?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in n?{stringValue:""}:"bytesValue"in n?{bytesValue:""}:"referenceValue"in n?Cr(Dn.empty(),O.empty()):"geoPointValue"in n?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in n?{arrayValue:{}}:"mapValue"in n?Eu(n)?XE:{mapValue:{}}:U(35942,{value:n})}function N0(n){return"nullValue"in n?{booleanValue:!1}:"booleanValue"in n?{doubleValue:NaN}:"integerValue"in n||"doubleValue"in n?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in n?{stringValue:""}:"stringValue"in n?{bytesValue:""}:"bytesValue"in n?Cr(Dn.empty(),O.empty()):"referenceValue"in n?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in n?{arrayValue:{}}:"arrayValue"in n?XE:"mapValue"in n?Eu(n)?{mapValue:{}}:cr:U(61959,{value:n})}function Pw(n,e){let t=fr(n.value,e.value);return t!==0?t:n.inclusive&&!e.inclusive?-1:!n.inclusive&&e.inclusive?1:0}function xw(n,e){let t=fr(n.value,e.value);return t!==0?t:n.inclusive&&!e.inclusive?1:!n.inclusive&&e.inclusive?-1:0}var Ze=class n{constructor(e){this.value=e}static empty(){return new n({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r{if(!t.isImmediateParentOf(a)){let l=this.getFieldsMap(t);this.applyChanges(l,r,s),r={},s=[],t=a.popLast()}o?r[a.lastSegment()]=Xo(o):s.push(a.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,r,s)}delete(e){let t=this.field(e.popLast());hl(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return fn(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;re[s]=i);for(let s of r)delete e[s]}clone(){return new n(Xo(this.value))}};function ZE(n){let e=[];return br(n.fields,(t,r)=>{let s=new Se([t]);if(hl(r)){let i=ZE(r.mapValue).fields;if(i.length===0)e.push(s);else for(let o of i)e.push(s.child(o))}else e.push(s)}),new St(e)}var Ue=class n{constructor(e,t,r,s,i,o,a){this.key=e,this.documentType=t,this.version=r,this.readTime=s,this.createTime=i,this.data=o,this.documentState=a}static newInvalidDocument(e){return new n(e,0,j.min(),j.min(),j.min(),Ze.empty(),0)}static newFoundDocument(e,t,r,s){return new n(e,1,t,j.min(),r,s,0)}static newNoDocument(e,t){return new n(e,2,t,j.min(),j.min(),Ze.empty(),0)}static newUnknownDocument(e,t){return new n(e,3,t,j.min(),j.min(),Ze.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(j.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Ze.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ze.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=j.min(),this}setReadTime(e){return this.readTime=e,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(e){return e instanceof n&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new n(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}})`}};var Kt=class{constructor(e,t){this.position=e,this.inclusive=t}};function kw(n,e,t){let r=0;for(let s=0;s":return e>0;case">=":return e>=0;default:return U(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},de=class n extends Rl{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new n(e,t)}matches(e){return _i(this)?this.filters.find(t=>!t.matches(e))===void 0:this.filters.find(t=>t.matches(e))!==void 0}getFlattenedFilters(){return this.Pe!==null||(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}};function _i(n){return n.op==="and"}function wf(n){return n.op==="or"}function cm(n){return eT(n)&&_i(n)}function eT(n){for(let e of n.filters)if(e instanceof de)return!1;return!0}function Ef(n){if(n instanceof re)return n.field.canonicalString()+n.op.toString()+gi(n.value);if(cm(n))return n.filters.map(e=>Ef(e)).join(",");{let e=n.filters.map(t=>Ef(t)).join(",");return`${n.op}(${e})`}}function tT(n,e){return n instanceof re?(function(r,s){return s instanceof re&&r.op===s.op&&r.field.isEqual(s.field)&&fn(r.value,s.value)})(n,e):n instanceof de?(function(r,s){return s instanceof de&&r.op===s.op&&r.filters.length===s.filters.length?r.filters.reduce((i,o,a)=>i&&tT(o,s.filters[a]),!0):!1})(n,e):void U(19439)}function nT(n,e){let t=n.filters.concat(e);return de.create(t,n.op)}function rT(n){return n instanceof re?(function(t){return`${t.field.canonicalString()} ${t.op} ${gi(t.value)}`})(n):n instanceof de?(function(t){return t.op.toString()+" {"+t.getFilters().map(rT).join(" ,")+"}"})(n):"Filter"}var Tf=class extends re{constructor(e,t,r){super(e,t,r),this.key=O.fromName(r.referenceValue)}matches(e){let t=O.comparator(e.key,this.key);return this.matchesComparison(t)}},If=class extends re{constructor(e,t){super(e,"in",t),this.keys=sT("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}},Af=class extends re{constructor(e,t){super(e,"not-in",t),this.keys=sT("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}};function sT(n,e){return(e.arrayValue?.values||[]).map(t=>O.fromName(t.referenceValue))}var bf=class extends re{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return ua(t)&&la(t.arrayValue,this.value)}},Pl=class extends re{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&la(this.value.arrayValue,t)}},Cf=class extends re{constructor(e,t){super(e,"not-in",t)}matches(e){if(la(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&t.nullValue===void 0&&!la(this.value.arrayValue,t)}},Sf=class extends re{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!ua(t)||!t.arrayValue.values)&&t.arrayValue.values.some(r=>la(this.value.arrayValue,r))}};var Rf=class{constructor(e,t=null,r=[],s=[],i=null,o=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=s,this.limit=i,this.startAt=o,this.endAt=a,this.Te=null}};function Pf(n,e=null,t=[],r=[],s=null,i=null,o=null){return new Rf(n,e,t,r,s,i,o)}function ps(n){let e=F(n);if(e.Te===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(r=>Ef(r)).join(","),t+="|ob:",t+=e.orderBy.map(r=>(function(i){return i.field.canonicalString()+i.dir})(r)).join(","),Ra(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(r=>gi(r)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(r=>gi(r)).join(",")),e.Te=t}return e.Te}function ka(n,e){if(n.limit!==e.limit||n.orderBy.length!==e.orderBy.length)return!1;for(let t=0;tt instanceof re&&t.field.isEqual(e))}function Dw(n,e,t){let r=ll,s=!0;for(let i of kl(n,e)){let o=ll,a=!0;switch(i.op){case"<":case"<=":o=k0(i.value);break;case"==":case"in":case">=":o=i.value;break;case">":o=i.value,a=!1;break;case"!=":case"not-in":o=ll}Pw({value:r,inclusive:s},{value:o,inclusive:a})<0&&(r=o,s=a)}if(t!==null){for(let i=0;i=":case">":o=N0(i.value),a=!1;break;case"==":case"in":case"<=":o=i.value;break;case"<":o=i.value,a=!1;break;case"!=":case"not-in":o=cr}xw({value:r,inclusive:s},{value:o,inclusive:a})>0&&(r=o,s=a)}if(t!==null){for(let i=0;i0&&(r=o,s=t.inclusive);break}}return{value:r,inclusive:s}}var Wt=class{constructor(e,t=null,r=[],s=[],i=null,o="F",a=null,l=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=s,this.limit=i,this.limitType=o,this.startAt=a,this.endAt=l,this.Ie=null,this.Ee=null,this.Re=null,this.startAt,this.endAt}};function iT(n,e,t,r,s,i,o,a){return new Wt(n,e,t,r,s,i,o,a)}function Es(n){return new Wt(n)}function Ow(n){return n.filters.length===0&&n.limit===null&&n.startAt==null&&n.endAt==null&&(n.explicitOrderBy.length===0||n.explicitOrderBy.length===1&&n.explicitOrderBy[0].field.isKeyField())}function V0(n){return O.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}function Tu(n){return n.collectionGroup!==null}function hs(n){let e=F(n);if(e.Ie===null){e.Ie=[];let t=new Set;for(let i of e.explicitOrderBy)e.Ie.push(i),t.add(i.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(o){let a=new fe(Se.comparator);return o.filters.forEach(l=>{l.getFlattenedFilters().forEach(u=>{u.isInequality()&&(a=a.add(u.field))})}),a})(e).forEach(i=>{t.has(i.canonicalString())||i.isKeyField()||e.Ie.push(new pr(i,r))}),t.has(Se.keyField().canonicalString())||e.Ie.push(new pr(Se.keyField(),r))}return e.Ie}function ct(n){let e=F(n);return e.Ee||(e.Ee=O0(e,hs(n))),e.Ee}function O0(n,e){if(n.limitType==="F")return Pf(n.path,n.collectionGroup,e,n.filters,n.limit,n.startAt,n.endAt);{e=e.map(s=>{let i=s.dir==="desc"?"asc":"desc";return new pr(s.field,i)});let t=n.endAt?new Kt(n.endAt.position,n.endAt.inclusive):null,r=n.startAt?new Kt(n.startAt.position,n.startAt.inclusive):null;return Pf(n.path,n.collectionGroup,e,n.filters,n.limit,t,r)}}function Iu(n,e){let t=n.filters.concat([e]);return new Wt(n.path,n.collectionGroup,n.explicitOrderBy.slice(),t,n.limit,n.limitType,n.startAt,n.endAt)}function oT(n,e){let t=n.explicitOrderBy.concat([e]);return new Wt(n.path,n.collectionGroup,t,n.filters.slice(),n.limit,n.limitType,n.startAt,n.endAt)}function ha(n,e,t){return new Wt(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),e,t,n.startAt,n.endAt)}function aT(n,e){return new Wt(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),n.limit,n.limitType,e,n.endAt)}function cT(n,e){return new Wt(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),n.limit,n.limitType,n.startAt,e)}function Na(n,e){return ka(ct(n),ct(e))&&n.limitType===e.limitType}function lT(n){return`${ps(ct(n))}|lt:${n.limitType}`}function ni(n){return`Query(target=${(function(t){let r=t.path.canonicalString();return t.collectionGroup!==null&&(r+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(r+=`, filters: [${t.filters.map(s=>rT(s)).join(", ")}]`),Ra(t.limit)||(r+=", limit: "+t.limit),t.orderBy.length>0&&(r+=`, orderBy: [${t.orderBy.map(s=>(function(o){return`${o.field.canonicalString()} (${o.dir})`})(s)).join(", ")}]`),t.startAt&&(r+=", startAt: ",r+=t.startAt.inclusive?"b:":"a:",r+=t.startAt.position.map(s=>gi(s)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(s=>gi(s)).join(",")),`Target(${r})`})(ct(n))}; limitType=${n.limitType})`}function Da(n,e){return e.isFoundDocument()&&(function(r,s){let i=s.key.path;return r.collectionGroup!==null?s.key.hasCollectionId(r.collectionGroup)&&r.path.isPrefixOf(i):O.isDocumentKey(r.path)?r.path.isEqual(i):r.path.isImmediateParentOf(i)})(n,e)&&(function(r,s){for(let i of hs(r))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0})(n,e)&&(function(r,s){for(let i of r.filters)if(!i.matches(s))return!1;return!0})(n,e)&&(function(r,s){return!(r.startAt&&!(function(o,a,l){let u=kw(o,a,l);return o.inclusive?u<=0:u<0})(r.startAt,hs(r),s)||r.endAt&&!(function(o,a,l){let u=kw(o,a,l);return o.inclusive?u>=0:u>0})(r.endAt,hs(r),s))})(n,e)}function uT(n){return n.collectionGroup||(n.path.length%2==1?n.path.lastSegment():n.path.get(n.path.length-2))}function hT(n){return(e,t)=>{let r=!1;for(let s of hs(n)){let i=M0(s,e,t);if(i!==0)return i;r=r||s.field.isKeyField()}return 0}}function M0(n,e,t){let r=n.field.isKeyField()?O.comparator(e.key,t.key):(function(i,o,a){let l=o.data.field(i),u=a.data.field(i);return l!==null&&u!==null?fr(l,u):U(42886)})(n.field,e,t);switch(n.dir){case"asc":return r;case"desc":return-1*r;default:return U(19790,{direction:n.dir})}}var $t=class{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),r=this.inner[t];if(r!==void 0){for(let[s,i]of r)if(this.equalsFn(s,e))return i}}has(e){return this.get(e)!==void 0}set(e,t){let r=this.mapKeyFn(e),s=this.inner[r];if(s===void 0)return this.inner[r]=[[e,t]],void this.innerSize++;for(let i=0;i{for(let[s,i]of r)e(s,i)})}isEmpty(){return zE(this.inner)}size(){return this.innerSize}};var F0=new ye(O.comparator);function yt(){return F0}var dT=new ye(O.comparator);function $o(...n){let e=dT;for(let t of n)e=e.insert(t.key,t);return e}function fT(n){let e=dT;return n.forEach((t,r)=>e=e.insert(t,r.overlayedDocument)),e}function ln(){return Zo()}function pT(){return Zo()}function Zo(){return new $t(n=>n.toString(),(n,e)=>n.isEqual(e))}var L0=new ye(O.comparator),U0=new fe(O.comparator);function $(...n){let e=U0;for(let t of n)e=e.add(t);return e}var B0=new fe(W);function lm(){return B0}function um(n,e){if(n.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:ra(e)?"-0":e}}function mT(n){return{integerValue:""+n}}function gT(n,e){return DE(e)?mT(e):um(n,e)}var yi=class{constructor(){this._=void 0}};function q0(n,e,t){return n instanceof mr?(function(s,i){let o={fields:{[WE]:{stringValue:KE},[HE]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&xa(i)&&(i=wu(i)),i&&(o.fields[$E]=i),{mapValue:o}})(t,e):n instanceof Vn?yT(n,e):n instanceof On?vT(n,e):(function(s,i){let o=_T(s,i),a=Mw(o)+Mw(s.Ae);return vf(o)&&vf(s.Ae)?mT(a):um(s.serializer,a)})(n,e)}function j0(n,e,t){return n instanceof Vn?yT(n,e):n instanceof On?vT(n,e):t}function _T(n,e){return n instanceof gr?(function(r){return vf(r)||(function(i){return!!i&&"doubleValue"in i})(r)})(e)?e:{integerValue:0}:null}var mr=class extends yi{},Vn=class extends yi{constructor(e){super(),this.elements=e}};function yT(n,e){let t=wT(e);for(let r of n.elements)t.some(s=>fn(s,r))||t.push(r);return{arrayValue:{values:t}}}var On=class extends yi{constructor(e){super(),this.elements=e}};function vT(n,e){let t=wT(e);for(let r of n.elements)t=t.filter(s=>!fn(s,r));return{arrayValue:{values:t}}}var gr=class extends yi{constructor(e,t){super(),this.serializer=e,this.Ae=t}};function Mw(n){return Te(n.integerValue||n.doubleValue)}function wT(n){return ua(n)&&n.arrayValue.values?n.arrayValue.values.slice():[]}var ms=class{constructor(e,t){this.field=e,this.transform=t}};function G0(n,e){return n.field.isEqual(e.field)&&(function(r,s){return r instanceof Vn&&s instanceof Vn||r instanceof On&&s instanceof On?ci(r.elements,s.elements,fn):r instanceof gr&&s instanceof gr?fn(r.Ae,s.Ae):r instanceof mr&&s instanceof mr})(n.transform,e.transform)}var xf=class{constructor(e,t){this.version=e,this.transformResults=t}},Ae=class n{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new n}static exists(e){return new n(void 0,e)}static updateTime(e){return new n(e)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}};function dl(n,e){return n.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(n.updateTime):n.exists===void 0||n.exists===e.isFoundDocument()}var vi=class{};function ET(n,e){if(!n.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return n.isNoDocument()?new Mn(n.key,Ae.none()):new _r(n.key,n.data,Ae.none());{let t=n.data,r=Ze.empty(),s=new fe(Se.comparator);for(let i of e.fields)if(!s.has(i)){let o=t.field(i);o===null&&i.length>1&&(i=i.popLast(),o=t.field(i)),o===null?r.delete(i):r.set(i,o),s=s.add(i)}return new Ht(n.key,r,new St(s.toArray()),Ae.none())}}function z0(n,e,t){n instanceof _r?(function(s,i,o){let a=s.value.clone(),l=Lw(s.fieldTransforms,i,o.transformResults);a.setAll(l),i.convertToFoundDocument(o.version,a).setHasCommittedMutations()})(n,e,t):n instanceof Ht?(function(s,i,o){if(!dl(s.precondition,i))return void i.convertToUnknownDocument(o.version);let a=Lw(s.fieldTransforms,i,o.transformResults),l=i.data;l.setAll(TT(s)),l.setAll(a),i.convertToFoundDocument(o.version,l).setHasCommittedMutations()})(n,e,t):(function(s,i,o){i.convertToNoDocument(o.version).setHasCommittedMutations()})(0,e,t)}function ea(n,e,t,r){return n instanceof _r?(function(i,o,a,l){if(!dl(i.precondition,o))return a;let u=i.value.clone(),d=Uw(i.fieldTransforms,l,o);return u.setAll(d),o.convertToFoundDocument(o.version,u).setHasLocalMutations(),null})(n,e,t,r):n instanceof Ht?(function(i,o,a,l){if(!dl(i.precondition,o))return a;let u=Uw(i.fieldTransforms,l,o),d=o.data;return d.setAll(TT(i)),d.setAll(u),o.convertToFoundDocument(o.version,d).setHasLocalMutations(),a===null?null:a.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map(p=>p.field))})(n,e,t,r):(function(i,o,a){return dl(i.precondition,o)?(o.convertToNoDocument(o.version).setHasLocalMutations(),null):a})(n,e,t)}function K0(n,e){let t=null;for(let r of n.fieldTransforms){let s=e.data.field(r.field),i=_T(r.transform,s||null);i!=null&&(t===null&&(t=Ze.empty()),t.set(r.field,i))}return t||null}function Fw(n,e){return n.type===e.type&&!!n.key.isEqual(e.key)&&!!n.precondition.isEqual(e.precondition)&&!!(function(r,s){return r===void 0&&s===void 0||!(!r||!s)&&ci(r,s,(i,o)=>G0(i,o))})(n.fieldTransforms,e.fieldTransforms)&&(n.type===0?n.value.isEqual(e.value):n.type!==1||n.data.isEqual(e.data)&&n.fieldMask.isEqual(e.fieldMask))}var _r=class extends vi{constructor(e,t,r,s=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},Ht=class extends vi{constructor(e,t,r,s,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}};function TT(n){let e=new Map;return n.fieldMask.fields.forEach(t=>{if(!t.isEmpty()){let r=n.data.field(t);e.set(t,r)}}),e}function Lw(n,e,t){let r=new Map;B(n.length===t.length,32656,{Ve:t.length,de:n.length});for(let s=0;s{let i=e.get(s.key),o=i.overlayedDocument,a=this.applyToLocalView(o,i.mutatedFields);a=t.has(s.key)?null:a;let l=ET(o,a);l!==null&&r.set(s.key,l),o.isValidDocument()||o.convertToNoDocument(j.min())}),r}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),$())}isEqual(e){return this.batchId===e.batchId&&ci(this.mutations,e.mutations,(t,r)=>Fw(t,r))&&ci(this.baseMutations,e.baseMutations,(t,r)=>Fw(t,r))}},kf=class n{constructor(e,t,r,s){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=s}static from(e,t,r){B(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let s=(function(){return L0})(),i=e.mutations;for(let o=0;o=8)throw new as(`Invalid padding: ${t}`);if(r<0)throw new as(`Invalid hash count: ${r}`);if(e.length>0&&this.hashCount===0)throw new as(`Invalid hash count: ${r}`);if(e.length===0&&t!==0)throw new as(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=Rn.fromNumber(this.ge)}ye(e,t,r){let s=e.add(t.multiply(Rn.fromNumber(r)));return s.compare($0)===1&&(s=new Rn([s.getBits(0),s.getBits(1)],0)),s.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<o.insert(a)),o}insert(e){if(this.ge===0)return;let t=Bw(e),[r,s]=qw(t);for(let i=0;i0&&(this.Oe=!0,this.Me=e)}ke(){let e=$(),t=$(),r=$();return this.Fe.forEach((s,i)=>{switch(i){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:r=r.add(s);break;default:U(38017,{changeType:i})}}),new ma(this.Me,this.xe,e,t,r)}Ke(){this.Oe=!1,this.Fe=jw()}qe(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){this.ve-=1,B(this.ve>=0,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}},Vf=class{constructor(e){this.Ge=e,this.ze=new Map,this.je=yt(),this.Je=nl(),this.He=nl(),this.Ze=new ye(W)}Xe(e){for(let t of e.be)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(let t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,t=>{let r=this.nt(t);switch(e.state){case 0:this.rt(t)&&r.Le(e.resumeToken);break;case 1:r.We(),r.Ne||r.Ke(),r.Le(e.resumeToken);break;case 2:r.We(),r.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(r.Qe(),r.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),r.Le(e.resumeToken));break;default:U(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach((r,s)=>{this.rt(s)&&t(s)})}st(e){let t=e.targetId,r=e.Ce.count,s=this.ot(t);if(s){let i=s.target;if(xl(i))if(r===0){let o=new O(i.path);this.et(t,o,Ue.newNoDocument(o,j.min()))}else B(r===1,20013,{expectedCount:r});else{let o=this._t(t);if(o!==r){let a=this.ut(e),l=a?this.ct(a,e,o):1;if(l!==0){this.it(t);let u=l===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ze=this.Ze.insert(t,u)}W0?.o((function(d,p,m,v,S){let x={localCacheCount:d,existenceFilterCount:p.count,databaseId:m.database,projectId:m.projectId},k=p.unchangedNames;return k&&(x.bloomFilter={applied:S===0,hashCount:k?.hashCount??0,bitmapLength:k?.bits?.bitmap?.length??0,padding:k?.bits?.padding??0,mightContain:q=>v?.mightContain(q)??!1}),x})(o,e.Ce,this.Ge.ht(),a,l))}}}}ut(e){let t=e.Ce.unchangedNames;if(!t||!t.bits)return null;let{bits:{bitmap:r="",padding:s=0},hashCount:i=0}=t,o,a;try{o=Nn(r).toUint8Array()}catch(l){if(l instanceof Sl)return vt("Decoding the base64 bloom filter in existence filter failed ("+l.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw l}try{a=new Df(o,s,i)}catch(l){return vt(l instanceof as?"BloomFilter error: ":"Applying bloom filter failed: ",l),null}return a.ge===0?null:a}ct(e,t,r){return t.Ce.count===r-this.Pt(e,t.targetId)?0:2}Pt(e,t){let r=this.Ge.getRemoteKeysForTarget(t),s=0;return r.forEach(i=>{let o=this.Ge.ht(),a=`projects/${o.projectId}/databases/${o.database}/documents/${i.path.canonicalString()}`;e.mightContain(a)||(this.et(t,i,null),s++)}),s}Tt(e){let t=new Map;this.ze.forEach((i,o)=>{let a=this.ot(o);if(a){if(i.current&&xl(a.target)){let l=new O(a.target.path);this.It(l).has(o)||this.Et(o,l)||this.et(o,l,Ue.newNoDocument(l,e))}i.Be&&(t.set(o,i.ke()),i.Ke())}});let r=$();this.He.forEach((i,o)=>{let a=!0;o.forEachWhile(l=>{let u=this.ot(l);return!u||u.purpose==="TargetPurposeLimboResolution"||(a=!1,!1)}),a&&(r=r.add(i))}),this.je.forEach((i,o)=>o.setReadTime(e));let s=new wi(e,t,this.Ze,this.je,r);return this.je=yt(),this.Je=nl(),this.He=nl(),this.Ze=new ye(W),s}Ye(e,t){if(!this.rt(e))return;let r=this.Et(e,t.key)?2:0;this.nt(e).qe(t.key,r),this.je=this.je.insert(t.key,t),this.Je=this.Je.insert(t.key,this.It(t.key).add(e)),this.He=this.He.insert(t.key,this.Rt(t.key).add(e))}et(e,t,r){if(!this.rt(e))return;let s=this.nt(e);this.Et(e,t)?s.qe(t,1):s.Ue(t),this.He=this.He.insert(t,this.Rt(t).delete(e)),this.He=this.He.insert(t,this.Rt(t).add(e)),r&&(this.je=this.je.insert(t,r))}removeTarget(e){this.ze.delete(e)}_t(e){let t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new Vl,this.ze.set(e,t)),t}Rt(e){let t=this.He.get(e);return t||(t=new fe(W),this.He=this.He.insert(e,t)),t}It(e){let t=this.Je.get(e);return t||(t=new fe(W),this.Je=this.Je.insert(e,t)),t}rt(e){let t=this.ot(e)!==null;return t||D("WatchChangeAggregator","Detected inactive target",e),t}ot(e){let t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new Vl),this.Ge.getRemoteKeysForTarget(e).forEach(t=>{this.et(e,t,null)})}Et(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}};function nl(){return new ye(O.comparator)}function jw(){return new ye(O.comparator)}var H0={asc:"ASCENDING",desc:"DESCENDING"},Q0={"<":"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"},Y0={and:"AND",or:"OR"},Of=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Mf(n,e){return n.useProto3Json||Ra(e)?e:{value:e}}function Ei(n,e){return n.useProto3Json?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function CT(n,e){return n.useProto3Json?e.toBase64():e.toUint8Array()}function J0(n,e){return Ei(n,e.toTimestamp())}function Ne(n){return B(!!n,49232),j.fromTimestamp((function(t){let r=kn(t);return new me(r.seconds,r.nanos)})(n))}function hm(n,e){return Ff(n,e).canonicalString()}function Ff(n,e){let t=(function(s){return new ie(["projects",s.projectId,"databases",s.database])})(n).child("documents");return e===void 0?t:t.child(e)}function ST(n){let e=ie.fromString(n);return B(MT(e),10190,{key:e.toString()}),e}function ga(n,e){return hm(n.databaseId,e.path)}function hn(n,e){let t=ST(e);if(t.get(1)!==n.databaseId.projectId)throw new N(R.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+t.get(1)+" vs "+n.databaseId.projectId);if(t.get(3)!==n.databaseId.database)throw new N(R.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+n.databaseId.database);return new O(xT(t))}function RT(n,e){return hm(n.databaseId,e)}function PT(n){let e=ST(n);return e.length===4?ie.emptyPath():xT(e)}function Lf(n){return new ie(["projects",n.databaseId.projectId,"databases",n.databaseId.database]).canonicalString()}function xT(n){return B(n.length>4&&n.get(4)==="documents",29091,{key:n.toString()}),n.popFirst(5)}function Gw(n,e,t){return{name:ga(n,e),fields:t.value.mapValue.fields}}function dm(n,e,t){let r=hn(n,e.name),s=Ne(e.updateTime),i=e.createTime?Ne(e.createTime):j.min(),o=new Ze({mapValue:{fields:e.fields}}),a=Ue.newFoundDocument(r,s,i,o);return t&&a.setHasCommittedMutations(),t?a.setHasCommittedMutations():a}function X0(n,e){return"found"in e?(function(r,s){B(!!s.found,43571),s.found.name,s.found.updateTime;let i=hn(r,s.found.name),o=Ne(s.found.updateTime),a=s.found.createTime?Ne(s.found.createTime):j.min(),l=new Ze({mapValue:{fields:s.found.fields}});return Ue.newFoundDocument(i,o,a,l)})(n,e):"missing"in e?(function(r,s){B(!!s.missing,3894),B(!!s.readTime,22933);let i=hn(r,s.missing),o=Ne(s.readTime);return Ue.newNoDocument(i,o)})(n,e):U(7234,{result:e})}function Z0(n,e){let t;if("targetChange"in e){e.targetChange;let r=(function(u){return u==="NO_CHANGE"?0:u==="ADD"?1:u==="REMOVE"?2:u==="CURRENT"?3:u==="RESET"?4:U(39313,{state:u})})(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=(function(u,d){return u.useProto3Json?(B(d===void 0||typeof d=="string",58123),Re.fromBase64String(d||"")):(B(d===void 0||d instanceof Buffer||d instanceof Uint8Array,16193),Re.fromUint8Array(d||new Uint8Array))})(n,e.targetChange.resumeToken),o=e.targetChange.cause,a=o&&(function(u){let d=u.code===void 0?R.UNKNOWN:AT(u.code);return new N(d,u.message||"")})(o);t=new Dl(r,s,i,a||null)}else if("documentChange"in e){e.documentChange;let r=e.documentChange;r.document,r.document.name,r.document.updateTime;let s=hn(n,r.document.name),i=Ne(r.document.updateTime),o=r.document.createTime?Ne(r.document.createTime):j.min(),a=new Ze({mapValue:{fields:r.document.fields}}),l=Ue.newFoundDocument(s,i,o,a),u=r.targetIds||[],d=r.removedTargetIds||[];t=new ai(u,d,l.key,l)}else if("documentDelete"in e){e.documentDelete;let r=e.documentDelete;r.document;let s=hn(n,r.document),i=r.readTime?Ne(r.readTime):j.min(),o=Ue.newNoDocument(s,i),a=r.removedTargetIds||[];t=new ai([],a,o.key,o)}else if("documentRemove"in e){e.documentRemove;let r=e.documentRemove;r.document;let s=hn(n,r.document),i=r.removedTargetIds||[];t=new ai([],i,s,null)}else{if(!("filter"in e))return U(11601,{Vt:e});{e.filter;let r=e.filter;r.targetId;let{count:s=0,unchangedNames:i}=r,o=new Nf(s,i),a=r.targetId;t=new Nl(a,o)}}return t}function _a(n,e){let t;if(e instanceof _r)t={update:Gw(n,e.key,e.value)};else if(e instanceof Mn)t={delete:ga(n,e.key)};else if(e instanceof Ht)t={update:Gw(n,e.key,e.data),updateMask:iR(e.fieldMask)};else{if(!(e instanceof da))return U(16599,{dt:e.type});t={verify:ga(n,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(r=>(function(i,o){let a=o.transform;if(a instanceof mr)return{fieldPath:o.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(a instanceof Vn)return{fieldPath:o.field.canonicalString(),appendMissingElements:{values:a.elements}};if(a instanceof On)return{fieldPath:o.field.canonicalString(),removeAllFromArray:{values:a.elements}};if(a instanceof gr)return{fieldPath:o.field.canonicalString(),increment:a.Ae};throw U(20930,{transform:o.transform})})(0,r))),e.precondition.isNone||(t.currentDocument=(function(s,i){return i.updateTime!==void 0?{updateTime:J0(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:U(27497)})(n,e.precondition)),t}function Uf(n,e){let t=e.currentDocument?(function(i){return i.updateTime!==void 0?Ae.updateTime(Ne(i.updateTime)):i.exists!==void 0?Ae.exists(i.exists):Ae.none()})(e.currentDocument):Ae.none(),r=e.updateTransforms?e.updateTransforms.map(s=>(function(o,a){let l=null;if("setToServerValue"in a)B(a.setToServerValue==="REQUEST_TIME",16630,{proto:a}),l=new mr;else if("appendMissingElements"in a){let d=a.appendMissingElements.values||[];l=new Vn(d)}else if("removeAllFromArray"in a){let d=a.removeAllFromArray.values||[];l=new On(d)}else"increment"in a?l=new gr(o,a.increment):U(16584,{proto:a});let u=Se.fromServerFormat(a.fieldPath);return new ms(u,l)})(n,s)):[];if(e.update){e.update.name;let s=hn(n,e.update.name),i=new Ze({mapValue:{fields:e.update.fields}});if(e.updateMask){let o=(function(l){let u=l.fieldPaths||[];return new St(u.map(d=>Se.fromServerFormat(d)))})(e.updateMask);return new Ht(s,i,o,t,r)}return new _r(s,i,t,r)}if(e.delete){let s=hn(n,e.delete);return new Mn(s,t)}if(e.verify){let s=hn(n,e.verify);return new da(s,t)}return U(1463,{proto:e})}function eR(n,e){return n&&n.length>0?(B(e!==void 0,14353),n.map(t=>(function(s,i){let o=s.updateTime?Ne(s.updateTime):Ne(i);return o.isEqual(j.min())&&(o=Ne(i)),new xf(o,s.transformResults||[])})(t,e))):[]}function kT(n,e){return{documents:[RT(n,e.path)]}}function NT(n,e){let t={structuredQuery:{}},r=e.path,s;e.collectionGroup!==null?(s=r,t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(s=r.popLast(),t.structuredQuery.from=[{collectionId:r.lastSegment()}]),t.parent=RT(n,s);let i=(function(u){if(u.length!==0)return OT(de.create(u,"and"))})(e.filters);i&&(t.structuredQuery.where=i);let o=(function(u){if(u.length!==0)return u.map(d=>(function(m){return{field:ri(m.field),direction:nR(m.dir)}})(d))})(e.orderBy);o&&(t.structuredQuery.orderBy=o);let a=Mf(n,e.limit);return a!==null&&(t.structuredQuery.limit=a),e.startAt&&(t.structuredQuery.startAt=(function(u){return{before:u.inclusive,values:u.position}})(e.startAt)),e.endAt&&(t.structuredQuery.endAt=(function(u){return{before:!u.inclusive,values:u.position}})(e.endAt)),{ft:t,parent:s}}function DT(n){let e=PT(n.parent),t=n.structuredQuery,r=t.from?t.from.length:0,s=null;if(r>0){B(r===1,65062);let d=t.from[0];d.allDescendants?s=d.collectionId:e=e.child(d.collectionId)}let i=[];t.where&&(i=(function(p){let m=VT(p);return m instanceof de&&cm(m)?m.getFilters():[m]})(t.where));let o=[];t.orderBy&&(o=(function(p){return p.map(m=>(function(S){return new pr(si(S.field),(function(k){switch(k){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(S.direction))})(m))})(t.orderBy));let a=null;t.limit&&(a=(function(p){let m;return m=typeof p=="object"?p.value:p,Ra(m)?null:m})(t.limit));let l=null;t.startAt&&(l=(function(p){let m=!!p.before,v=p.values||[];return new Kt(v,m)})(t.startAt));let u=null;return t.endAt&&(u=(function(p){let m=!p.before,v=p.values||[];return new Kt(v,m)})(t.endAt)),iT(e,s,o,i,a,"F",l,u)}function tR(n,e){let t=(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 U(28987,{purpose:s})}})(e.purpose);return t==null?null:{"goog-listen-tags":t}}function VT(n){return n.unaryFilter!==void 0?(function(t){switch(t.unaryFilter.op){case"IS_NAN":let r=si(t.unaryFilter.field);return re.create(r,"==",{doubleValue:NaN});case"IS_NULL":let s=si(t.unaryFilter.field);return re.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=si(t.unaryFilter.field);return re.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let o=si(t.unaryFilter.field);return re.create(o,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return U(61313);default:return U(60726)}})(n):n.fieldFilter!==void 0?(function(t){return re.create(si(t.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";case"OPERATOR_UNSPECIFIED":return U(58110);default:return U(50506)}})(t.fieldFilter.op),t.fieldFilter.value)})(n):n.compositeFilter!==void 0?(function(t){return de.create(t.compositeFilter.filters.map(r=>VT(r)),(function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return U(1026)}})(t.compositeFilter.op))})(n):U(30097,{filter:n})}function nR(n){return H0[n]}function rR(n){return Q0[n]}function sR(n){return Y0[n]}function ri(n){return{fieldPath:n.canonicalString()}}function si(n){return Se.fromServerFormat(n.fieldPath)}function OT(n){return n instanceof re?(function(t){if(t.op==="=="){if(Rw(t.value))return{unaryFilter:{field:ri(t.field),op:"IS_NAN"}};if(Sw(t.value))return{unaryFilter:{field:ri(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(Rw(t.value))return{unaryFilter:{field:ri(t.field),op:"IS_NOT_NAN"}};if(Sw(t.value))return{unaryFilter:{field:ri(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ri(t.field),op:rR(t.op),value:t.value}}})(n):n instanceof de?(function(t){let r=t.getFilters().map(s=>OT(s));return r.length===1?r[0]:{compositeFilter:{op:sR(t.op),filters:r}}})(n):U(54877,{filter:n})}function iR(n){let e=[];return n.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function MT(n){return n.length>=4&&n.get(0)==="projects"&&n.get(2)==="databases"}function FT(n){return!!n&&typeof n._toProto=="function"&&n._protoValueType==="ProtoValue"}var gs=class n{constructor(e,t,r,s,i=j.min(),o=j.min(),a=Re.EMPTY_BYTE_STRING,l=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=o,this.resumeToken=a,this.expectedCount=l}withSequenceNumber(e){return new n(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new n(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new n(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new n(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}};var Ol=class{constructor(e){this.yt=e}};function oR(n,e){let t;if(e.document)t=dm(n.yt,e.document,!!e.hasCommittedMutations);else if(e.noDocument){let r=O.fromSegments(e.noDocument.path),s=ys(e.noDocument.readTime);t=Ue.newNoDocument(r,s),e.hasCommittedMutations&&t.setHasCommittedMutations()}else{if(!e.unknownDocument)return U(56709);{let r=O.fromSegments(e.unknownDocument.path),s=ys(e.unknownDocument.version);t=Ue.newUnknownDocument(r,s)}}return e.readTime&&t.setReadTime((function(s){let i=new me(s[0],s[1]);return j.fromTimestamp(i)})(e.readTime)),t}function zw(n,e){let t=e.key,r={prefixPath:t.getCollectionPath().popLast().toArray(),collectionGroup:t.collectionGroup,documentId:t.path.lastSegment(),readTime:Ml(e.readTime),hasCommittedMutations:e.hasCommittedMutations};if(e.isFoundDocument())r.document=(function(i,o){return{name:ga(i,o.key),fields:o.data.value.mapValue.fields,updateTime:Ei(i,o.version.toTimestamp()),createTime:Ei(i,o.createTime.toTimestamp())}})(n.yt,e);else if(e.isNoDocument())r.noDocument={path:t.path.toArray(),readTime:_s(e.version)};else{if(!e.isUnknownDocument())return U(57904,{document:e});r.unknownDocument={path:t.path.toArray(),version:_s(e.version)}}return r}function Ml(n){let e=n.toTimestamp();return[e.seconds,e.nanoseconds]}function _s(n){let e=n.toTimestamp();return{seconds:e.seconds,nanoseconds:e.nanoseconds}}function ys(n){let e=new me(n.seconds,n.nanoseconds);return j.fromTimestamp(e)}function rs(n,e){let t=(e.baseMutations||[]).map(i=>Uf(n.yt,i));for(let i=0;iUf(n.yt,i)),s=me.fromMillis(e.localWriteTimeMs);return new fa(e.batchId,s,t,r)}function Ho(n){let e=ys(n.readTime),t=n.lastLimboFreeSnapshotVersion!==void 0?ys(n.lastLimboFreeSnapshotVersion):j.min(),r;return r=(function(i){return i.documents!==void 0})(n.query)?(function(i){let o=i.documents.length;return B(o===1,1966,{count:o}),ct(Es(PT(i.documents[0])))})(n.query):(function(i){return ct(DT(i))})(n.query),new gs(r,n.targetId,"TargetPurposeListen",n.lastListenSequenceNumber,e,t,Re.fromBase64String(n.resumeToken))}function LT(n,e){let t=_s(e.snapshotVersion),r=_s(e.lastLimboFreeSnapshotVersion),s;s=xl(e.target)?kT(n.yt,e.target):NT(n.yt,e.target).ft;let i=e.resumeToken.toBase64();return{targetId:e.targetId,canonicalId:ps(e.target),readTime:t,resumeToken:i,lastListenSequenceNumber:e.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function Au(n){let e=DT({parent:n.parent,structuredQuery:n.structuredQuery});return n.limitType==="LAST"?ha(e,e.limit,"L"):e}function Yd(n,e){return new pa(e.largestBatchId,Uf(n.yt,e.overlayMutation))}function Kw(n,e){let t=e.path.lastSegment();return[n,rt(e.path.popLast()),t]}function Ww(n,e,t,r){return{indexId:n,uid:e,sequenceNumber:t,readTime:_s(r.readTime),documentKey:rt(r.documentKey.path),largestBatchId:r.largestBatchId}}var Bf=class{getBundleMetadata(e,t){return $w(e).get(t).next(r=>{if(r)return(function(i){return{id:i.bundleId,createTime:ys(i.createTime),version:i.version}})(r)})}saveBundleMetadata(e,t){return $w(e).put((function(s){return{bundleId:s.id,createTime:_s(Ne(s.createTime)),version:s.version}})(t))}getNamedQuery(e,t){return Hw(e).get(t).next(r=>{if(r)return(function(i){return{name:i.name,query:Au(i.bundledQuery),readTime:ys(i.readTime)}})(r)})}saveNamedQuery(e,t){return Hw(e).put((function(s){return{name:s.name,readTime:_s(Ne(s.readTime)),bundledQuery:s.bundledQuery}})(t))}};function $w(n){return We(n,_u)}function Hw(n){return We(n,yu)}var Fl=class n{constructor(e,t){this.serializer=e,this.userId=t}static wt(e,t){let r=t.uid||"";return new n(e,r)}getOverlay(e,t){return jo(e).get(Kw(this.userId,t)).next(r=>r?Yd(this.serializer,r):null)}getOverlays(e,t){let r=ln();return C.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&r.set(s,i)})).next(()=>r)}saveOverlays(e,t,r){let s=[];return r.forEach((i,o)=>{let a=new pa(t,o);s.push(this.St(e,a))}),C.waitFor(s)}removeOverlaysForBatchId(e,t,r){let s=new Set;t.forEach(o=>s.add(rt(o.getCollectionPath())));let i=[];return s.forEach(o=>{let a=IDBKeyRange.bound([this.userId,o,r],[this.userId,o,r+1],!1,!0);i.push(jo(e).X(mf,a))}),C.waitFor(i)}getOverlaysForCollection(e,t,r){let s=ln(),i=rt(t),o=IDBKeyRange.bound([this.userId,i,r],[this.userId,i,Number.POSITIVE_INFINITY],!0);return jo(e).J(mf,o).next(a=>{for(let l of a){let u=Yd(this.serializer,l);s.set(u.getKey(),u)}return s})}getOverlaysForCollectionGroup(e,t,r,s){let i=ln(),o,a=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,Number.POSITIVE_INFINITY],!0);return jo(e).ee({index:UE,range:a},(l,u,d)=>{let p=Yd(this.serializer,u);i.size()i)}St(e,t){return jo(e).put((function(s,i,o){let[a,l,u]=Kw(i,o.mutation.key);return{userId:i,collectionPath:l,documentId:u,collectionGroup:o.mutation.key.getCollectionGroup(),largestBatchId:o.largestBatchId,overlayMutation:_a(s.yt,o.mutation)}})(this.serializer,this.userId,t))}};function jo(n){return We(n,vu)}var qf=class{bt(e){return We(e,rm)}getSessionToken(e){return this.bt(e).get("sessionToken").next(t=>{let r=t?.value;return r?Re.fromUint8Array(r):Re.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.bt(e).put({name:"sessionToken",value:t.toUint8Array()})}};var xn=class{constructor(){}Dt(e,t){this.Ct(e,t),t.vt()}Ct(e,t){if("nullValue"in e)this.Ft(t,5);else if("booleanValue"in e)this.Ft(t,10),t.Mt(e.booleanValue?1:0);else if("integerValue"in e)this.Ft(t,15),t.Mt(Te(e.integerValue));else if("doubleValue"in e){let r=Te(e.doubleValue);isNaN(r)?this.Ft(t,13):(this.Ft(t,15),ra(r)?t.Mt(0):t.Mt(r))}else if("timestampValue"in e){let r=e.timestampValue;this.Ft(t,20),typeof r=="string"&&(r=kn(r)),t.xt(`${r.seconds||""}`),t.Mt(r.nanos||0)}else if("stringValue"in e)this.Ot(e.stringValue,t),this.Nt(t);else if("bytesValue"in e)this.Ft(t,30),t.Bt(Nn(e.bytesValue)),this.Nt(t);else if("referenceValue"in e)this.Lt(e.referenceValue,t);else if("geoPointValue"in e){let r=e.geoPointValue;this.Ft(t,45),t.Mt(r.latitude||0),t.Mt(r.longitude||0)}else"mapValue"in e?JE(e)?this.Ft(t,Number.MAX_SAFE_INTEGER):Eu(e)?this.kt(e.mapValue,t):(this.Kt(e.mapValue,t),this.Nt(t)):"arrayValue"in e?(this.qt(e.arrayValue,t),this.Nt(t)):U(19022,{Ut:e})}Ot(e,t){this.Ft(t,25),this.$t(e,t)}$t(e,t){t.xt(e)}Kt(e,t){let r=e.fields||{};this.Ft(t,55);for(let s of Object.keys(r))this.Ot(s,t),this.Ct(r[s],t)}kt(e,t){let r=e.fields||{};this.Ft(t,53);let s=mi,i=r[s].arrayValue?.values?.length||0;this.Ft(t,15),t.Mt(Te(i)),this.Ot(s,t),this.Ct(r[s],t)}qt(e,t){let r=e.values||[];this.Ft(t,50);for(let s of r)this.Ct(s,t)}Lt(e,t){this.Ft(t,37),O.fromName(e).path.forEach(r=>{this.Ft(t,60),this.$t(r,t)})}Ft(e,t){e.Mt(t)}Nt(e){e.Mt(2)}};xn.Wt=new xn;var Js=255;function aR(n){if(n===0)return 8;let e=0;return n>>4||(e+=4,n<<=4),n>>6||(e+=2,n<<=2),n>>7||(e+=1),e}function Qw(n){let e=64-(function(r){let s=0;for(let i=0;i<8;++i){let o=aR(255&r[i]);if(s+=o,o!==8)break}return s})(n);return Math.ceil(e/8)}var jf=class{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Qt(e){let t=e[Symbol.iterator](),r=t.next();for(;!r.done;)this.Gt(r.value),r=t.next();this.zt()}jt(e){let t=e[Symbol.iterator](),r=t.next();for(;!r.done;)this.Jt(r.value),r=t.next();this.Ht()}Zt(e){for(let t of e){let r=t.charCodeAt(0);if(r<128)this.Gt(r);else if(r<2048)this.Gt(960|r>>>6),this.Gt(128|63&r);else if(t<"\uD800"||"\uDBFF">>12),this.Gt(128|63&r>>>6),this.Gt(128|63&r);else{let s=t.codePointAt(0);this.Gt(240|s>>>18),this.Gt(128|63&s>>>12),this.Gt(128|63&s>>>6),this.Gt(128|63&s)}}this.zt()}Xt(e){for(let t of e){let r=t.charCodeAt(0);if(r<128)this.Jt(r);else if(r<2048)this.Jt(960|r>>>6),this.Jt(128|63&r);else if(t<"\uD800"||"\uDBFF">>12),this.Jt(128|63&r>>>6),this.Jt(128|63&r);else{let s=t.codePointAt(0);this.Jt(240|s>>>18),this.Jt(128|63&s>>>12),this.Jt(128|63&s>>>6),this.Jt(128|63&s)}}this.Ht()}Yt(e){let t=this.en(e),r=Qw(t);this.tn(1+r),this.buffer[this.position++]=255&r;for(let s=t.length-r;sSe.comparator(t.field,r.field)),this.collectionId=e.collectionGroup!=null?e.collectionGroup:e.path.lastSegment(),this.dn=e.orderBy,this.mn=[];for(let t of e.filters){let r=t;r.isInequality()?this.Vn=this.Vn.add(r):this.mn.push(r)}}get fn(){return this.Vn.size>1}gn(e){if(B(e.collectionGroup===this.collectionId,49279),this.fn)return!1;let t=cf(e);if(t!==void 0&&!this.pn(t))return!1;let r=es(e),s=new Set,i=0,o=0;for(;i0){let a=this.Vn.getIterator().getNext();if(!s.has(a.field.canonicalString())){let l=r[i];if(!this.yn(a,l)||!this.wn(this.dn[o++],l))return!1}++i}for(;i=this.dn.length||!this.wn(this.dn[o++],a))return!1}return!0}Sn(){if(this.fn)return null;let e=new fe(Se.comparator),t=[];for(let r of this.mn)if(!r.field.isKeyField())if(r.op==="array-contains"||r.op==="array-contains-any")t.push(new cs(r.field,2));else{if(e.has(r.field))continue;e=e.add(r.field),t.push(new cs(r.field,0))}for(let r of this.dn)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new cs(r.field,r.dir==="asc"?0:1)));return new fs(fs.UNKNOWN_ID,this.collectionId,t,ui.empty())}pn(e){for(let t of this.mn)if(this.yn(t,e))return!0;return!1}yn(e,t){if(e===void 0||!e.field.isEqual(t.fieldPath))return!1;let r=e.op==="array-contains"||e.op==="array-contains-any";return t.kind===2===r}wn(e,t){return!!e.field.isEqual(t.fieldPath)&&(t.kind===0&&e.dir==="asc"||t.kind===1&&e.dir==="desc")}};function UT(n){if(B(n instanceof re||n instanceof de,20012),n instanceof re){if(n instanceof Pl){let t=n.value.arrayValue?.values?.map(r=>re.create(n.field,"==",r))||[];return de.create(t,"or")}return n}let e=n.filters.map(t=>UT(t));return de.create(e,n.op)}function cR(n){if(n.getFilters().length===0)return[];let e=$f(UT(n));return B(BT(e),7391),Kf(e)||Wf(e)?[e]:e.getFilters()}function Kf(n){return n instanceof re}function Wf(n){return n instanceof de&&cm(n)}function BT(n){return Kf(n)||Wf(n)||(function(t){if(t instanceof de&&wf(t)){for(let r of t.getFilters())if(!Kf(r)&&!Wf(r))return!1;return!0}return!1})(n)}function $f(n){if(B(n instanceof re||n instanceof de,34018),n instanceof re)return n;if(n.filters.length===1)return $f(n.filters[0]);let e=n.filters.map(r=>$f(r)),t=de.create(e,n.op);return t=Ul(t),BT(t)?t:(B(t instanceof de,64498),B(_i(t),40251),B(t.filters.length>1,57927),t.filters.reduce((r,s)=>fm(r,s)))}function fm(n,e){let t;return B(n instanceof re||n instanceof de,38388),B(e instanceof re||e instanceof de,25473),t=n instanceof re?e instanceof re?(function(s,i){return de.create([s,i],"and")})(n,e):Xw(n,e):e instanceof re?Xw(e,n):(function(s,i){if(B(s.filters.length>0&&i.filters.length>0,48005),_i(s)&&_i(i))return nT(s,i.getFilters());let o=wf(s)?s:i,a=wf(s)?i:s,l=o.filters.map(u=>fm(u,a));return de.create(l,"or")})(n,e),Ul(t)}function Xw(n,e){if(_i(e))return nT(e,n.getFilters());{let t=e.filters.map(r=>fm(n,r));return de.create(t,"or")}}function Ul(n){if(B(n instanceof re||n instanceof de,11850),n instanceof re)return n;let e=n.getFilters();if(e.length===1)return Ul(e[0]);if(eT(n))return n;let t=e.map(s=>Ul(s)),r=[];return t.forEach(s=>{s instanceof re?r.push(s):s instanceof de&&(s.op===n.op?r.push(...s.filters):r.push(s))}),r.length===1?r[0]:de.create(r,n.op)}var Hf=class{constructor(){this.bn=new ya}addToCollectionParentIndex(e,t){return this.bn.add(t),C.resolve()}getCollectionParents(e,t){return C.resolve(this.bn.getEntries(t))}addFieldIndex(e,t){return C.resolve()}deleteFieldIndex(e,t){return C.resolve()}deleteAllFieldIndexes(e){return C.resolve()}createTargetIndexes(e,t){return C.resolve()}getDocumentsMatchingTarget(e,t){return C.resolve(null)}getIndexType(e,t){return C.resolve(0)}getFieldIndexes(e,t){return C.resolve([])}getNextCollectionGroupToUpdate(e){return C.resolve(null)}getMinOffset(e,t){return C.resolve(Vt.min())}getMinOffsetFromCollectionGroup(e,t){return C.resolve(Vt.min())}updateCollectionGroup(e,t,r){return C.resolve()}updateIndexEntries(e,t){return C.resolve()}},ya=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),r=e.popLast(),s=this.index[t]||new fe(ie.comparator),i=!s.has(r);return this.index[t]=s.add(r),i}has(e){let t=e.lastSegment(),r=e.popLast(),s=this.index[t];return s&&s.has(r)}getEntries(e){return(this.index[e]||new fe(ie.comparator)).toArray()}};var Zw="IndexedDbIndexManager",rl=new Uint8Array(0),Qf=class{constructor(e,t){this.databaseId=t,this.Dn=new ya,this.Cn=new $t(r=>ps(r),(r,s)=>ka(r,s)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.Dn.has(t)){let r=t.lastSegment(),s=t.popLast();e.addOnCommittedListener(()=>{this.Dn.add(t)});let i={collectionId:r,parent:rt(s)};return eE(e).put(i)}return C.resolve()}getCollectionParents(e,t){let r=[],s=IDBKeyRange.bound([t,""],[SE(t),""],!1,!0);return eE(e).J(s).next(i=>{for(let o of i){if(o.collectionId!==t)break;r.push(cn(o.parent))}return r})}addFieldIndex(e,t){let r=Go(e),s=(function(a){return{indexId:a.indexId,collectionGroup:a.collectionGroup,fields:a.fields.map(l=>[l.fieldPath.canonicalString(),l.kind])}})(t);delete s.indexId;let i=r.add(s);if(t.indexState){let o=Zs(e);return i.next(a=>{o.put(Ww(a,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let r=Go(e),s=Zs(e),i=Xs(e);return r.delete(t.indexId).next(()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=Go(e),r=Xs(e),s=Zs(e);return t.X().next(()=>r.X()).next(()=>s.X())}createTargetIndexes(e,t){return C.forEach(this.vn(t),r=>this.getIndexType(e,r).next(s=>{if(s===0||s===1){let i=new Ll(r).Sn();if(i!=null)return this.addFieldIndex(e,i)}}))}getDocumentsMatchingTarget(e,t){let r=Xs(e),s=!0,i=new Map;return C.forEach(this.vn(t),o=>this.Fn(e,o).next(a=>{s&&(s=!!a),i.set(o,a)})).next(()=>{if(s){let o=$(),a=[];return C.forEach(i,(l,u)=>{D(Zw,`Using index ${(function(L){return`id=${L.indexId}|cg=${L.collectionGroup}|f=${L.fields.map(H=>`${H.fieldPath}:${H.kind}`).join(",")}`})(l)} to execute ${ps(t)}`);let d=(function(L,H){let J=cf(H);if(J===void 0)return null;for(let oe of kl(L,J.fieldPath))switch(oe.op){case"array-contains-any":return oe.value.arrayValue.values||[];case"array-contains":return[oe.value]}return null})(u,l),p=(function(L,H){let J=new Map;for(let oe of es(H))for(let E of kl(L,oe.fieldPath))switch(E.op){case"==":case"in":J.set(oe.fieldPath.canonicalString(),E.value);break;case"not-in":case"!=":return J.set(oe.fieldPath.canonicalString(),E.value),Array.from(J.values())}return null})(u,l),m=(function(L,H){let J=[],oe=!0;for(let E of es(H)){let _=E.kind===0?Dw(L,E.fieldPath,L.startAt):Vw(L,E.fieldPath,L.startAt);J.push(_.value),oe&&(oe=_.inclusive)}return new Kt(J,oe)})(u,l),v=(function(L,H){let J=[],oe=!0;for(let E of es(H)){let _=E.kind===0?Vw(L,E.fieldPath,L.endAt):Dw(L,E.fieldPath,L.endAt);J.push(_.value),oe&&(oe=_.inclusive)}return new Kt(J,oe)})(u,l),S=this.Mn(l,u,m),x=this.Mn(l,u,v),k=this.xn(l,u,p),q=this.On(l.indexId,d,S,m.inclusive,x,v.inclusive,k);return C.forEach(q,G=>r.Z(G,t.limit).next(L=>{L.forEach(H=>{let J=O.fromSegments(H.documentKey);o.has(J)||(o=o.add(J),a.push(J))})}))}).next(()=>a)}return C.resolve(null)})}vn(e){let t=this.Cn.get(e);return t||(e.filters.length===0?t=[e]:t=cR(de.create(e.filters,"and")).map(r=>Pf(e.path,e.collectionGroup,e.orderBy,r.getFilters(),e.limit,e.startAt,e.endAt)),this.Cn.set(e,t),t)}On(e,t,r,s,i,o,a){let l=(t!=null?t.length:1)*Math.max(r.length,i.length),u=l/(t!=null?t.length:1),d=[];for(let p=0;pthis.Bn(e,m,k,!0));d.push(...this.createRange(v,S,x))}return d}Bn(e,t,r,s){let i=new is(e,O.empty(),t,r);return s?i:i.En()}Ln(e,t,r,s){let i=new is(e,O.empty(),t,r);return s?i.En():i}Fn(e,t){let r=new Ll(t),s=t.collectionGroup!=null?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,s).next(i=>{let o=null;for(let a of i)r.gn(a)&&(!o||a.fields.length>o.fields.length)&&(o=a);return o})}getIndexType(e,t){let r=2,s=this.vn(t);return C.forEach(s,i=>this.Fn(e,i).next(o=>{o?r!==0&&o.fields.length<(function(l){let u=new fe(Se.comparator),d=!1;for(let p of l.filters)for(let m of p.getFlattenedFilters())m.field.isKeyField()||(m.op==="array-contains"||m.op==="array-contains-any"?d=!0:u=u.add(m.field));for(let p of l.orderBy)p.field.isKeyField()||(u=u.add(p.field));return u.size+(d?1:0)})(i)&&(r=1):r=0})).next(()=>(function(o){return o.limit!==null})(t)&&s.length>1&&r===2?1:r)}kn(e,t){let r=new ss;for(let s of es(e)){let i=t.data.field(s.fieldPath);if(i==null)return null;let o=r.ln(s.kind);xn.Wt.Dt(i,o)}return r.un()}Nn(e){let t=new ss;return xn.Wt.Dt(e,t.ln(0)),t.un()}Kn(e,t){let r=new ss;return xn.Wt.Dt(Cr(this.databaseId,t),r.ln((function(i){let o=es(i);return o.length===0?0:o[o.length-1].kind})(e))),r.un()}xn(e,t,r){if(r===null)return[];let s=[];s.push(new ss);let i=0;for(let o of es(e)){let a=r[i++];for(let l of s)if(this.qn(t,o.fieldPath)&&ua(a))s=this.Un(s,o,a);else{let u=l.ln(o.kind);xn.Wt.Dt(a,u)}}return this.$n(s)}Mn(e,t,r){return this.xn(e,t,r.position)}$n(e){let t=[];for(let r=0;rr instanceof re&&r.field.isEqual(t)&&(r.op==="in"||r.op==="not-in"))}getFieldIndexes(e,t){let r=Go(e),s=Zs(e);return(t?r.J(pf,IDBKeyRange.bound(t,t)):r.J()).next(i=>{let o=[];return C.forEach(i,a=>s.get([a.indexId,this.uid]).next(l=>{o.push((function(d,p){let m=p?new ui(p.sequenceNumber,new Vt(ys(p.readTime),new O(cn(p.documentKey)),p.largestBatchId)):ui.empty(),v=d.fields.map(([S,x])=>new cs(Se.fromServerFormat(S),x));return new fs(d.indexId,d.collectionGroup,v,m)})(a,l))})).next(()=>o)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(t=>t.length===0?null:(t.sort((r,s)=>{let i=r.indexState.sequenceNumber-s.indexState.sequenceNumber;return i!==0?i:W(r.collectionGroup,s.collectionGroup)}),t[0].collectionGroup))}updateCollectionGroup(e,t,r){let s=Go(e),i=Zs(e);return this.Wn(e).next(o=>s.J(pf,IDBKeyRange.bound(t,t)).next(a=>C.forEach(a,l=>i.put(Ww(l.indexId,this.uid,o,r)))))}updateIndexEntries(e,t){let r=new Map;return C.forEach(t,(s,i)=>{let o=r.get(s.collectionGroup);return(o?C.resolve(o):this.getFieldIndexes(e,s.collectionGroup)).next(a=>(r.set(s.collectionGroup,a),C.forEach(a,l=>this.Qn(e,s,l).next(u=>{let d=this.Gn(i,l);return u.isEqual(d)?C.resolve():this.zn(e,i,l,u,d)}))))})}jn(e,t,r,s){return Xs(e).put(s.Rn(this.uid,this.Kn(r,t.key),t.key))}Jn(e,t,r,s){return Xs(e).delete(s.An(this.uid,this.Kn(r,t.key),t.key))}Qn(e,t,r){let s=Xs(e),i=new fe(sr);return s.ee({index:LE,range:IDBKeyRange.only([r.indexId,this.uid,fl(this.Kn(r,t))])},(o,a)=>{i=i.add(new is(r.indexId,t,Jw(a.arrayValue),Jw(a.directionalValue)))}).next(()=>i)}Gn(e,t){let r=new fe(sr),s=this.kn(t,e);if(s==null)return r;let i=cf(t);if(i!=null){let o=e.data.field(i.fieldPath);if(ua(o))for(let a of o.arrayValue.values||[])r=r.add(new is(t.indexId,e.key,this.Nn(a),s))}else r=r.add(new is(t.indexId,e.key,rl,s));return r}zn(e,t,r,s,i){D(Zw,"Updating index entries for document '%s'",t.key);let o=[];return(function(l,u,d,p,m){let v=l.getIterator(),S=u.getIterator(),x=Ys(v),k=Ys(S);for(;x||k;){let q=!1,G=!1;if(x&&k){let L=d(x,k);L<0?G=!0:L>0&&(q=!0)}else x!=null?G=!0:q=!0;q?(p(k),k=Ys(S)):G?(m(x),x=Ys(v)):(x=Ys(v),k=Ys(S))}})(s,i,sr,a=>{o.push(this.jn(e,t,r,a))},a=>{o.push(this.Jn(e,t,r,a))}),C.waitFor(o)}Wn(e){let t=1;return Zs(e).ee({index:FE,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(r,s,i)=>{i.done(),t=s.sequenceNumber+1}).next(()=>t)}createRange(e,t,r){r=r.sort((o,a)=>sr(o,a)).filter((o,a,l)=>!a||sr(o,l[a-1])!==0);let s=[];s.push(e);for(let o of r){let a=sr(o,e),l=sr(o,t);if(a===0)s[0]=e.En();else if(a>0&&l<0)s.push(o),s.push(o.En());else if(l>0)break}s.push(t);let i=[];for(let o=0;o0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(tE)}getMinOffset(e,t){return C.mapArray(this.vn(t),r=>this.Fn(e,r).next(s=>s||U(44426))).next(tE)}};function eE(n){return We(n,oa)}function Xs(n){return We(n,Jo)}function Go(n){return We(n,nm)}function Zs(n){return We(n,Yo)}function tE(n){B(n.length!==0,28825);let e=n[0].indexState.offset,t=e.largestBatchId;for(let r=1;r(a++,m.delete()));i.push(l.next(()=>{B(a===1,47070,{batchId:t.batchId})}));let u=[];for(let d of t.mutations){let p=VE(e,d.key.path,t.batchId);i.push(s.delete(p)),u.push(d.key)}return C.waitFor(i).next(()=>u)}function Bl(n){if(!n)return 0;let e;if(n.document)e=n.document;else if(n.unknownDocument)e=n.unknownDocument;else{if(!n.noDocument)throw U(14731);e=n.noDocument}return JSON.stringify(e).length}_t.DEFAULT_COLLECTION_PERCENTILE=10,_t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,_t.DEFAULT=new _t(qT,_t.DEFAULT_COLLECTION_PERCENTILE,_t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),_t.DISABLED=new _t(-1,0,0);var ql=class n{constructor(e,t,r,s){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=s,this.Zn={}}static wt(e,t,r,s){B(e.uid!=="",64387);let i=e.isAuthenticated()?e.uid:"";return new n(i,t,r,s)}checkEmpty(e){let t=!0,r=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ir(e).ee({index:os,range:r},(s,i,o)=>{t=!1,o.done()}).next(()=>t)}addMutationBatch(e,t,r,s){let i=ii(e),o=ir(e);return o.add({}).next(a=>{B(typeof a=="number",49019);let l=new fa(a,t,r,s),u=(function(v,S,x){let k=x.baseMutations.map(G=>_a(v.yt,G)),q=x.mutations.map(G=>_a(v.yt,G));return{userId:S,batchId:x.batchId,localWriteTimeMs:x.localWriteTime.toMillis(),baseMutations:k,mutations:q}})(this.serializer,this.userId,l),d=[],p=new fe((m,v)=>W(m.canonicalString(),v.canonicalString()));for(let m of s){let v=VE(this.userId,m.key.path,a);p=p.add(m.key.path.popLast()),d.push(o.put(u)),d.push(i.put(v,o0))}return p.forEach(m=>{d.push(this.indexManager.addToCollectionParentIndex(e,m))}),e.addOnCommittedListener(()=>{this.Zn[a]=l.keys()}),C.waitFor(d).next(()=>l)})}lookupMutationBatch(e,t){return ir(e).get(t).next(r=>r?(B(r.userId===this.userId,48,"Unexpected user for mutation batch",{userId:r.userId,batchId:t}),rs(this.serializer,r)):null)}Xn(e,t){return this.Zn[t]?C.resolve(this.Zn[t]):this.lookupMutationBatch(e,t).next(r=>{if(r){let s=r.keys();return this.Zn[t]=s,s}return null})}getNextMutationBatchAfterBatchId(e,t){let r=t+1,s=IDBKeyRange.lowerBound([this.userId,r]),i=null;return ir(e).ee({index:os,range:s},(o,a,l)=>{a.userId===this.userId&&(B(a.batchId>=r,47524,{Yn:r}),i=rs(this.serializer,a)),l.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),r=lr;return ir(e).ee({index:os,range:t,reverse:!0},(s,i,o)=>{r=i.batchId,o.done()}).next(()=>r)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,lr],[this.userId,Number.POSITIVE_INFINITY]);return ir(e).J(os,t).next(r=>r.map(s=>rs(this.serializer,s)))}getAllMutationBatchesAffectingDocumentKey(e,t){let r=al(this.userId,t.path),s=IDBKeyRange.lowerBound(r),i=[];return ii(e).ee({range:s},(o,a,l)=>{let[u,d,p]=o,m=cn(d);if(u===this.userId&&t.path.isEqual(m))return ir(e).get(p).next(v=>{if(!v)throw U(61480,{er:o,batchId:p});B(v.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:v.userId,batchId:p}),i.push(rs(this.serializer,v))});l.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new fe(W),s=[];return t.forEach(i=>{let o=al(this.userId,i.path),a=IDBKeyRange.lowerBound(o),l=ii(e).ee({range:a},(u,d,p)=>{let[m,v,S]=u,x=cn(v);m===this.userId&&i.path.isEqual(x)?r=r.add(S):p.done()});s.push(l)}),C.waitFor(s).next(()=>this.tr(e,r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,s=r.length+1,i=al(this.userId,r),o=IDBKeyRange.lowerBound(i),a=new fe(W);return ii(e).ee({range:o},(l,u,d)=>{let[p,m,v]=l,S=cn(m);p===this.userId&&r.isPrefixOf(S)?S.length===s&&(a=a.add(v)):d.done()}).next(()=>this.tr(e,a))}tr(e,t){let r=[],s=[];return t.forEach(i=>{s.push(ir(e).get(i).next(o=>{if(o===null)throw U(35274,{batchId:i});B(o.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:o.userId,batchId:i}),r.push(rs(this.serializer,o))}))}),C.waitFor(s).next(()=>r)}removeMutationBatch(e,t){return jT(e.le,this.userId,t).next(r=>(e.addOnCommittedListener(()=>{this.nr(t.batchId)}),C.forEach(r,s=>this.referenceDelegate.markPotentiallyOrphaned(e,s))))}nr(e){delete this.Zn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return C.resolve();let r=IDBKeyRange.lowerBound((function(o){return[o]})(this.userId)),s=[];return ii(e).ee({range:r},(i,o,a)=>{if(i[0]===this.userId){let l=cn(i[1]);s.push(l)}else a.done()}).next(()=>{B(s.length===0,56720,{rr:s.map(i=>i.canonicalString())})})})}containsKey(e,t){return GT(e,this.userId,t)}ir(e){return zT(e).get(this.userId).next(t=>t||{userId:this.userId,lastAcknowledgedBatchId:lr,lastStreamToken:""})}};function GT(n,e,t){let r=al(e,t.path),s=r[1],i=IDBKeyRange.lowerBound(r),o=!1;return ii(n).ee({range:i,Y:!0},(a,l,u)=>{let[d,p,m]=a;d===e&&p===s&&(o=!0),u.done()}).next(()=>o)}function ir(n){return We(n,jt)}function ii(n){return We(n,hi)}function zT(n){return We(n,sa)}var yr=class n{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new n(0)}static ar(){return new n(-1)}};var Yf=class{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.ur(e).next(t=>{let r=new yr(t.highestTargetId);return t.highestTargetId=r.next(),this.cr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.ur(e).next(t=>j.fromTimestamp(new me(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.ur(e).next(t=>t.highestListenSequenceNumber)}setTargetsMetadata(e,t,r){return this.ur(e).next(s=>(s.highestListenSequenceNumber=t,r&&(s.lastRemoteSnapshotVersion=r.toTimestamp()),t>s.highestListenSequenceNumber&&(s.highestListenSequenceNumber=t),this.cr(e,s)))}addTargetData(e,t){return this.lr(e,t).next(()=>this.ur(e).next(r=>(r.targetCount+=1,this.hr(t,r),this.cr(e,r))))}updateTargetData(e,t){return this.lr(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>ei(e).delete(t.targetId)).next(()=>this.ur(e)).next(r=>(B(r.targetCount>0,8065),r.targetCount-=1,this.cr(e,r)))}removeTargets(e,t,r){let s=0,i=[];return ei(e).ee((o,a)=>{let l=Ho(a);l.sequenceNumber<=t&&r.get(l.targetId)===null&&(s++,i.push(this.removeTargetData(e,l)))}).next(()=>C.waitFor(i)).next(()=>s)}forEachTarget(e,t){return ei(e).ee((r,s)=>{let i=Ho(s);t(i)})}ur(e){return rE(e).get(bl).next(t=>(B(t!==null,2888),t))}cr(e,t){return rE(e).put(bl,t)}lr(e,t){return ei(e).put(LT(this.serializer,t))}hr(e,t){let r=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,r=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,r=!0),r}getTargetCount(e){return this.ur(e).next(t=>t.targetCount)}getTargetData(e,t){let r=ps(t),s=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),i=null;return ei(e).ee({range:s,index:ME},(o,a,l)=>{let u=Ho(a);ka(t,u.target)&&(i=u,l.done())}).next(()=>i)}addMatchingKeys(e,t,r){let s=[],i=ar(e);return t.forEach(o=>{let a=rt(o.path);s.push(i.put({targetId:r,path:a})),s.push(this.referenceDelegate.addReference(e,r,o))}),C.waitFor(s)}removeMatchingKeys(e,t,r){let s=ar(e);return C.forEach(t,i=>{let o=rt(i.path);return C.waitFor([s.delete([r,o]),this.referenceDelegate.removeReference(e,r,i)])})}removeMatchingKeysForTargetId(e,t){let r=ar(e),s=IDBKeyRange.bound([t],[t+1],!1,!0);return r.delete(s)}getMatchingKeysForTargetId(e,t){let r=IDBKeyRange.bound([t],[t+1],!1,!0),s=ar(e),i=$();return s.ee({range:r,Y:!0},(o,a,l)=>{let u=cn(o[1]),d=new O(u);i=i.add(d)}).next(()=>i)}containsKey(e,t){let r=rt(t.path),s=IDBKeyRange.bound([r],[SE(r)],!1,!0),i=0;return ar(e).ee({index:tm,Y:!0,range:s},([o,a],l,u)=>{o!==0&&(i++,u.done())}).next(()=>i>0)}At(e,t){return ei(e).get(t).next(r=>r?Ho(r):null)}};function ei(n){return We(n,di)}function rE(n){return We(n,us)}function ar(n){return We(n,fi)}var sE="LruGarbageCollector",lR=1048576;function iE([n,e],[t,r]){let s=W(n,t);return s===0?W(e,r):s}var Jf=class{constructor(e){this.Pr=e,this.buffer=new fe(iE),this.Tr=0}Ir(){return++this.Tr}Er(e){let t=[e,this.Ir()];if(this.buffer.size{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){Ar(t)?D(sE,"Ignoring IndexedDB error during garbage collection: ",t):await Ir(t)}await this.Ar(3e5)})}},Xf=class{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next(r=>Math.floor(t/100*r))}nthSequenceNumber(e,t){if(t===0)return C.resolve(Ct.ce);let r=new Jf(t);return this.Vr.forEachTarget(e,s=>r.Er(s.sequenceNumber)).next(()=>this.Vr.mr(e,s=>r.Er(s))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.Vr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(D("LruGarbageCollector","Garbage collection skipped; disabled"),C.resolve(nE)):this.getCacheSize(e).next(r=>r(p>this.params.maximumSequenceNumbersToCollect?(D("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${p}`),s=this.params.maximumSequenceNumbersToCollect):s=p,o=Date.now(),this.nthSequenceNumber(e,s))).next(p=>(r=p,a=Date.now(),this.removeTargets(e,r,t))).next(p=>(i=p,l=Date.now(),this.removeOrphanedDocuments(e,r))).next(p=>(u=Date.now(),ti()<=Dt.DEBUG&&D("LruGarbageCollector",`LRU Garbage Collection Counted targets in ${o-d}ms Determined least recently used ${s} in `+(a-o)+`ms Removed ${i} targets in `+(l-a)+`ms Removed ${p} documents in `+(u-l)+`ms Total Duration: ${u-d}ms`),C.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:p})))}};function KT(n,e){return new Xf(n,e)}var Zf=class{constructor(e,t){this.db=e,this.garbageCollector=KT(this,t)}dr(e){let t=this.pr(e);return this.db.getTargetCache().getTargetCount(e).next(r=>t.next(s=>r+s))}pr(e){let t=0;return this.mr(e,r=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}mr(e,t){return this.yr(e,(r,s)=>t(s))}addReference(e,t,r){return sl(e,r)}removeReference(e,t,r){return sl(e,r)}removeTargets(e,t,r){return this.db.getTargetCache().removeTargets(e,t,r)}markPotentiallyOrphaned(e,t){return sl(e,t)}wr(e,t){return(function(s,i){let o=!1;return zT(s).te(a=>GT(s,a,i).next(l=>(l&&(o=!0),C.resolve(!l)))).next(()=>o)})(e,t)}removeOrphanedDocuments(e,t){let r=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],i=0;return this.yr(e,(o,a)=>{if(a<=t){let l=this.wr(e,o).next(u=>{if(!u)return i++,r.getEntry(e,o).next(()=>(r.removeEntry(o,j.min()),ar(e).delete((function(p){return[0,rt(p.path)]})(o))))});s.push(l)}}).next(()=>C.waitFor(s)).next(()=>r.apply(e)).next(()=>i)}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,r)}updateLimboDocument(e,t){return sl(e,t)}yr(e,t){let r=ar(e),s,i=Ct.ce;return r.ee({index:tm},([o,a],{path:l,sequenceNumber:u})=>{o===0?(i!==Ct.ce&&t(new O(cn(s)),i),i=u,s=l):i=Ct.ce}).next(()=>{i!==Ct.ce&&t(new O(cn(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}};function sl(n,e){return ar(n).put((function(r,s){return{targetId:0,path:rt(r.path),sequenceNumber:s}})(e,n.currentSequenceNumber))}var Gl=class{constructor(){this.changes=new $t(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Ue.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let r=this.changes.get(t);return r!==void 0?C.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}};var ep=class{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,r){return Zr(e).put(r)}removeEntry(e,t,r){return Zr(e).delete((function(i,o){let a=i.path.toArray();return[a.slice(0,a.length-2),a[a.length-2],Ml(o),a[a.length-1]]})(t,r))}updateMetadata(e,t){return this.getMetadata(e).next(r=>(r.byteSize+=t,this.Sr(e,r)))}getEntry(e,t){let r=Ue.newInvalidDocument(t);return Zr(e).ee({index:cl,range:IDBKeyRange.only(zo(t))},(s,i)=>{r=this.br(t,i)}).next(()=>r)}Dr(e,t){let r={size:0,document:Ue.newInvalidDocument(t)};return Zr(e).ee({index:cl,range:IDBKeyRange.only(zo(t))},(s,i)=>{r={document:this.br(t,i),size:Bl(i)}}).next(()=>r)}getEntries(e,t){let r=yt();return this.Cr(e,t,(s,i)=>{let o=this.br(s,i);r=r.insert(s,o)}).next(()=>r)}vr(e,t){let r=yt(),s=new ye(O.comparator);return this.Cr(e,t,(i,o)=>{let a=this.br(i,o);r=r.insert(i,a),s=s.insert(i,Bl(o))}).next(()=>({documents:r,Fr:s}))}Cr(e,t,r){if(t.isEmpty())return C.resolve();let s=new fe(cE);t.forEach(l=>s=s.add(l));let i=IDBKeyRange.bound(zo(s.first()),zo(s.last())),o=s.getIterator(),a=o.getNext();return Zr(e).ee({index:cl,range:i},(l,u,d)=>{let p=O.fromSegments([...u.prefixPath,u.collectionGroup,u.documentId]);for(;a&&cE(a,p)<0;)r(a,null),a=o.getNext();a&&a.isEqual(p)&&(r(a,u),a=o.hasNext()?o.getNext():null),a?d.j(zo(a)):d.done()}).next(()=>{for(;a;)r(a,null),a=o.hasNext()?o.getNext():null})}getDocumentsMatchingQuery(e,t,r,s,i){let o=t.path,a=[o.popLast().toArray(),o.lastSegment(),Ml(r.readTime),r.documentKey.path.isEmpty()?"":r.documentKey.path.lastSegment()],l=[o.popLast().toArray(),o.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Zr(e).J(IDBKeyRange.bound(a,l,!0)).next(u=>{i?.incrementDocumentReadCount(u.length);let d=yt();for(let p of u){let m=this.br(O.fromSegments(p.prefixPath.concat(p.collectionGroup,p.documentId)),p);m.isFoundDocument()&&(Da(t,m)||s.has(m.key))&&(d=d.insert(m.key,m))}return d})}getAllFromCollectionGroup(e,t,r,s){let i=yt(),o=aE(t,r),a=aE(t,Vt.max());return Zr(e).ee({index:OE,range:IDBKeyRange.bound(o,a,!0)},(l,u,d)=>{let p=this.br(O.fromSegments(u.prefixPath.concat(u.collectionGroup,u.documentId)),u);i=i.insert(p.key,p),i.size===s&&d.done()}).next(()=>i)}newChangeBuffer(e){return new tp(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(t=>t.byteSize)}getMetadata(e){return oE(e).get(ff).next(t=>(B(!!t,20021),t))}Sr(e,t){return oE(e).put(ff,t)}br(e,t){if(t){let r=oR(this.serializer,t);if(!(r.isNoDocument()&&r.version.isEqual(j.min())))return r}return Ue.newInvalidDocument(e)}};function WT(n){return new ep(n)}var tp=class extends Gl{constructor(e,t){super(),this.Mr=e,this.trackRemovals=t,this.Or=new $t(r=>r.toString(),(r,s)=>r.isEqual(s))}applyChanges(e){let t=[],r=0,s=new fe((i,o)=>W(i.canonicalString(),o.canonicalString()));return this.changes.forEach((i,o)=>{let a=this.Or.get(i);if(t.push(this.Mr.removeEntry(e,i,a.readTime)),o.isValidDocument()){let l=zw(this.Mr.serializer,o);s=s.add(i.path.popLast());let u=Bl(l);r+=u-a.size,t.push(this.Mr.addEntry(e,i,l))}else if(r-=a.size,this.trackRemovals){let l=zw(this.Mr.serializer,o.convertToNoDocument(j.min()));t.push(this.Mr.addEntry(e,i,l))}}),s.forEach(i=>{t.push(this.Mr.indexManager.addToCollectionParentIndex(e,i))}),t.push(this.Mr.updateMetadata(e,r)),C.waitFor(t)}getFromCache(e,t){return this.Mr.Dr(e,t).next(r=>(this.Or.set(t,{size:r.size,readTime:r.document.readTime}),r.document))}getAllFromCache(e,t){return this.Mr.vr(e,t).next(({documents:r,Fr:s})=>(s.forEach((i,o)=>{this.Or.set(i,{size:o,readTime:r.get(i).readTime})}),r))}};function oE(n){return We(n,ia)}function Zr(n){return We(n,Al)}function zo(n){let e=n.path.toArray();return[e.slice(0,e.length-2),e[e.length-2],e[e.length-1]]}function aE(n,e){let t=e.documentKey.path.toArray();return[n,Ml(e.readTime),t.slice(0,t.length-2),t.length>0?t[t.length-1]:""]}function cE(n,e){let t=n.path.toArray(),r=e.path.toArray(),s=0;for(let i=0;i(r=s,this.remoteDocumentCache.getEntry(e,t))).next(s=>(r!==null&&ea(r.mutation,s,St.empty(),me.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.getLocalViewOfDocuments(e,r,$()).next(()=>r))}getLocalViewOfDocuments(e,t,r=$()){let s=ln();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,r).next(i=>{let o=$o();return i.forEach((a,l)=>{o=o.insert(a,l.overlayedDocument)}),o}))}getOverlayedDocuments(e,t){let r=ln();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,$()))}populateOverlays(e,t,r){let s=[];return r.forEach(i=>{t.has(i)||s.push(i)}),this.documentOverlayCache.getOverlays(e,s).next(i=>{i.forEach((o,a)=>{t.set(o,a)})})}computeViews(e,t,r,s){let i=yt(),o=Zo(),a=(function(){return Zo()})();return t.forEach((l,u)=>{let d=r.get(u.key);s.has(u.key)&&(d===void 0||d.mutation instanceof Ht)?i=i.insert(u.key,u):d!==void 0?(o.set(u.key,d.mutation.getFieldMask()),ea(d.mutation,u,d.mutation.getFieldMask(),me.now())):o.set(u.key,St.empty())}),this.recalculateAndSaveOverlays(e,i).next(l=>(l.forEach((u,d)=>o.set(u,d)),t.forEach((u,d)=>a.set(u,new np(d,o.get(u)??null))),a))}recalculateAndSaveOverlays(e,t){let r=Zo(),s=new ye((o,a)=>o-a),i=$();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(o=>{for(let a of o)a.keys().forEach(l=>{let u=t.get(l);if(u===null)return;let d=r.get(l)||St.empty();d=a.applyToLocalView(u,d),r.set(l,d);let p=(s.get(a.batchId)||$()).add(l);s=s.insert(a.batchId,p)})}).next(()=>{let o=[],a=s.getReverseIterator();for(;a.hasNext();){let l=a.getNext(),u=l.key,d=l.value,p=pT();d.forEach(m=>{if(!i.has(m)){let v=ET(t.get(m),r.get(m));v!==null&&p.set(m,v),i=i.add(m)}}),o.push(this.documentOverlayCache.saveOverlays(e,u,p))}return C.waitFor(o)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.recalculateAndSaveOverlays(e,r))}getDocumentsMatchingQuery(e,t,r,s){return V0(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Tu(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,s):this.getDocumentsMatchingCollectionQuery(e,t,r,s)}getNextDocuments(e,t,r,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,r,s).next(i=>{let o=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,s-i.size):C.resolve(ln()),a=li,l=i;return o.next(u=>C.forEach(u,(d,p)=>(a{l=l.insert(d,m)}))).next(()=>this.populateOverlays(e,u,i)).next(()=>this.computeViews(e,l,u,$())).next(d=>({batchId:a,changes:fT(d)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new O(t)).next(r=>{let s=$o();return r.isFoundDocument()&&(s=s.insert(r.key,r)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,r,s){let i=t.collectionGroup,o=$o();return this.indexManager.getCollectionParents(e,i).next(a=>C.forEach(a,l=>{let u=(function(p,m){return new Wt(m,null,p.explicitOrderBy.slice(),p.filters.slice(),p.limit,p.limitType,p.startAt,p.endAt)})(t,l.child(i));return this.getDocumentsMatchingCollectionQuery(e,u,r,s).next(d=>{d.forEach((p,m)=>{o=o.insert(p,m)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(e,t,r,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(o=>(i=o,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,s))).next(o=>{i.forEach((l,u)=>{let d=u.getKey();o.get(d)===null&&(o=o.insert(d,Ue.newInvalidDocument(d)))});let a=$o();return o.forEach((l,u)=>{let d=i.get(l);d!==void 0&&ea(d.mutation,u,St.empty(),me.now()),Da(t,u)&&(a=a.insert(l,u))}),a})}};var rp=class{constructor(e){this.serializer=e,this.Nr=new Map,this.Br=new Map}getBundleMetadata(e,t){return C.resolve(this.Nr.get(t))}saveBundleMetadata(e,t){return this.Nr.set(t.id,(function(s){return{id:s.id,version:s.version,createTime:Ne(s.createTime)}})(t)),C.resolve()}getNamedQuery(e,t){return C.resolve(this.Br.get(t))}saveNamedQuery(e,t){return this.Br.set(t.name,(function(s){return{name:s.name,query:Au(s.bundledQuery),readTime:Ne(s.readTime)}})(t)),C.resolve()}};var sp=class{constructor(){this.overlays=new ye(O.comparator),this.Lr=new Map}getOverlay(e,t){return C.resolve(this.overlays.get(t))}getOverlays(e,t){let r=ln();return C.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&r.set(s,i)})).next(()=>r)}saveOverlays(e,t,r){return r.forEach((s,i)=>{this.St(e,t,i)}),C.resolve()}removeOverlaysForBatchId(e,t,r){let s=this.Lr.get(r);return s!==void 0&&(s.forEach(i=>this.overlays=this.overlays.remove(i)),this.Lr.delete(r)),C.resolve()}getOverlaysForCollection(e,t,r){let s=ln(),i=t.length+1,o=new O(t.child("")),a=this.overlays.getIteratorFrom(o);for(;a.hasNext();){let l=a.getNext().value,u=l.getKey();if(!t.isPrefixOf(u.path))break;u.path.length===i&&l.largestBatchId>r&&s.set(l.getKey(),l)}return C.resolve(s)}getOverlaysForCollectionGroup(e,t,r,s){let i=new ye((u,d)=>u-d),o=this.overlays.getIterator();for(;o.hasNext();){let u=o.getNext().value;if(u.getKey().getCollectionGroup()===t&&u.largestBatchId>r){let d=i.get(u.largestBatchId);d===null&&(d=ln(),i=i.insert(u.largestBatchId,d)),d.set(u.getKey(),u)}}let a=ln(),l=i.getIterator();for(;l.hasNext()&&(l.getNext().value.forEach((u,d)=>a.set(u,d)),!(a.size()>=s)););return C.resolve(a)}St(e,t,r){let s=this.overlays.get(r.key);if(s!==null){let o=this.Lr.get(s.largestBatchId).delete(r.key);this.Lr.set(s.largestBatchId,o)}this.overlays=this.overlays.insert(r.key,new pa(t,r));let i=this.Lr.get(t);i===void 0&&(i=$(),this.Lr.set(t,i)),this.Lr.set(t,i.add(r.key))}};var ip=class{constructor(){this.sessionToken=Re.EMPTY_BYTE_STRING}getSessionToken(e){return C.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,C.resolve()}};var va=class{constructor(){this.kr=new fe(Fe.Kr),this.qr=new fe(Fe.Ur)}isEmpty(){return this.kr.isEmpty()}addReference(e,t){let r=new Fe(e,t);this.kr=this.kr.add(r),this.qr=this.qr.add(r)}$r(e,t){e.forEach(r=>this.addReference(r,t))}removeReference(e,t){this.Wr(new Fe(e,t))}Qr(e,t){e.forEach(r=>this.removeReference(r,t))}Gr(e){let t=new O(new ie([])),r=new Fe(t,e),s=new Fe(t,e+1),i=[];return this.qr.forEachInRange([r,s],o=>{this.Wr(o),i.push(o.key)}),i}zr(){this.kr.forEach(e=>this.Wr(e))}Wr(e){this.kr=this.kr.delete(e),this.qr=this.qr.delete(e)}jr(e){let t=new O(new ie([])),r=new Fe(t,e),s=new Fe(t,e+1),i=$();return this.qr.forEachInRange([r,s],o=>{i=i.add(o.key)}),i}containsKey(e){let t=new Fe(e,0),r=this.kr.firstAfterOrEqual(t);return r!==null&&e.isEqual(r.key)}},Fe=class{constructor(e,t){this.key=e,this.Jr=t}static Kr(e,t){return O.comparator(e.key,t.key)||W(e.Jr,t.Jr)}static Ur(e,t){return W(e.Jr,t.Jr)||O.comparator(e.key,t.key)}};var op=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Yn=1,this.Hr=new fe(Fe.Kr)}checkEmpty(e){return C.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,r,s){let i=this.Yn;this.Yn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let o=new fa(i,t,r,s);this.mutationQueue.push(o);for(let a of s)this.Hr=this.Hr.add(new Fe(a.key,i)),this.indexManager.addToCollectionParentIndex(e,a.key.path.popLast());return C.resolve(o)}lookupMutationBatch(e,t){return C.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let r=t+1,s=this.Xr(r),i=s<0?0:s;return C.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return C.resolve(this.mutationQueue.length===0?lr:this.Yn-1)}getAllMutationBatches(e){return C.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new Fe(t,0),s=new Fe(t,Number.POSITIVE_INFINITY),i=[];return this.Hr.forEachInRange([r,s],o=>{let a=this.Zr(o.Jr);i.push(a)}),C.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new fe(W);return t.forEach(s=>{let i=new Fe(s,0),o=new Fe(s,Number.POSITIVE_INFINITY);this.Hr.forEachInRange([i,o],a=>{r=r.add(a.Jr)})}),C.resolve(this.Yr(r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,s=r.length+1,i=r;O.isDocumentKey(i)||(i=i.child(""));let o=new Fe(new O(i),0),a=new fe(W);return this.Hr.forEachWhile(l=>{let u=l.key.path;return!!r.isPrefixOf(u)&&(u.length===s&&(a=a.add(l.Jr)),!0)},o),C.resolve(this.Yr(a))}Yr(e){let t=[];return e.forEach(r=>{let s=this.Zr(r);s!==null&&t.push(s)}),t}removeMutationBatch(e,t){B(this.ei(t.batchId,"removed")===0,55003),this.mutationQueue.shift();let r=this.Hr;return C.forEach(t.mutations,s=>{let i=new Fe(s.key,t.batchId);return r=r.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.Hr=r})}nr(e){}containsKey(e,t){let r=new Fe(t,0),s=this.Hr.firstAfterOrEqual(r);return C.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,C.resolve()}ei(e,t){return this.Xr(e)}Xr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}};var ap=class{constructor(e){this.ti=e,this.docs=(function(){return new ye(O.comparator)})(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let r=t.key,s=this.docs.get(r),i=s?s.size:0,o=this.ti(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:o}),this.size+=o-i,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let r=this.docs.get(t);return C.resolve(r?r.document.mutableCopy():Ue.newInvalidDocument(t))}getEntries(e,t){let r=yt();return t.forEach(s=>{let i=this.docs.get(s);r=r.insert(s,i?i.document.mutableCopy():Ue.newInvalidDocument(s))}),C.resolve(r)}getDocumentsMatchingQuery(e,t,r,s){let i=yt(),o=t.path,a=new O(o.child("__id-9223372036854775808__")),l=this.docs.getIteratorFrom(a);for(;l.hasNext();){let{key:u,value:{document:d}}=l.getNext();if(!o.isPrefixOf(u.path))break;u.path.length>o.length+1||Zp(xE(d),r)<=0||(s.has(d.key)||Da(t,d))&&(i=i.insert(d.key,d.mutableCopy()))}return C.resolve(i)}getAllFromCollectionGroup(e,t,r,s){U(9500)}ni(e,t){return C.forEach(this.docs,r=>t(r))}newChangeBuffer(e){return new cp(this)}getSize(e){return C.resolve(this.size)}},cp=class extends Gl{constructor(e){super(),this.Mr=e}applyChanges(e){let t=[];return this.changes.forEach((r,s)=>{s.isValidDocument()?t.push(this.Mr.addEntry(e,s)):this.Mr.removeEntry(r)}),C.waitFor(t)}getFromCache(e,t){return this.Mr.getEntry(e,t)}getAllFromCache(e,t){return this.Mr.getEntries(e,t)}};var lp=class{constructor(e){this.persistence=e,this.ri=new $t(t=>ps(t),ka),this.lastRemoteSnapshotVersion=j.min(),this.highestTargetId=0,this.ii=0,this.si=new va,this.targetCount=0,this.oi=yr._r()}forEachTarget(e,t){return this.ri.forEach((r,s)=>t(s)),C.resolve()}getLastRemoteSnapshotVersion(e){return C.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return C.resolve(this.ii)}allocateTargetId(e){return this.highestTargetId=this.oi.next(),C.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.ii&&(this.ii=t),C.resolve()}lr(e){this.ri.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.oi=new yr(t),this.highestTargetId=t),e.sequenceNumber>this.ii&&(this.ii=e.sequenceNumber)}addTargetData(e,t){return this.lr(t),this.targetCount+=1,C.resolve()}updateTargetData(e,t){return this.lr(t),C.resolve()}removeTargetData(e,t){return this.ri.delete(t.target),this.si.Gr(t.targetId),this.targetCount-=1,C.resolve()}removeTargets(e,t,r){let s=0,i=[];return this.ri.forEach((o,a)=>{a.sequenceNumber<=t&&r.get(a.targetId)===null&&(this.ri.delete(o),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),s++)}),C.waitFor(i).next(()=>s)}getTargetCount(e){return C.resolve(this.targetCount)}getTargetData(e,t){let r=this.ri.get(t)||null;return C.resolve(r)}addMatchingKeys(e,t,r){return this.si.$r(t,r),C.resolve()}removeMatchingKeys(e,t,r){this.si.Qr(t,r);let s=this.persistence.referenceDelegate,i=[];return s&&t.forEach(o=>{i.push(s.markPotentiallyOrphaned(e,o))}),C.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.si.Gr(t),C.resolve()}getMatchingKeysForTargetId(e,t){let r=this.si.jr(t);return C.resolve(r)}containsKey(e,t){return C.resolve(this.si.containsKey(t))}};var wa=class{constructor(e,t){this._i={},this.overlays={},this.ai=new Ct(0),this.ui=!1,this.ui=!0,this.ci=new ip,this.referenceDelegate=e(this),this.li=new lp(this),this.indexManager=new Hf,this.remoteDocumentCache=(function(s){return new ap(s)})(r=>this.referenceDelegate.hi(r)),this.serializer=new Ol(t),this.Pi=new rp(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ui=!1,Promise.resolve()}get started(){return this.ui}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new sp,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this._i[e.toKey()];return r||(r=new op(t,this.referenceDelegate),this._i[e.toKey()]=r),r}getGlobalsCache(){return this.ci}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Pi}runTransaction(e,t,r){D("MemoryPersistence","Starting transaction:",e);let s=new up(this.ai.next());return this.referenceDelegate.Ti(),r(s).next(i=>this.referenceDelegate.Ii(s).next(()=>i)).toPromise().then(i=>(s.raiseOnCommittedEvent(),i))}Ei(e,t){return C.or(Object.values(this._i).map(r=>()=>r.containsKey(e,t)))}},up=class extends El{constructor(e){super(),this.currentSequenceNumber=e}},Kl=class n{constructor(e){this.persistence=e,this.Ri=new va,this.Ai=null}static Vi(e){return new n(e)}get di(){if(this.Ai)return this.Ai;throw U(60996)}addReference(e,t,r){return this.Ri.addReference(r,t),this.di.delete(r.toString()),C.resolve()}removeReference(e,t,r){return this.Ri.removeReference(r,t),this.di.add(r.toString()),C.resolve()}markPotentiallyOrphaned(e,t){return this.di.add(t.toString()),C.resolve()}removeTarget(e,t){this.Ri.Gr(t.targetId).forEach(s=>this.di.add(s.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(s=>{s.forEach(i=>this.di.add(i.toString()))}).next(()=>r.removeTargetData(e,t))}Ti(){this.Ai=new Set}Ii(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return C.forEach(this.di,r=>{let s=O.fromPath(r);return this.mi(e,s).next(i=>{i||t.removeEntry(s,j.min())})}).next(()=>(this.Ai=null,t.apply(e)))}updateLimboDocument(e,t){return this.mi(e,t).next(r=>{r?this.di.delete(t.toString()):this.di.add(t.toString())})}hi(e){return 0}mi(e,t){return C.or([()=>C.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}},Wl=class n{constructor(e,t){this.persistence=e,this.fi=new $t(r=>rt(r.path),(r,s)=>r.isEqual(s)),this.garbageCollector=KT(this,t)}static Vi(e,t){return new n(e,t)}Ti(){}Ii(e){return C.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}dr(e){let t=this.pr(e);return this.persistence.getTargetCache().getTargetCount(e).next(r=>t.next(s=>r+s))}pr(e){let t=0;return this.mr(e,r=>{t++}).next(()=>t)}mr(e,t){return C.forEach(this.fi,(r,s)=>this.wr(e,r,s).next(i=>i?C.resolve():t(s)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,t){let r=0,s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.ni(e,o=>this.wr(e,o,t).next(a=>{a||(r++,i.removeEntry(o,j.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.fi.set(t,e.currentSequenceNumber),C.resolve()}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),C.resolve()}removeReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),C.resolve()}updateLimboDocument(e,t){return this.fi.set(t,e.currentSequenceNumber),C.resolve()}hi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=ul(e.data.value)),t}wr(e,t,r){return C.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let s=this.fi.get(t);return C.resolve(s!==void 0&&s>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}};var hp=class{constructor(e){this.serializer=e}k(e,t,r,s){let i=new Tl("createOrUpgrade",t);r<1&&s>=1&&((function(l){l.createObjectStore(Pa)})(e),(function(l){l.createObjectStore(sa,{keyPath:i0}),l.createObjectStore(jt,{keyPath:Tw,autoIncrement:!0}).createIndex(os,Iw,{unique:!0}),l.createObjectStore(hi)})(e),lE(e),(function(l){l.createObjectStore(ts)})(e));let o=C.resolve();return r<3&&s>=3&&(r!==0&&((function(l){l.deleteObjectStore(fi),l.deleteObjectStore(di),l.deleteObjectStore(us)})(e),lE(e)),o=o.next(()=>(function(l){let u=l.store(us),d={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:j.min().toTimestamp(),targetCount:0};return u.put(bl,d)})(i))),r<4&&s>=4&&(r!==0&&(o=o.next(()=>(function(l,u){return u.store(jt).J().next(p=>{l.deleteObjectStore(jt),l.createObjectStore(jt,{keyPath:Tw,autoIncrement:!0}).createIndex(os,Iw,{unique:!0});let m=u.store(jt),v=p.map(S=>m.put(S));return C.waitFor(v)})})(e,i))),o=o.next(()=>{(function(l){l.createObjectStore(pi,{keyPath:p0})})(e)})),r<5&&s>=5&&(o=o.next(()=>this.gi(i))),r<6&&s>=6&&(o=o.next(()=>((function(l){l.createObjectStore(ia)})(e),this.pi(i)))),r<7&&s>=7&&(o=o.next(()=>this.yi(i))),r<8&&s>=8&&(o=o.next(()=>this.wi(e,i))),r<9&&s>=9&&(o=o.next(()=>{(function(l){l.objectStoreNames.contains("remoteDocumentChanges")&&l.deleteObjectStore("remoteDocumentChanges")})(e)})),r<10&&s>=10&&(o=o.next(()=>this.Si(i))),r<11&&s>=11&&(o=o.next(()=>{(function(l){l.createObjectStore(_u,{keyPath:m0})})(e),(function(l){l.createObjectStore(yu,{keyPath:g0})})(e)})),r<12&&s>=12&&(o=o.next(()=>{(function(l){let u=l.createObjectStore(vu,{keyPath:I0});u.createIndex(mf,A0,{unique:!1}),u.createIndex(UE,b0,{unique:!1})})(e)})),r<13&&s>=13&&(o=o.next(()=>(function(l){let u=l.createObjectStore(Al,{keyPath:a0});u.createIndex(cl,c0),u.createIndex(OE,l0)})(e)).next(()=>this.bi(e,i)).next(()=>e.deleteObjectStore(ts))),r<14&&s>=14&&(o=o.next(()=>this.Di(e,i))),r<15&&s>=15&&(o=o.next(()=>(function(l){l.createObjectStore(nm,{keyPath:_0,autoIncrement:!0}).createIndex(pf,y0,{unique:!1}),l.createObjectStore(Yo,{keyPath:v0}).createIndex(FE,w0,{unique:!1}),l.createObjectStore(Jo,{keyPath:E0}).createIndex(LE,T0,{unique:!1})})(e))),r<16&&s>=16&&(o=o.next(()=>{t.objectStore(Yo).clear()}).next(()=>{t.objectStore(Jo).clear()})),r<17&&s>=17&&(o=o.next(()=>{(function(l){l.createObjectStore(rm,{keyPath:C0})})(e)})),r<18&&s>=18&&kd()&&(o=o.next(()=>{t.objectStore(Yo).clear()}).next(()=>{t.objectStore(Jo).clear()})),o}pi(e){let t=0;return e.store(ts).ee((r,s)=>{t+=Bl(s)}).next(()=>{let r={byteSize:t};return e.store(ia).put(ff,r)})}gi(e){let t=e.store(sa),r=e.store(jt);return t.J().next(s=>C.forEach(s,i=>{let o=IDBKeyRange.bound([i.userId,lr],[i.userId,i.lastAcknowledgedBatchId]);return r.J(os,o).next(a=>C.forEach(a,l=>{B(l.userId===i.userId,18650,"Cannot process batch from unexpected user",{batchId:l.batchId});let u=rs(this.serializer,l);return jT(e,i.userId,u).next(()=>{})}))}))}yi(e){let t=e.store(fi),r=e.store(ts);return e.store(us).get(bl).next(s=>{let i=[];return r.ee((o,a)=>{let l=new ie(o),u=(function(p){return[0,rt(p)]})(l);i.push(t.get(u).next(d=>d?C.resolve():(p=>t.put({targetId:0,path:rt(p),sequenceNumber:s.highestListenSequenceNumber}))(l)))}).next(()=>C.waitFor(i))})}wi(e,t){e.createObjectStore(oa,{keyPath:f0});let r=t.store(oa),s=new ya,i=o=>{if(s.add(o)){let a=o.lastSegment(),l=o.popLast();return r.put({collectionId:a,parent:rt(l)})}};return t.store(ts).ee({Y:!0},(o,a)=>{let l=new ie(o);return i(l.popLast())}).next(()=>t.store(hi).ee({Y:!0},([o,a,l],u)=>{let d=cn(a);return i(d.popLast())}))}Si(e){let t=e.store(di);return t.ee((r,s)=>{let i=Ho(s),o=LT(this.serializer,i);return t.put(o)})}bi(e,t){let r=t.store(ts),s=[];return r.ee((i,o)=>{let a=t.store(Al),l=(function(p){return p.document?new O(ie.fromString(p.document.name).popFirst(5)):p.noDocument?O.fromSegments(p.noDocument.path):p.unknownDocument?O.fromSegments(p.unknownDocument.path):U(36783)})(o).path.toArray(),u={prefixPath:l.slice(0,l.length-2),collectionGroup:l[l.length-2],documentId:l[l.length-1],readTime:o.readTime||[0,0],unknownDocument:o.unknownDocument,noDocument:o.noDocument,document:o.document,hasCommittedMutations:!!o.hasCommittedMutations};s.push(a.put(u))}).next(()=>C.waitFor(s))}Di(e,t){let r=t.store(jt),s=WT(this.serializer),i=new wa(Kl.Vi,this.serializer.yt);return r.J().next(o=>{let a=new Map;return o.forEach(l=>{let u=a.get(l.userId)??$();rs(this.serializer,l).keys().forEach(d=>u=u.add(d)),a.set(l.userId,u)}),C.forEach(a,(l,u)=>{let d=new Le(u),p=Fl.wt(this.serializer,d),m=i.getIndexManager(d),v=ql.wt(d,this.serializer,m,i.referenceDelegate);return new zl(s,v,p,m).recalculateAndSaveOverlaysForDocumentKeys(new aa(t,Ct.ce),l).next()})})}};function lE(n){n.createObjectStore(fi,{keyPath:h0}).createIndex(tm,d0,{unique:!0}),n.createObjectStore(di,{keyPath:"targetId"}).createIndex(ME,u0,{unique:!0}),n.createObjectStore(us)}var or="IndexedDbPersistence",Jd=18e5,Xd=5e3,Zd="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.",$T="main",dp=class n{constructor(e,t,r,s,i,o,a,l,u,d,p=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=r,this.Ci=i,this.window=o,this.document=a,this.Fi=u,this.Mi=d,this.xi=p,this.ai=null,this.ui=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Oi=null,this.inForeground=!1,this.Ni=null,this.Bi=null,this.Li=Number.NEGATIVE_INFINITY,this.ki=m=>Promise.resolve(),!n.v())throw new N(R.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new Zf(this,s),this.Ki=t+$T,this.serializer=new Ol(l),this.qi=new hr(this.Ki,this.xi,new hp(this.serializer)),this.ci=new qf,this.li=new Yf(this.referenceDelegate,this.serializer),this.remoteDocumentCache=WT(this.serializer),this.Pi=new Bf,this.window&&this.window.localStorage?this.Ui=this.window.localStorage:(this.Ui=null,d===!1&&xe(or,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.$i().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new N(R.FAILED_PRECONDITION,Zd);return this.Wi(),this.Qi(),this.Gi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.li.getHighestSequenceNumber(e))}).then(e=>{this.ai=new Ct(e,this.Fi)}).then(()=>{this.ui=!0}).catch(e=>(this.qi&&this.qi.close(),Promise.reject(e)))}zi(e){return this.ki=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.qi.q(async t=>{t.newVersion===null&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Ci.enqueueAndForget(async()=>{this.started&&await this.$i()}))}$i(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>il(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.ji(e).next(t=>{t||(this.isPrimary=!1,this.Ci.enqueueRetryable(()=>this.ki(!1)))})}).next(()=>this.Ji(e)).next(t=>this.isPrimary&&!t?this.Hi(e).next(()=>!1):!!t&&this.Zi(e).next(()=>!0))).catch(e=>{if(Ar(e))return D(or,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return D(or,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Ci.enqueueRetryable(()=>this.ki(e)),this.isPrimary=e})}ji(e){return Ko(e).get(Qs).next(t=>C.resolve(this.Xi(t)))}Yi(e){return il(e).delete(this.clientId)}async es(){if(this.isPrimary&&!this.ts(this.Li,Jd)){this.Li=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",t=>{let r=We(t,pi);return r.J().next(s=>{let i=this.ns(s,Jd),o=s.filter(a=>i.indexOf(a)===-1);return C.forEach(o,a=>r.delete(a.clientId)).next(()=>o)})}).catch(()=>[]);if(this.Ui)for(let t of e)this.Ui.removeItem(this.rs(t.clientId))}}Gi(){this.Bi=this.Ci.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.$i().then(()=>this.es()).then(()=>this.Gi()))}Xi(e){return!!e&&e.ownerId===this.clientId}Ji(e){return this.Mi?C.resolve(!0):Ko(e).get(Qs).next(t=>{if(t!==null&&this.ts(t.leaseTimestampMs,Xd)&&!this.ss(t.ownerId)){if(this.Xi(t)&&this.networkEnabled)return!0;if(!this.Xi(t)){if(!t.allowTabSynchronization)throw new N(R.FAILED_PRECONDITION,Zd);return!1}}return!(!this.networkEnabled||!this.inForeground)||il(e).J().next(r=>this.ns(r,Xd).find(s=>{if(this.clientId!==s.clientId){let i=!this.networkEnabled&&s.networkEnabled,o=!this.inForeground&&s.inForeground,a=this.networkEnabled===s.networkEnabled;if(i||o&&a)return!0}return!1})===void 0)}).next(t=>(this.isPrimary!==t&&D(or,`Client ${t?"is":"is not"} eligible for a primary lease.`),t))}async shutdown(){this.ui=!1,this._s(),this.Bi&&(this.Bi.cancel(),this.Bi=null),this.us(),this.cs(),await this.qi.runTransaction("shutdown","readwrite",[Pa,pi],e=>{let t=new aa(e,Ct.ce);return this.Hi(t).next(()=>this.Yi(t))}),this.qi.close(),this.ls()}ns(e,t){return e.filter(r=>this.ts(r.updateTimeMs,t)&&!this.ss(r.clientId))}hs(){return this.runTransaction("getActiveClients","readonly",e=>il(e).J().next(t=>this.ns(t,Jd).map(r=>r.clientId)))}get started(){return this.ui}getGlobalsCache(){return this.ci}getMutationQueue(e,t){return ql.wt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Qf(e,this.serializer.yt.databaseId)}getDocumentOverlayCache(e){return Fl.wt(this.serializer,e)}getBundleCache(){return this.Pi}runTransaction(e,t,r){D(or,"Starting transaction:",e);let s=t==="readonly"?"readonly":"readwrite",i=(function(l){return l===18?P0:l===17?GE:l===16?R0:l===15?sm:l===14?jE:l===13?qE:l===12?S0:l===11?BE:void U(60245)})(this.xi),o;return this.qi.runTransaction(e,s,i,a=>(o=new aa(a,this.ai?this.ai.next():Ct.ce),t==="readwrite-primary"?this.ji(o).next(l=>!!l||this.Ji(o)).next(l=>{if(!l)throw xe(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.Ci.enqueueRetryable(()=>this.ki(!1)),new N(R.FAILED_PRECONDITION,kE);return r(o)}).next(l=>this.Zi(o).next(()=>l)):this.Ps(o).next(()=>r(o)))).then(a=>(o.raiseOnCommittedEvent(),a))}Ps(e){return Ko(e).get(Qs).next(t=>{if(t!==null&&this.ts(t.leaseTimestampMs,Xd)&&!this.ss(t.ownerId)&&!this.Xi(t)&&!(this.Mi||this.allowTabSynchronization&&t.allowTabSynchronization))throw new N(R.FAILED_PRECONDITION,Zd)})}Zi(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Ko(e).put(Qs,t)}static v(){return hr.v()}Hi(e){let t=Ko(e);return t.get(Qs).next(r=>this.Xi(r)?(D(or,"Releasing primary lease."),t.delete(Qs)):C.resolve())}ts(e,t){let r=Date.now();return!(er)||(xe(`Detected an update time that is in the future: ${e} > ${r}`),!1))}Wi(){this.document!==null&&typeof this.document.addEventListener=="function"&&(this.Ni=()=>{this.Ci.enqueueAndForget(()=>(this.inForeground=this.document.visibilityState==="visible",this.$i()))},this.document.addEventListener("visibilitychange",this.Ni),this.inForeground=this.document.visibilityState==="visible")}us(){this.Ni&&(this.document.removeEventListener("visibilitychange",this.Ni),this.Ni=null)}Qi(){typeof this.window?.addEventListener=="function"&&(this.Oi=()=>{this._s();let e=/(?:Version|Mobile)\/1[456]/;xd()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.Ci.enterRestrictedMode(!0),this.Ci.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Oi))}cs(){this.Oi&&(this.window.removeEventListener("pagehide",this.Oi),this.Oi=null)}ss(e){try{let t=this.Ui?.getItem(this.rs(e))!==null;return D(or,`Client '${e}' ${t?"is":"is not"} zombied in LocalStorage`),t}catch(t){return xe(or,"Failed to get zombied client id.",t),!1}}_s(){if(this.Ui)try{this.Ui.setItem(this.rs(this.clientId),String(Date.now()))}catch(e){xe("Failed to set zombie client id.",e)}}ls(){if(this.Ui)try{this.Ui.removeItem(this.rs(this.clientId))}catch{}}rs(e){return`firestore_zombie_${this.persistenceKey}_${e}`}};function Ko(n){return We(n,Pa)}function il(n){return We(n,pi)}function pm(n,e){let t=n.projectId;return n.isDefaultDatabase||(t+="."+n.database),"firestore/"+e+"/"+t+"/"}var fp=class n{constructor(e,t,r,s){this.targetId=e,this.fromCache=t,this.Ts=r,this.Is=s}static Es(e,t){let r=$(),s=$();for(let i of t.docChanges)switch(i.type){case 0:r=r.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new n(e,t.fromCache,r,s)}};var pp=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var $l=class{constructor(){this.Rs=!1,this.As=!1,this.Vs=100,this.ds=(function(){return xd()?8:NE(So())>0?6:4})()}initialize(e,t){this.fs=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,r,s){let i={result:null};return this.gs(e,t).next(o=>{i.result=o}).next(()=>{if(!i.result)return this.ps(e,t,s,r).next(o=>{i.result=o})}).next(()=>{if(i.result)return;let o=new pp;return this.ys(e,t,o).next(a=>{if(i.result=a,this.As)return this.ws(e,t,o,a.size)})}).next(()=>i.result)}ws(e,t,r,s){return r.documentReadCountthis.ds*s?(ti()<=Dt.DEBUG&&D("QueryEngine","The SDK decides to create cache indexes for query:",ni(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,ct(t))):C.resolve())}gs(e,t){if(Ow(t))return C.resolve(null);let r=ct(t);return this.indexManager.getIndexType(e,r).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=ha(t,null,"F"),r=ct(t)),this.indexManager.getDocumentsMatchingTarget(e,r).next(i=>{let o=$(...i);return this.fs.getDocuments(e,o).next(a=>this.indexManager.getMinOffset(e,r).next(l=>{let u=this.Ss(t,a);return this.bs(t,u,o,l.readTime)?this.gs(e,ha(t,null,"F")):this.Ds(e,u,t,l)}))})))}ps(e,t,r,s){return Ow(t)||s.isEqual(j.min())?C.resolve(null):this.fs.getDocuments(e,r).next(i=>{let o=this.Ss(t,i);return this.bs(t,o,r,s)?C.resolve(null):(ti()<=Dt.DEBUG&&D("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),ni(t)),this.Ds(e,o,t,PE(s,li)).next(a=>a))})}Ss(e,t){let r=new fe(hT(e));return t.forEach((s,i)=>{Da(e,i)&&(r=r.add(i))}),r}bs(e,t,r,s){if(e.limit===null)return!1;if(r.size!==t.size)return!0;let i=e.limitType==="F"?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}ys(e,t,r){return ti()<=Dt.DEBUG&&D("QueryEngine","Using full collection scan to execute query:",ni(t)),this.fs.getDocumentsMatchingQuery(e,t,Vt.min(),r)}Ds(e,t,r,s){return this.fs.getDocumentsMatchingQuery(e,r,s).next(i=>(t.forEach(o=>{i=i.insert(o.key,o)}),i))}};var mm="LocalStore",uR=3e8,mp=class{constructor(e,t,r,s){this.persistence=e,this.Cs=t,this.serializer=s,this.vs=new ye(W),this.Fs=new $t(i=>ps(i),ka),this.Ms=new Map,this.xs=e.getRemoteDocumentCache(),this.li=e.getTargetCache(),this.Pi=e.getBundleCache(),this.Os(r)}Os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new zl(this.xs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.xs.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.vs))}};function HT(n,e,t,r){return new mp(n,e,t,r)}async function QT(n,e){let t=F(n);return await t.persistence.runTransaction("Handle user change","readonly",r=>{let s;return t.mutationQueue.getAllMutationBatches(r).next(i=>(s=i,t.Os(e),t.mutationQueue.getAllMutationBatches(r))).next(i=>{let o=[],a=[],l=$();for(let u of s){o.push(u.batchId);for(let d of u.mutations)l=l.add(d.key)}for(let u of i){a.push(u.batchId);for(let d of u.mutations)l=l.add(d.key)}return t.localDocuments.getDocuments(r,l).next(u=>({Ns:u,removedBatchIds:o,addedBatchIds:a}))})})}function hR(n,e){let t=F(n);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",r=>{let s=e.batch.keys(),i=t.xs.newChangeBuffer({trackRemovals:!0});return(function(a,l,u,d){let p=u.batch,m=p.keys(),v=C.resolve();return m.forEach(S=>{v=v.next(()=>d.getEntry(l,S)).next(x=>{let k=u.docVersions.get(S);B(k!==null,48541),x.version.compareTo(k)<0&&(p.applyToRemoteDocument(x,u),x.isValidDocument()&&(x.setReadTime(u.commitVersion),d.addEntry(x)))})}),v.next(()=>a.mutationQueue.removeMutationBatch(l,p))})(t,r,e,i).next(()=>i.apply(r)).next(()=>t.mutationQueue.performConsistencyCheck(r)).next(()=>t.documentOverlayCache.removeOverlaysForBatchId(r,s,e.batch.batchId)).next(()=>t.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(r,(function(a){let l=$();for(let u=0;u0&&(l=l.add(a.batch.mutations[u].key));return l})(e))).next(()=>t.localDocuments.getDocuments(r,s))})}function YT(n){let e=F(n);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.li.getLastRemoteSnapshotVersion(t))}function dR(n,e){let t=F(n),r=e.snapshotVersion,s=t.vs;return t.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let o=t.xs.newChangeBuffer({trackRemovals:!0});s=t.vs;let a=[];e.targetChanges.forEach((d,p)=>{let m=s.get(p);if(!m)return;a.push(t.li.removeMatchingKeys(i,d.removedDocuments,p).next(()=>t.li.addMatchingKeys(i,d.addedDocuments,p)));let v=m.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(p)!==null?v=v.withResumeToken(Re.EMPTY_BYTE_STRING,j.min()).withLastLimboFreeSnapshotVersion(j.min()):d.resumeToken.approximateByteSize()>0&&(v=v.withResumeToken(d.resumeToken,r)),s=s.insert(p,v),(function(x,k,q){return x.resumeToken.approximateByteSize()===0||k.snapshotVersion.toMicroseconds()-x.snapshotVersion.toMicroseconds()>=uR?!0:q.addedDocuments.size+q.modifiedDocuments.size+q.removedDocuments.size>0})(m,v,d)&&a.push(t.li.updateTargetData(i,v))});let l=yt(),u=$();if(e.documentUpdates.forEach(d=>{e.resolvedLimboDocuments.has(d)&&a.push(t.persistence.referenceDelegate.updateLimboDocument(i,d))}),a.push(JT(i,o,e.documentUpdates).next(d=>{l=d.Bs,u=d.Ls})),!r.isEqual(j.min())){let d=t.li.getLastRemoteSnapshotVersion(i).next(p=>t.li.setTargetsMetadata(i,i.currentSequenceNumber,r));a.push(d)}return C.waitFor(a).next(()=>o.apply(i)).next(()=>t.localDocuments.getLocalViewOfDocuments(i,l,u)).next(()=>l)}).then(i=>(t.vs=s,i))}function JT(n,e,t){let r=$(),s=$();return t.forEach(i=>r=r.add(i)),e.getEntries(n,r).next(i=>{let o=yt();return t.forEach((a,l)=>{let u=i.get(a);l.isFoundDocument()!==u.isFoundDocument()&&(s=s.add(a)),l.isNoDocument()&&l.version.isEqual(j.min())?(e.removeEntry(a,l.readTime),o=o.insert(a,l)):!u.isValidDocument()||l.version.compareTo(u.version)>0||l.version.compareTo(u.version)===0&&u.hasPendingWrites?(e.addEntry(l),o=o.insert(a,l)):D(mm,"Ignoring outdated watch update for ",a,". Current version:",u.version," Watch version:",l.version)}),{Bs:o,Ls:s}})}function fR(n,e){let t=F(n);return t.persistence.runTransaction("Get next mutation batch","readonly",r=>(e===void 0&&(e=lr),t.mutationQueue.getNextMutationBatchAfterBatchId(r,e)))}function Ti(n,e){let t=F(n);return t.persistence.runTransaction("Allocate target","readwrite",r=>{let s;return t.li.getTargetData(r,e).next(i=>i?(s=i,C.resolve(s)):t.li.allocateTargetId(r).next(o=>(s=new gs(e,o,"TargetPurposeListen",r.currentSequenceNumber),t.li.addTargetData(r,s).next(()=>s))))}).then(r=>{let s=t.vs.get(r.targetId);return(s===null||r.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.vs=t.vs.insert(r.targetId,r),t.Fs.set(e,r.targetId)),r})}async function Ii(n,e,t){let r=F(n),s=r.vs.get(e),i=t?"readwrite":"readwrite-primary";try{t||await r.persistence.runTransaction("Release target",i,o=>r.persistence.referenceDelegate.removeTarget(o,s))}catch(o){if(!Ar(o))throw o;D(mm,`Failed to update sequence numbers for target ${e}: ${o}`)}r.vs=r.vs.remove(e),r.Fs.delete(s.target)}function Hl(n,e,t){let r=F(n),s=j.min(),i=$();return r.persistence.runTransaction("Execute query","readwrite",o=>(function(l,u,d){let p=F(l),m=p.Fs.get(d);return m!==void 0?C.resolve(p.vs.get(m)):p.li.getTargetData(u,d)})(r,o,ct(e)).next(a=>{if(a)return s=a.lastLimboFreeSnapshotVersion,r.li.getMatchingKeysForTargetId(o,a.targetId).next(l=>{i=l})}).next(()=>r.Cs.getDocumentsMatchingQuery(o,e,t?s:j.min(),t?i:$())).next(a=>(eI(r,uT(e),a),{documents:a,ks:i})))}function XT(n,e){let t=F(n),r=F(t.li),s=t.vs.get(e);return s?Promise.resolve(s.target):t.persistence.runTransaction("Get target data","readonly",i=>r.At(i,e).next(o=>o?o.target:null))}function ZT(n,e){let t=F(n),r=t.Ms.get(e)||j.min();return t.persistence.runTransaction("Get new document changes","readonly",s=>t.xs.getAllFromCollectionGroup(s,e,PE(r,li),Number.MAX_SAFE_INTEGER)).then(s=>(eI(t,e,s),s))}function eI(n,e,t){let r=n.Ms.get(e)||j.min();t.forEach((s,i)=>{i.readTime.compareTo(r)>0&&(r=i.readTime)}),n.Ms.set(e,r)}async function pR(n,e,t,r){let s=F(n),i=$(),o=yt();for(let u of t){let d=e.Ks(u.metadata.name);u.document&&(i=i.add(d));let p=e.qs(u);p.setReadTime(e.Us(u.metadata.readTime)),o=o.insert(d,p)}let a=s.xs.newChangeBuffer({trackRemovals:!0}),l=await Ti(s,(function(d){return ct(Es(ie.fromString(`__bundle__/docs/${d}`)))})(r));return s.persistence.runTransaction("Apply bundle documents","readwrite",u=>JT(u,a,o).next(d=>(a.apply(u),d)).next(d=>s.li.removeMatchingKeysForTargetId(u,l.targetId).next(()=>s.li.addMatchingKeys(u,i,l.targetId)).next(()=>s.localDocuments.getLocalViewOfDocuments(u,d.Bs,d.Ls)).next(()=>d.Bs)))}async function mR(n,e,t=$()){let r=await Ti(n,ct(Au(e.bundledQuery))),s=F(n);return s.persistence.runTransaction("Save named query","readwrite",i=>{let o=Ne(e.readTime);if(r.snapshotVersion.compareTo(o)>=0)return s.Pi.saveNamedQuery(i,e);let a=r.withResumeToken(Re.EMPTY_BYTE_STRING,o);return s.vs=s.vs.insert(a.targetId,a),s.li.updateTargetData(i,a).next(()=>s.li.removeMatchingKeysForTargetId(i,r.targetId)).next(()=>s.li.addMatchingKeys(i,t,r.targetId)).next(()=>s.Pi.saveNamedQuery(i,e))})}var tI="firestore_clients";function uE(n,e){return`${tI}_${n}_${e}`}var nI="firestore_mutations";function hE(n,e,t){let r=`${nI}_${n}_${t}`;return e.isAuthenticated()&&(r+=`_${e.uid}`),r}var rI="firestore_targets";function ef(n,e){return`${rI}_${n}_${e}`}var an="SharedClientState",Ql=class n{constructor(e,t,r,s){this.user=e,this.batchId=t,this.state=r,this.error=s}static $s(e,t,r){let s=JSON.parse(r),i,o=typeof s=="object"&&["pending","acknowledged","rejected"].indexOf(s.state)!==-1&&(s.error===void 0||typeof s.error=="object");return o&&s.error&&(o=typeof s.error.message=="string"&&typeof s.error.code=="string",o&&(i=new N(s.error.code,s.error.message))),o?new n(e,t,s.state,i):(xe(an,`Failed to parse mutation state for ID '${t}': ${r}`),null)}Ws(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}},ta=class n{constructor(e,t,r){this.targetId=e,this.state=t,this.error=r}static $s(e,t){let r=JSON.parse(t),s,i=typeof r=="object"&&["not-current","current","rejected"].indexOf(r.state)!==-1&&(r.error===void 0||typeof r.error=="object");return i&&r.error&&(i=typeof r.error.message=="string"&&typeof r.error.code=="string",i&&(s=new N(r.error.code,r.error.message))),i?new n(e,r.state,s):(xe(an,`Failed to parse target state for ID '${e}': ${t}`),null)}Ws(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}},Yl=class n{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static $s(e,t){let r=JSON.parse(t),s=typeof r=="object"&&r.activeTargetIds instanceof Array,i=lm();for(let o=0;s&&othis.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ys,JSON.stringify(e))}getAllActiveQueryTargets(){return this.uo(this.Hs)}isActiveQueryTarget(e){let t=!1;return this.Hs.forEach((r,s)=>{s.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.co(e,"pending")}updateMutationState(e,t,r){this.co(e,t,r),this.lo(e)}addLocalQueryTarget(e,t=!0){let r="not-current";if(this.isActiveQueryTarget(e)){let s=this.storage.getItem(ef(this.persistenceKey,e));if(s){let i=ta.$s(e,s);i&&(r=i.state)}}return t&&this.ho.Qs(e),this.oo(),r}removeLocalQueryTarget(e){this.ho.Gs(e),this.oo()}isLocalQueryTarget(e){return this.ho.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(ef(this.persistenceKey,e))}updateQueryState(e,t,r){this.Po(e,t,r)}handleUserChange(e,t,r){t.forEach(s=>{this.lo(s)}),this.currentUser=e,r.forEach(s=>{this.addPendingMutation(s)})}setOnlineState(e){this.To(e)}notifyBundleLoaded(e){this.Io(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.js),this.removeItem(this.Xs),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return D(an,"READ",e,t),t}setItem(e,t){D(an,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){D(an,"REMOVE",e),this.storage.removeItem(e)}Js(e){let t=e;if(t.storageArea===this.storage){if(D(an,"EVENT",t.key,t.newValue),t.key===this.Xs)return void xe("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Ci.enqueueRetryable(async()=>{if(this.started){if(t.key!==null){if(this.eo.test(t.key)){if(t.newValue==null){let r=this.Eo(t.key);return this.Ro(r,null)}{let r=this.Ao(t.key,t.newValue);if(r)return this.Ro(r.clientId,r)}}else if(this.no.test(t.key)){if(t.newValue!==null){let r=this.Vo(t.key,t.newValue);if(r)return this.mo(r)}}else if(this.ro.test(t.key)){if(t.newValue!==null){let r=this.fo(t.key,t.newValue);if(r)return this.po(r)}}else if(t.key===this.io){if(t.newValue!==null){let r=this._o(t.newValue);if(r)return this.ao(r)}}else if(t.key===this.Ys){let r=(function(i){let o=Ct.ce;if(i!=null)try{let a=JSON.parse(i);B(typeof a=="number",30636,{yo:i}),o=a}catch(a){xe(an,"Failed to read sequence number from WebStorage",a)}return o})(t.newValue);r!==Ct.ce&&this.sequenceNumberHandler(r)}else if(t.key===this.so){let r=this.wo(t.newValue);await Promise.all(r.map(s=>this.syncEngine.So(s)))}}}else this.Zs.push(t)})}}get ho(){return this.Hs.get(this.zs)}oo(){this.setItem(this.Xs,this.ho.Ws())}co(e,t,r){let s=new Ql(this.currentUser,e,t,r),i=hE(this.persistenceKey,this.currentUser,e);this.setItem(i,s.Ws())}lo(e){let t=hE(this.persistenceKey,this.currentUser,e);this.removeItem(t)}To(e){let t={clientId:this.zs,onlineState:e};this.storage.setItem(this.io,JSON.stringify(t))}Po(e,t,r){let s=ef(this.persistenceKey,e),i=new ta(e,t,r);this.setItem(s,i.Ws())}Io(e){let t=JSON.stringify(Array.from(e));this.setItem(this.so,t)}Eo(e){let t=this.eo.exec(e);return t?t[1]:null}Ao(e,t){let r=this.Eo(e);return Yl.$s(r,t)}Vo(e,t){let r=this.no.exec(e),s=Number(r[1]),i=r[2]!==void 0?r[2]:null;return Ql.$s(new Le(i),s,t)}fo(e,t){let r=this.ro.exec(e),s=Number(r[1]);return ta.$s(s,t)}_o(e){return gp.$s(e)}wo(e){return JSON.parse(e)}async mo(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.bo(e.batchId,e.state,e.error);D(an,`Ignoring mutation for non-active user ${e.user.uid}`)}po(e){return this.syncEngine.Do(e.targetId,e.state,e.error)}Ro(e,t){let r=t?this.Hs.insert(e,t):this.Hs.remove(e),s=this.uo(this.Hs),i=this.uo(r),o=[],a=[];return i.forEach(l=>{s.has(l)||o.push(l)}),s.forEach(l=>{i.has(l)||a.push(l)}),this.syncEngine.Co(o,a).then(()=>{this.Hs=r})}ao(e){this.Hs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}uo(e){let t=lm();return e.forEach((r,s)=>{t=t.unionWith(s.activeTargetIds)}),t}},Jl=class{constructor(){this.vo=new Ea,this.Fo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.vo.Qs(e),this.Fo[e]||"not-current"}updateQueryState(e,t,r){this.Fo[e]=t}removeLocalQueryTarget(e){this.vo.Gs(e)}isLocalQueryTarget(e){return this.vo.activeTargetIds.has(e)}clearQueryState(e){delete this.Fo[e]}getAllActiveQueryTargets(){return this.vo.activeTargetIds}isActiveQueryTarget(e){return this.vo.activeTargetIds.has(e)}start(){return this.vo=new Ea,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var _p=class{Mo(e){}shutdown(){}};var dE="ConnectivityMonitor",Xl=class{constructor(){this.xo=()=>this.Oo(),this.No=()=>this.Bo(),this.Lo=[],this.ko()}Mo(e){this.Lo.push(e)}shutdown(){window.removeEventListener("online",this.xo),window.removeEventListener("offline",this.No)}ko(){window.addEventListener("online",this.xo),window.addEventListener("offline",this.No)}Oo(){D(dE,"Network connectivity changed: AVAILABLE");for(let e of this.Lo)e(0)}Bo(){D(dE,"Network connectivity changed: UNAVAILABLE");for(let e of this.Lo)e(1)}static v(){return typeof window<"u"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}};var ol=null;function yp(){return ol===null?ol=(function(){return 268435456+Math.round(2147483648*Math.random())})():ol++,"0x"+ol.toString(16)}var tf="RestConnection",gR={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"},vp=class{get Ko(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.qo=t+"://"+e.host,this.Uo=`projects/${r}/databases/${s}`,this.$o=this.databaseId.database===_f?`project_id=${r}`:`project_id=${r}&database_id=${s}`}Wo(e,t,r,s,i){let o=yp(),a=this.Qo(e,t.toUriEncodedString());D(tf,`Sending RPC '${e}' ${o}:`,a,r);let l={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.$o};this.Go(l,s,i);let{host:u}=new URL(a),d=Ws(u);return this.zo(e,a,l,r,d).then(p=>(D(tf,`Received RPC '${e}' ${o}: `,p),p),p=>{throw vt(tf,`RPC '${e}' ${o} failed with error: `,p,"url: ",a,"request:",r),p})}jo(e,t,r,s,i,o){return this.Wo(e,t,r,s,i)}Go(e,t,r){e["X-Goog-Api-Client"]=(function(){return"gl-js/ fire/"+Ri})(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((s,i)=>e[i]=s),r&&r.headers.forEach((s,i)=>e[i]=s)}Qo(e,t){let r=gR[e],s=`${this.qo}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(s=`${s}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),s}terminate(){}};var wp=class{constructor(e){this.Jo=e.Jo,this.Ho=e.Ho}Zo(e){this.Xo=e}Yo(e){this.e_=e}t_(e){this.n_=e}onMessage(e){this.r_=e}close(){this.Ho()}send(e){this.Jo(e)}i_(){this.Xo()}s_(){this.e_()}o_(e){this.n_(e)}__(e){this.r_(e)}};var nt="WebChannelConnection",Wo=(n,e,t)=>{n.listen(e,r=>{try{t(r)}catch(s){setTimeout(()=>{throw s},0)}})},Zl=class n extends vp{constructor(e){super(e),this.a_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static u_(){if(!n.c_){let e=$d();Wo(e,Wd.STAT_EVENT,t=>{t.stat===tl.PROXY?D(nt,"STAT_EVENT: detected buffering proxy"):t.stat===tl.NOPROXY&&D(nt,"STAT_EVENT: detected no buffering proxy")}),n.c_=!0}}zo(e,t,r,s,i){let o=yp();return new Promise((a,l)=>{let u=new zd;u.setWithCredentials(!0),u.listenOnce(Kd.COMPLETE,()=>{try{switch(u.getLastErrorCode()){case qo.NO_ERROR:let p=u.getResponseJson();D(nt,`XHR for RPC '${e}' ${o} received:`,JSON.stringify(p)),a(p);break;case qo.TIMEOUT:D(nt,`RPC '${e}' ${o} timed out`),l(new N(R.DEADLINE_EXCEEDED,"Request time out"));break;case qo.HTTP_ERROR:let m=u.getStatus();if(D(nt,`RPC '${e}' ${o} failed with status:`,m,"response text:",u.getResponseText()),m>0){let v=u.getResponseJson();Array.isArray(v)&&(v=v[0]);let S=v?.error;if(S&&S.status&&S.message){let x=(function(q){let G=q.toLowerCase().replace(/_/g,"-");return Object.values(R).indexOf(G)>=0?G:R.UNKNOWN})(S.status);l(new N(x,S.message))}else l(new N(R.UNKNOWN,"Server responded with status "+u.getStatus()))}else l(new N(R.UNAVAILABLE,"Connection failed."));break;default:U(9055,{l_:e,streamId:o,h_:u.getLastErrorCode(),P_:u.getLastError()})}}finally{D(nt,`RPC '${e}' ${o} completed.`)}});let d=JSON.stringify(s);D(nt,`RPC '${e}' ${o} sending request:`,s),u.send(t,"POST",d,r,15)})}T_(e,t,r){let s=yp(),i=[this.qo,"/","google.firestore.v1.Firestore","/",e,"/channel"],o=this.createWebChannelTransport(),a={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},l=this.longPollingOptions.timeoutSeconds;l!==void 0&&(a.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Go(a.initMessageHeaders,t,r),a.encodeInitMessageHeaders=!0;let u=i.join("");D(nt,`Creating RPC '${e}' stream ${s}: ${u}`,a);let d=o.createWebChannel(u,a);this.I_(d);let p=!1,m=!1,v=new wp({Jo:S=>{m?D(nt,`Not sending because RPC '${e}' stream ${s} is closed:`,S):(p||(D(nt,`Opening RPC '${e}' stream ${s} transport.`),d.open(),p=!0),D(nt,`RPC '${e}' stream ${s} sending:`,S),d.send(S))},Ho:()=>d.close()});return Wo(d,Hs.EventType.OPEN,()=>{m||(D(nt,`RPC '${e}' stream ${s} transport opened.`),v.i_())}),Wo(d,Hs.EventType.CLOSE,()=>{m||(m=!0,D(nt,`RPC '${e}' stream ${s} transport closed`),v.o_(),this.E_(d))}),Wo(d,Hs.EventType.ERROR,S=>{m||(m=!0,vt(nt,`RPC '${e}' stream ${s} transport errored. Name:`,S.name,"Message:",S.message),v.o_(new N(R.UNAVAILABLE,"The operation could not be completed")))}),Wo(d,Hs.EventType.MESSAGE,S=>{if(!m){let x=S.data[0];B(!!x,16349);let k=x,q=k?.error||k[0]?.error;if(q){D(nt,`RPC '${e}' stream ${s} received error:`,q);let G=q.status,L=(function(oe){let E=Me[oe];if(E!==void 0)return AT(E)})(G),H=q.message;G==="NOT_FOUND"&&H.includes("database")&&H.includes("does not exist")&&H.includes(this.databaseId.database)&&vt(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),L===void 0&&(L=R.INTERNAL,H="Unknown error status: "+G+" with message "+q.message),m=!0,v.o_(new N(L,H)),d.close()}else D(nt,`RPC '${e}' stream ${s} received:`,x),v.__(x)}}),n.u_(),setTimeout(()=>{v.s_()},0),v}terminate(){this.a_.forEach(e=>e.close()),this.a_=[]}I_(e){this.a_.push(e)}E_(e){this.a_=this.a_.filter(t=>t===e)}Go(e,t,r){super.Go(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return Hd()}};function _R(n){return new Zl(n)}function sI(){return typeof window<"u"?window:null}function pl(){return typeof document<"u"?document:null}function xi(n){return new Of(n,!0)}Zl.c_=!1;var Ta=class{constructor(e,t,r=1e3,s=1.5,i=6e4){this.Ci=e,this.timerId=t,this.R_=r,this.A_=s,this.V_=i,this.d_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.d_=0}g_(){this.d_=this.V_}p_(e){this.cancel();let t=Math.floor(this.d_+this.y_()),r=Math.max(0,Date.now()-this.f_),s=Math.max(0,t-r);s>0&&D("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.d_} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.m_=this.Ci.enqueueAfterDelay(this.timerId,s,()=>(this.f_=Date.now(),e())),this.d_*=this.A_,this.d_this.V_&&(this.d_=this.V_)}w_(){this.m_!==null&&(this.m_.skipDelay(),this.m_=null)}cancel(){this.m_!==null&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.d_}};var fE="PersistentStream",eu=class{constructor(e,t,r,s,i,o,a,l){this.Ci=e,this.S_=r,this.b_=s,this.connection=i,this.authCredentialsProvider=o,this.appCheckCredentialsProvider=a,this.listener=l,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new Ta(e,t)}x_(){return this.state===1||this.state===5||this.O_()}O_(){return this.state===2||this.state===3}start(){this.F_=0,this.state!==4?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&this.C_===null&&(this.C_=this.Ci.enqueueAfterDelay(this.S_,6e4,()=>this.k_()))}K_(e){this.q_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}q_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.U_(),this.M_.cancel(),this.D_++,e!==4?this.M_.reset():t&&t.code===R.RESOURCE_EXHAUSTED?(xe(t.toString()),xe("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===R.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.t_(t)}W_(){}auth(){this.state=1;let e=this.Q_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([r,s])=>{this.D_===t&&this.G_(r,s)},r=>{e(()=>{let s=new N(R.UNKNOWN,"Fetching auth token failed: "+r.message);return this.z_(s)})})}G_(e,t){let r=this.Q_(this.D_);this.stream=this.j_(e,t),this.stream.Zo(()=>{r(()=>this.listener.Zo())}),this.stream.Yo(()=>{r(()=>(this.state=2,this.v_=this.Ci.enqueueAfterDelay(this.b_,1e4,()=>(this.O_()&&(this.state=3),Promise.resolve())),this.listener.Yo()))}),this.stream.t_(s=>{r(()=>this.z_(s))}),this.stream.onMessage(s=>{r(()=>++this.F_==1?this.J_(s):this.onNext(s))})}N_(){this.state=5,this.M_.p_(async()=>{this.state=0,this.start()})}z_(e){return D(fE,`close with error: ${e}`),this.stream=null,this.close(4,e)}Q_(e){return t=>{this.Ci.enqueueAndForget(()=>this.D_===e?t():(D(fE,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}},Ep=class extends eu{constructor(e,t,r,s,i,o){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,s,o),this.serializer=i}j_(e,t){return this.connection.T_("Listen",e,t)}J_(e){return this.onNext(e)}onNext(e){this.M_.reset();let t=Z0(this.serializer,e),r=(function(i){if(!("targetChange"in i))return j.min();let o=i.targetChange;return o.targetIds&&o.targetIds.length?j.min():o.readTime?Ne(o.readTime):j.min()})(e);return this.listener.H_(t,r)}Z_(e){let t={};t.database=Lf(this.serializer),t.addTarget=(function(i,o){let a,l=o.target;if(a=xl(l)?{documents:kT(i,l)}:{query:NT(i,l).ft},a.targetId=o.targetId,o.resumeToken.approximateByteSize()>0){a.resumeToken=CT(i,o.resumeToken);let u=Mf(i,o.expectedCount);u!==null&&(a.expectedCount=u)}else if(o.snapshotVersion.compareTo(j.min())>0){a.readTime=Ei(i,o.snapshotVersion.toTimestamp());let u=Mf(i,o.expectedCount);u!==null&&(a.expectedCount=u)}return a})(this.serializer,e);let r=tR(this.serializer,e);r&&(t.labels=r),this.K_(t)}X_(e){let t={};t.database=Lf(this.serializer),t.removeTarget=e,this.K_(t)}},Tp=class extends eu{constructor(e,t,r,s,i,o){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,s,o),this.serializer=i}get Y_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.Y_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}J_(e){return B(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,B(!e.writeResults||e.writeResults.length===0,55816),this.listener.ta()}onNext(e){B(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();let t=eR(e.writeResults,e.commitTime),r=Ne(e.commitTime);return this.listener.na(r,t)}ra(){let e={};e.database=Lf(this.serializer),this.K_(e)}ea(e){let t={streamToken:this.lastStreamToken,writes:e.map(r=>_a(this.serializer,r))};this.K_(t)}};var Ip=class{},Ap=class extends Ip{constructor(e,t,r,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=s,this.ia=!1}sa(){if(this.ia)throw new N(R.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,r,s){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,o])=>this.connection.Wo(e,Ff(t,r),s,i,o)).catch(i=>{throw i.name==="FirebaseError"?(i.code===R.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new N(R.UNKNOWN,i.toString())})}jo(e,t,r,s,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([o,a])=>this.connection.jo(e,Ff(t,r),s,o,a,i)).catch(o=>{throw o.name==="FirebaseError"?(o.code===R.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),o):new N(R.UNKNOWN,o.toString())})}terminate(){this.ia=!0,this.connection.terminate()}};function yR(n,e,t,r){return new Ap(n,e,t,r)}var bp=class{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){this.oa===0&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve())))}ha(e){this.state==="Online"?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,e==="Online"&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(e){let t=`Could not reach Cloud Firestore backend. ${e} This 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.aa?(xe(t),this.aa=!1):D("OnlineStateTracker",t)}Pa(){this._a!==null&&(this._a.cancel(),this._a=null)}};var pn="RemoteStore",Cp=class{constructor(e,t,r,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.Ta=[],this.Ia=new Map,this.Ea=new Map,this.Ra=new Map,this.Aa=new yr(1e3),this.Va=new yr(1001),this.da=new Set,this.ma=[],this.fa=i,this.fa.Mo(o=>{r.enqueueAndForget(async()=>{Sr(this)&&(D(pn,"Restarting streams for network reachability change."),await(async function(l){let u=F(l);u.da.add(4),await ki(u),u.ga.set("Unknown"),u.da.delete(4),await Va(u)})(this))})}),this.ga=new bp(r,s)}};async function Va(n){if(Sr(n))for(let e of n.ma)await e(!0)}async function ki(n){for(let e of n.ma)await e(!1)}function Sp(n,e){return n.Ea.get(e)||void 0}function bu(n,e){let t=F(n),r=Sp(t,e.targetId);if(r!==void 0&&t.Ia.has(r))return;let s=(function(a,l){let u=Sp(a,l);u!==void 0&&a.Ra.delete(u);let d=(function(m,v){return v%2!=0?m.Va.next():m.Aa.next()})(a,l);return a.Ea.set(l,d),a.Ra.set(d,l),d})(t,e.targetId);D(pn,"remoteStoreListen mapping SDK target ID to remote",e.targetId,s);let i=new gs(e.target,s,e.purpose,e.sequenceNumber,e.snapshotVersion,e.lastLimboFreeSnapshotVersion,e.resumeToken);t.Ia.set(s,i),ym(t)?_m(t):Di(t).O_()&&gm(t,i)}function Ai(n,e){let t=F(n),r=Di(t),s=Sp(t,e);D(pn,"remoteStoreUnlisten removing mapping of SDK target ID to remote",e,s),t.Ia.delete(s),t.Ea.delete(e),t.Ra.delete(s),r.O_()&&iI(t,s),t.Ia.size===0&&(r.O_()?r.L_():Sr(t)&&t.ga.set("Unknown"))}function gm(n,e){if(n.pa.$e(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(j.min())>0){let t=n.Ra.get(e.targetId);if(t===void 0)return void D(pn,"SDK target ID not found for remote ID: "+e.targetId);let r=n.remoteSyncer.getRemoteKeysForTarget(t).size;e=e.withExpectedCount(r)}Di(n).Z_(e)}function iI(n,e){n.pa.$e(e),Di(n).X_(e)}function _m(n){n.pa=new Vf({getRemoteKeysForTarget:e=>{let t=n.Ra.get(e);return t!==void 0?n.remoteSyncer.getRemoteKeysForTarget(t):$()},At:e=>n.Ia.get(e)||null,ht:()=>n.datastore.serializer.databaseId}),Di(n).start(),n.ga.ua()}function ym(n){return Sr(n)&&!Di(n).x_()&&n.Ia.size>0}function Sr(n){return F(n).da.size===0}function oI(n){n.pa=void 0}async function vR(n){n.ga.set("Online")}async function wR(n){n.Ia.forEach((e,t)=>{gm(n,e)})}async function ER(n,e){oI(n),ym(n)?(n.ga.ha(e),_m(n)):n.ga.set("Unknown")}async function TR(n,e,t){if(n.ga.set("Online"),e instanceof Dl&&e.state===2&&e.cause)try{await(async function(s,i){let o=i.cause;for(let a of i.targetIds){if(s.Ia.has(a)){let l=s.Ra.get(a);l!==void 0&&(await s.remoteSyncer.rejectListen(l,o),s.Ea.delete(l),s.Ra.delete(a)),s.Ia.delete(a)}s.pa.removeTarget(a)}})(n,e)}catch(r){D(pn,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await tu(n,r)}else if(e instanceof ai?n.pa.Xe(e):e instanceof Nl?n.pa.st(e):n.pa.tt(e),!t.isEqual(j.min()))try{let r=await YT(n.localStore);t.compareTo(r)>=0&&await(function(i,o){let a=i.pa.Tt(o);a.targetChanges.forEach((u,d)=>{if(u.resumeToken.approximateByteSize()>0){let p=i.Ia.get(d);p&&i.Ia.set(d,p.withResumeToken(u.resumeToken,o))}}),a.targetMismatches.forEach((u,d)=>{let p=i.Ia.get(u);if(!p)return;i.Ia.set(u,p.withResumeToken(Re.EMPTY_BYTE_STRING,p.snapshotVersion)),iI(i,u);let m=new gs(p.target,u,d,p.sequenceNumber);gm(i,m)});let l=(function(d,p){let m=new Map;p.targetChanges.forEach((S,x)=>{let k=d.Ra.get(x);k!==void 0&&m.set(k,S)});let v=new ye(W);return p.targetMismatches.forEach((S,x)=>{let k=d.Ra.get(S);k!==void 0&&(v=v.insert(k,x))}),new wi(p.snapshotVersion,m,v,p.documentUpdates,p.resolvedLimboDocuments)})(i,a);return i.remoteSyncer.applyRemoteEvent(l)})(n,t)}catch(r){D(pn,"Failed to raise snapshot:",r),await tu(n,r)}}async function tu(n,e,t){if(!Ar(e))throw e;n.da.add(1),await ki(n),n.ga.set("Offline"),t||(t=()=>YT(n.localStore)),n.asyncQueue.enqueueRetryable(async()=>{D(pn,"Retrying IndexedDB access"),await t(),n.da.delete(1),await Va(n)})}function aI(n,e){return e().catch(t=>tu(n,t,e))}async function Ni(n){let e=F(n),t=vr(e),r=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:lr;for(;IR(e);)try{let s=await fR(e.localStore,r);if(s===null){e.Ta.length===0&&t.L_();break}r=s.batchId,AR(e,s)}catch(s){await tu(e,s)}cI(e)&&lI(e)}function IR(n){return Sr(n)&&n.Ta.length<10}function AR(n,e){n.Ta.push(e);let t=vr(n);t.O_()&&t.Y_&&t.ea(e.mutations)}function cI(n){return Sr(n)&&!vr(n).x_()&&n.Ta.length>0}function lI(n){vr(n).start()}async function bR(n){vr(n).ra()}async function CR(n){let e=vr(n);for(let t of n.Ta)e.ea(t.mutations)}async function SR(n,e,t){let r=n.Ta.shift(),s=kf.from(r,e,t);await aI(n,()=>n.remoteSyncer.applySuccessfulWrite(s)),await Ni(n)}async function RR(n,e){e&&vr(n).Y_&&await(async function(r,s){if((function(o){return IT(o)&&o!==R.ABORTED})(s.code)){let i=r.Ta.shift();vr(r).B_(),await aI(r,()=>r.remoteSyncer.rejectFailedWrite(i.batchId,s)),await Ni(r)}})(n,e),cI(n)&&lI(n)}async function pE(n,e){let t=F(n);t.asyncQueue.verifyOperationInProgress(),D(pn,"RemoteStore received new credentials");let r=Sr(t);t.da.add(3),await ki(t),r&&t.ga.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.da.delete(3),await Va(t)}async function Rp(n,e){let t=F(n);e?(t.da.delete(2),await Va(t)):e||(t.da.add(2),await ki(t),t.ga.set("Unknown"))}function Di(n){return n.ya||(n.ya=(function(t,r,s){let i=F(t);return i.sa(),new Ep(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(n.datastore,n.asyncQueue,{Zo:vR.bind(null,n),Yo:wR.bind(null,n),t_:ER.bind(null,n),H_:TR.bind(null,n)}),n.ma.push(async e=>{e?(n.ya.B_(),ym(n)?_m(n):n.ga.set("Unknown")):(await n.ya.stop(),oI(n))})),n.ya}function vr(n){return n.wa||(n.wa=(function(t,r,s){let i=F(t);return i.sa(),new Tp(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(n.datastore,n.asyncQueue,{Zo:()=>Promise.resolve(),Yo:bR.bind(null,n),t_:RR.bind(null,n),ta:CR.bind(null,n),na:SR.bind(null,n)}),n.ma.push(async e=>{e?(n.wa.B_(),await Ni(n)):(await n.wa.stop(),n.Ta.length>0&&(D(pn,`Stopping write stream with ${n.Ta.length} pending writes`),n.Ta=[]))})),n.wa}var Pp=class n{constructor(e,t,r,s,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=s,this.removalCallback=i,this.deferred=new ze,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(o=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,r,s,i){let o=Date.now()+r,a=new n(e,t,o,s,i);return a.start(r),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new N(R.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}};function Vi(n,e){if(xe("AsyncQueue",`${e}: ${n}`),Ar(n))return new N(R.UNAVAILABLE,`${e}: ${n}`);throw n}var Ia=class n{static emptySet(e){return new n(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||O.comparator(t.key,r.key):(t,r)=>O.comparator(t.key,r.key),this.keyedMap=$o(),this.sortedSet=new ye(this.comparator)}has(e){return this.keyedMap.get(e)!=null}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,r)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof n)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=r.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),e.length===0?"DocumentSet ()":`DocumentSet ( `+e.join(` `)+` )`}copy(e,t){let r=new n;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}};var nu=class{constructor(){this.Sa=new ye(O.comparator)}track(e){let t=e.doc.key,r=this.Sa.get(t);r?e.type!==0&&r.type===3?this.Sa=this.Sa.insert(t,e):e.type===3&&r.type!==1?this.Sa=this.Sa.insert(t,{type:r.type,doc:e.doc}):e.type===2&&r.type===2?this.Sa=this.Sa.insert(t,{type:2,doc:e.doc}):e.type===2&&r.type===0?this.Sa=this.Sa.insert(t,{type:0,doc:e.doc}):e.type===1&&r.type===0?this.Sa=this.Sa.remove(t):e.type===1&&r.type===2?this.Sa=this.Sa.insert(t,{type:1,doc:r.doc}):e.type===0&&r.type===1?this.Sa=this.Sa.insert(t,{type:2,doc:e.doc}):U(63341,{Vt:e,ba:r}):this.Sa=this.Sa.insert(t,e)}Da(){let e=[];return this.Sa.inorderTraversal((t,r)=>{e.push(r)}),e}},vs=class n{constructor(e,t,r,s,i,o,a,l,u){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=s,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=a,this.excludesMetadataChanges=l,this.hasCachedResults=u}static fromInitialDocuments(e,t,r,s,i){let o=[];return t.forEach(a=>{o.push({type:0,doc:a})}),new n(e,t,Ia.emptySet(t),o,r,s,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Na(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let s=0;se.Ma())}},kp=class{constructor(){this.queries=mE(),this.onlineState="Unknown",this.xa=new Set}terminate(){(function(t,r){let s=F(t),i=s.queries;s.queries=mE(),i.forEach((o,a)=>{for(let l of a.va)l.onError(r)})})(this,new N(R.ABORTED,"Firestore shutting down"))}};function mE(){return new $t(n=>lT(n),Na)}async function vm(n,e){let t=F(n),r=3,s=e.query,i=t.queries.get(s);i?!i.Fa()&&e.Ma()&&(r=2):(i=new xp,r=e.Ma()?0:1);try{switch(r){case 0:i.Ca=await t.onListen(s,!0);break;case 1:i.Ca=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(o){let a=Vi(o,`Initialization of query '${ni(e.query)}' failed`);return void e.onError(a)}t.queries.set(s,i),i.va.push(e),e.Oa(t.onlineState),i.Ca&&e.Na(i.Ca)&&Em(t)}async function wm(n,e){let t=F(n),r=e.query,s=3,i=t.queries.get(r);if(i){let o=i.va.indexOf(e);o>=0&&(i.va.splice(o,1),i.va.length===0?s=e.Ma()?0:1:!i.Fa()&&e.Ma()&&(s=2))}switch(s){case 0:return t.queries.delete(r),t.onUnlisten(r,!0);case 1:return t.queries.delete(r),t.onUnlisten(r,!1);case 2:return t.onLastRemoteStoreUnlisten(r);default:return}}function PR(n,e){let t=F(n),r=!1;for(let s of e){let i=s.query,o=t.queries.get(i);if(o){for(let a of o.va)a.Na(s)&&(r=!0);o.Ca=s}}r&&Em(t)}function xR(n,e,t){let r=F(n),s=r.queries.get(e);if(s)for(let i of s.va)i.onError(t);r.queries.delete(e)}function Em(n){n.xa.forEach(e=>{e.next()})}var Np,gE;(gE=Np||(Np={})).Ba="default",gE.Cache="cache";var Aa=class{constructor(e,t,r){this.query=e,this.La=t,this.ka=!1,this.Ka=null,this.onlineState="Unknown",this.options=r||{}}Na(e){if(!this.options.includeMetadataChanges){let r=[];for(let s of e.docChanges)s.type!==3&&r.push(s);e=new vs(e.query,e.docs,e.oldDocs,r,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ka?this.qa(e)&&(this.La.next(e),t=!0):this.Ua(e,this.onlineState)&&(this.$a(e),t=!0),this.Ka=e,t}onError(e){this.La.error(e)}Oa(e){this.onlineState=e;let t=!1;return this.Ka&&!this.ka&&this.Ua(this.Ka,e)&&(this.$a(this.Ka),t=!0),t}Ua(e,t){if(!e.fromCache||!this.Ma())return!0;let r=t!=="Offline";return(!this.options.Wa||!r)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}qa(e){if(e.docChanges.length>0)return!0;let t=this.Ka&&this.Ka.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}$a(e){e=vs.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ka=!0,this.La.next(e)}Ma(){return this.options.source!==Np.Cache}};var Dp=class{constructor(e,t){this.Qa=e,this.byteLength=t}Ga(){return"metadata"in this.Qa}};var ru=class{constructor(e){this.serializer=e}Ks(e){return hn(this.serializer,e)}qs(e){return e.metadata.exists?dm(this.serializer,e.document,!1):Ue.newNoDocument(this.Ks(e.metadata.name),this.Us(e.metadata.readTime))}Us(e){return Ne(e)}},su=class{constructor(e,t){this.za=e,this.serializer=t,this.ja=[],this.Ja=[],this.collectionGroups=new Set,this.progress=uI(e)}get queries(){return this.ja}get documents(){return this.Ja}Ha(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.Qa.namedQuery)this.ja.push(e.Qa.namedQuery);else if(e.Qa.documentMetadata){this.Ja.push({metadata:e.Qa.documentMetadata}),e.Qa.documentMetadata.exists||++t;let r=ie.fromString(e.Qa.documentMetadata.name);this.collectionGroups.add(r.get(r.length-2))}else e.Qa.document&&(this.Ja[this.Ja.length-1].document=e.Qa.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Q({},this.progress)):null}Za(e){let t=new Map,r=new ru(this.serializer);for(let s of e)if(s.metadata.queries){let i=r.Ks(s.metadata.name);for(let o of s.metadata.queries){let a=(t.get(o)||$()).add(i);t.set(o,a)}}return t}async Xa(e){let t=await pR(e,new ru(this.serializer),this.Ja,this.za.id),r=this.Za(this.documents);for(let s of this.ja)await mR(e,s,r.get(s.name));return this.progress.taskState="Success",{progress:this.progress,Ya:this.collectionGroups,eu:t}}};function uI(n){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:n.totalDocuments,totalBytes:n.totalBytes}}var iu=class{constructor(e){this.key=e}},ou=class{constructor(e){this.key=e}},au=class{constructor(e,t){this.query=e,this.tu=t,this.nu=null,this.hasCachedResults=!1,this.current=!1,this.ru=$(),this.mutatedKeys=$(),this.iu=hT(e),this.su=new Ia(this.iu)}get ou(){return this.tu}_u(e,t){let r=t?t.au:new nu,s=t?t.su:this.su,i=t?t.mutatedKeys:this.mutatedKeys,o=s,a=!1,l=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,u=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((d,p)=>{let m=s.get(d),v=Da(this.query,p)?p:null,S=!!m&&this.mutatedKeys.has(m.key),x=!!v&&(v.hasLocalMutations||this.mutatedKeys.has(v.key)&&v.hasCommittedMutations),k=!1;m&&v?m.data.isEqual(v.data)?S!==x&&(r.track({type:3,doc:v}),k=!0):this.uu(m,v)||(r.track({type:2,doc:v}),k=!0,(l&&this.iu(v,l)>0||u&&this.iu(v,u)<0)&&(a=!0)):!m&&v?(r.track({type:0,doc:v}),k=!0):m&&!v&&(r.track({type:1,doc:m}),k=!0,(l||u)&&(a=!0)),k&&(v?(o=o.add(v),i=x?i.add(d):i.delete(d)):(o=o.delete(d),i=i.delete(d)))}),this.query.limit!==null)for(;o.size>this.query.limit;){let d=this.query.limitType==="F"?o.last():o.first();o=o.delete(d.key),i=i.delete(d.key),r.track({type:1,doc:d})}return{su:o,au:r,bs:a,mutatedKeys:i}}uu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,s){let i=this.su;this.su=e.su,this.mutatedKeys=e.mutatedKeys;let o=e.au.Da();o.sort((d,p)=>(function(v,S){let x=k=>{switch(k){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return U(20277,{Vt:k})}};return x(v)-x(S)})(d.type,p.type)||this.iu(d.doc,p.doc)),this.cu(r),s=s??!1;let a=t&&!s?this.lu():[],l=this.ru.size===0&&this.current&&!s?1:0,u=l!==this.nu;return this.nu=l,o.length!==0||u?{snapshot:new vs(this.query,e.su,i,o,e.mutatedKeys,l===0,u,!1,!!r&&r.resumeToken.approximateByteSize()>0),hu:a}:{hu:a}}Oa(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({su:this.su,au:new nu,mutatedKeys:this.mutatedKeys,bs:!1},!1)):{hu:[]}}Pu(e){return!this.tu.has(e)&&!!this.su.has(e)&&!this.su.get(e).hasLocalMutations}cu(e){e&&(e.addedDocuments.forEach(t=>this.tu=this.tu.add(t)),e.modifiedDocuments.forEach(t=>{}),e.removedDocuments.forEach(t=>this.tu=this.tu.delete(t)),this.current=e.current)}lu(){if(!this.current)return[];let e=this.ru;this.ru=$(),this.su.forEach(r=>{this.Pu(r.key)&&(this.ru=this.ru.add(r.key))});let t=[];return e.forEach(r=>{this.ru.has(r)||t.push(new ou(r))}),this.ru.forEach(r=>{e.has(r)||t.push(new iu(r))}),t}Tu(e){this.tu=e.ks,this.ru=$();let t=this._u(e.documents);return this.applyChanges(t,!0)}Iu(){return vs.fromInitialDocuments(this.query,this.su,this.mutatedKeys,this.nu===0,this.hasCachedResults)}},Rr="SyncEngine",Vp=class{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}},Op=class{constructor(e){this.key=e,this.Eu=!1}},Mp=class{constructor(e,t,r,s,i,o){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=o,this.Ru={},this.Au=new $t(a=>lT(a),Na),this.Vu=new Map,this.du=new Set,this.mu=new ye(O.comparator),this.fu=new Map,this.gu=new va,this.pu={},this.yu=new Map,this.wu=yr.ar(),this.onlineState="Unknown",this.Su=void 0}get isPrimaryClient(){return this.Su===!0}};async function kR(n,e,t=!0){let r=Cu(n),s,i=r.Au.get(e);return i?(r.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Iu()):s=await hI(r,e,t,!0),s}async function NR(n,e){let t=Cu(n);await hI(t,e,!0,!1)}async function hI(n,e,t,r){let s=await Ti(n.localStore,ct(e)),i=s.targetId,o=n.sharedClientState.addLocalQueryTarget(i,t),a;return r&&(a=await Tm(n,e,i,o==="current",s.resumeToken)),n.isPrimaryClient&&t&&bu(n.remoteStore,s),a}async function Tm(n,e,t,r,s){n.bu=(p,m,v)=>(async function(x,k,q,G){let L=k.view._u(q);L.bs&&(L=await Hl(x.localStore,k.query,!1).then(({documents:E})=>k.view._u(E,L)));let H=G&&G.targetChanges.get(k.targetId),J=G&&G.targetMismatches.get(k.targetId)!=null,oe=k.view.applyChanges(L,x.isPrimaryClient,H,J);return Fp(x,k.targetId,oe.hu),oe.snapshot})(n,p,m,v);let i=await Hl(n.localStore,e,!0),o=new au(e,i.ks),a=o._u(i.documents),l=ma.createSynthesizedTargetChangeForCurrentChange(t,r&&n.onlineState!=="Offline",s),u=o.applyChanges(a,n.isPrimaryClient,l);Fp(n,t,u.hu);let d=new Vp(e,t,o);return n.Au.set(e,d),n.Vu.has(t)?n.Vu.get(t).push(e):n.Vu.set(t,[e]),u.snapshot}async function DR(n,e,t){let r=F(n),s=r.Au.get(e),i=r.Vu.get(s.targetId);if(i.length>1)return r.Vu.set(s.targetId,i.filter(o=>!Na(o,e))),void r.Au.delete(e);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(s.targetId),r.sharedClientState.isActiveQueryTarget(s.targetId)||await Ii(r.localStore,s.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(s.targetId),t&&Ai(r.remoteStore,s.targetId),bi(r,s.targetId)}).catch(Ir)):(bi(r,s.targetId),await Ii(r.localStore,s.targetId,!0))}async function VR(n,e){let t=F(n),r=t.Au.get(e),s=t.Vu.get(r.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(r.targetId),Ai(t.remoteStore,r.targetId))}async function OR(n,e,t){let r=Cm(n);try{let s=await(function(o,a){let l=F(o),u=me.now(),d=a.reduce((v,S)=>v.add(S.key),$()),p,m;return l.persistence.runTransaction("Locally write mutations","readwrite",v=>{let S=yt(),x=$();return l.xs.getEntries(v,d).next(k=>{S=k,S.forEach((q,G)=>{G.isValidDocument()||(x=x.add(q))})}).next(()=>l.localDocuments.getOverlayedDocuments(v,S)).next(k=>{p=k;let q=[];for(let G of a){let L=K0(G,p.get(G.key).overlayedDocument);L!=null&&q.push(new Ht(G.key,L,ZE(L.value.mapValue),Ae.exists(!0)))}return l.mutationQueue.addMutationBatch(v,u,q,a)}).next(k=>{m=k;let q=k.applyToLocalDocumentSet(p,x);return l.documentOverlayCache.saveOverlays(v,k.batchId,q)})}).then(()=>({batchId:m.batchId,changes:fT(p)}))})(r.localStore,e);r.sharedClientState.addPendingMutation(s.batchId),(function(o,a,l){let u=o.pu[o.currentUser.toKey()];u||(u=new ye(W)),u=u.insert(a,l),o.pu[o.currentUser.toKey()]=u})(r,s.batchId,t),await Fn(r,s.changes),await Ni(r.remoteStore)}catch(s){let i=Vi(s,"Failed to persist write");t.reject(i)}}async function dI(n,e){let t=F(n);try{let r=await dR(t.localStore,e);e.targetChanges.forEach((s,i)=>{let o=t.fu.get(i);o&&(B(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?o.Eu=!0:s.modifiedDocuments.size>0?B(o.Eu,14607):s.removedDocuments.size>0&&(B(o.Eu,42227),o.Eu=!1))}),await Fn(t,r,e)}catch(r){await Ir(r)}}function _E(n,e,t){let r=F(n);if(r.isPrimaryClient&&t===0||!r.isPrimaryClient&&t===1){let s=[];r.Au.forEach((i,o)=>{let a=o.view.Oa(e);a.snapshot&&s.push(a.snapshot)}),(function(o,a){let l=F(o);l.onlineState=a;let u=!1;l.queries.forEach((d,p)=>{for(let m of p.va)m.Oa(a)&&(u=!0)}),u&&Em(l)})(r.eventManager,e),s.length&&r.Ru.H_(s),r.onlineState=e,r.isPrimaryClient&&r.sharedClientState.setOnlineState(e)}}async function MR(n,e,t){let r=F(n);r.sharedClientState.updateQueryState(e,"rejected",t);let s=r.fu.get(e),i=s&&s.key;if(i){let o=new ye(O.comparator);o=o.insert(i,Ue.newNoDocument(i,j.min()));let a=$().add(i),l=new wi(j.min(),new Map,new ye(W),o,a);await dI(r,l),r.mu=r.mu.remove(i),r.fu.delete(e),bm(r)}else await Ii(r.localStore,e,!1).then(()=>bi(r,e,t)).catch(Ir)}async function FR(n,e){let t=F(n),r=e.batch.batchId;try{let s=await hR(t.localStore,e);Am(t,r,null),Im(t,r),t.sharedClientState.updateMutationState(r,"acknowledged"),await Fn(t,s)}catch(s){await Ir(s)}}async function LR(n,e,t){let r=F(n);try{let s=await(function(o,a){let l=F(o);return l.persistence.runTransaction("Reject batch","readwrite-primary",u=>{let d;return l.mutationQueue.lookupMutationBatch(u,a).next(p=>(B(p!==null,37113),d=p.keys(),l.mutationQueue.removeMutationBatch(u,p))).next(()=>l.mutationQueue.performConsistencyCheck(u)).next(()=>l.documentOverlayCache.removeOverlaysForBatchId(u,d,a)).next(()=>l.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(u,d)).next(()=>l.localDocuments.getDocuments(u,d))})})(r.localStore,e);Am(r,e,t),Im(r,e),r.sharedClientState.updateMutationState(e,"rejected",t),await Fn(r,s)}catch(s){await Ir(s)}}async function UR(n,e){let t=F(n);Sr(t.remoteStore)||D(Rr,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let r=await(function(o){let a=F(o);return a.persistence.runTransaction("Get highest unacknowledged batch id","readonly",l=>a.mutationQueue.getHighestUnacknowledgedBatchId(l))})(t.localStore);if(r===lr)return void e.resolve();let s=t.yu.get(r)||[];s.push(e),t.yu.set(r,s)}catch(r){let s=Vi(r,"Initialization of waitForPendingWrites() operation failed");e.reject(s)}}function Im(n,e){(n.yu.get(e)||[]).forEach(t=>{t.resolve()}),n.yu.delete(e)}function Am(n,e,t){let r=F(n),s=r.pu[r.currentUser.toKey()];if(s){let i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),r.pu[r.currentUser.toKey()]=s}}function bi(n,e,t=null){n.sharedClientState.removeLocalQueryTarget(e);for(let r of n.Vu.get(e))n.Au.delete(r),t&&n.Ru.Du(r,t);n.Vu.delete(e),n.isPrimaryClient&&n.gu.Gr(e).forEach(r=>{n.gu.containsKey(r)||fI(n,r)})}function fI(n,e){n.du.delete(e.path.canonicalString());let t=n.mu.get(e);t!==null&&(Ai(n.remoteStore,t),n.mu=n.mu.remove(e),n.fu.delete(t),bm(n))}function Fp(n,e,t){for(let r of t)r instanceof iu?(n.gu.addReference(r.key,e),BR(n,r)):r instanceof ou?(D(Rr,"Document no longer in limbo: "+r.key),n.gu.removeReference(r.key,e),n.gu.containsKey(r.key)||fI(n,r.key)):U(19791,{Cu:r})}function BR(n,e){let t=e.key,r=t.path.canonicalString();n.mu.get(t)||n.du.has(r)||(D(Rr,"New document in limbo: "+t),n.du.add(r),bm(n))}function bm(n){for(;n.du.size>0&&n.mu.size{o.push(r.bu(l,e,t).then(u=>{if((u||t)&&r.isPrimaryClient){let d=u?!u.fromCache:t?.targetChanges.get(l.targetId)?.current;r.sharedClientState.updateQueryState(l.targetId,d?"current":"not-current")}if(u){s.push(u);let d=fp.Es(l.targetId,u);i.push(d)}}))}),await Promise.all(o),r.Ru.H_(s),await(async function(l,u){let d=F(l);try{await d.persistence.runTransaction("notifyLocalViewChanges","readwrite",p=>C.forEach(u,m=>C.forEach(m.Ts,v=>d.persistence.referenceDelegate.addReference(p,m.targetId,v)).next(()=>C.forEach(m.Is,v=>d.persistence.referenceDelegate.removeReference(p,m.targetId,v)))))}catch(p){if(!Ar(p))throw p;D(mm,"Failed to update sequence numbers: "+p)}for(let p of u){let m=p.targetId;if(!p.fromCache){let v=d.vs.get(m),S=v.snapshotVersion,x=v.withLastLimboFreeSnapshotVersion(S);d.vs=d.vs.insert(m,x)}}})(r.localStore,i))}async function qR(n,e){let t=F(n);if(!t.currentUser.isEqual(e)){D(Rr,"User change. New user:",e.toKey());let r=await QT(t.localStore,e);t.currentUser=e,(function(i,o){i.yu.forEach(a=>{a.forEach(l=>{l.reject(new N(R.CANCELLED,o))})}),i.yu.clear()})(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,r.removedBatchIds,r.addedBatchIds),await Fn(t,r.Ns)}}function jR(n,e){let t=F(n),r=t.fu.get(e);if(r&&r.Eu)return $().add(r.key);{let s=$(),i=t.Vu.get(e);if(!i)return s;for(let o of i){let a=t.Au.get(o);s=s.unionWith(a.view.ou)}return s}}async function GR(n,e){let t=F(n),r=await Hl(t.localStore,e.query,!0),s=e.view.Tu(r);return t.isPrimaryClient&&Fp(t,e.targetId,s.hu),s}async function zR(n,e){let t=F(n);return ZT(t.localStore,e).then(r=>Fn(t,r))}async function KR(n,e,t,r){let s=F(n),i=await(function(a,l){let u=F(a),d=F(u.mutationQueue);return u.persistence.runTransaction("Lookup mutation documents","readonly",p=>d.Xn(p,l).next(m=>m?u.localDocuments.getDocuments(p,m):C.resolve(null)))})(s.localStore,e);i!==null?(t==="pending"?await Ni(s.remoteStore):t==="acknowledged"||t==="rejected"?(Am(s,e,r||null),Im(s,e),(function(a,l){F(F(a).mutationQueue).nr(l)})(s.localStore,e)):U(6720,"Unknown batchState",{vu:t}),await Fn(s,i)):D(Rr,"Cannot apply mutation batch with id: "+e)}async function WR(n,e){let t=F(n);if(Cu(t),Cm(t),e===!0&&t.Su!==!0){let r=t.sharedClientState.getAllActiveQueryTargets(),s=await yE(t,r.toArray());t.Su=!0,await Rp(t.remoteStore,!0);for(let i of s)bu(t.remoteStore,i)}else if(e===!1&&t.Su!==!1){let r=[],s=Promise.resolve();t.Vu.forEach((i,o)=>{t.sharedClientState.isLocalQueryTarget(o)?r.push(o):s=s.then(()=>(bi(t,o),Ii(t.localStore,o,!0))),Ai(t.remoteStore,o)}),await s,await yE(t,r),(function(o){let a=F(o);a.fu.forEach((l,u)=>{Ai(a.remoteStore,u)}),a.gu.zr(),a.fu=new Map,a.mu=new ye(O.comparator)})(t),t.Su=!1,await Rp(t.remoteStore,!1)}}async function yE(n,e,t){let r=F(n),s=[],i=[];for(let o of e){let a,l=r.Vu.get(o);if(l&&l.length!==0){a=await Ti(r.localStore,ct(l[0]));for(let u of l){let d=r.Au.get(u),p=await GR(r,d);p.snapshot&&i.push(p.snapshot)}}else{let u=await XT(r.localStore,o);a=await Ti(r.localStore,u),await Tm(r,pI(u),o,!1,a.resumeToken)}s.push(a)}return r.Ru.H_(i),s}function pI(n){return iT(n.path,n.collectionGroup,n.orderBy,n.filters,n.limit,"F",n.startAt,n.endAt)}function $R(n){return(function(t){return F(F(t).persistence).hs()})(F(n).localStore)}async function HR(n,e,t,r){let s=F(n);if(s.Su)return void D(Rr,"Ignoring unexpected query state notification.");let i=s.Vu.get(e);if(i&&i.length>0)switch(t){case"current":case"not-current":{let o=await ZT(s.localStore,uT(i[0])),a=wi.createSynthesizedRemoteEventForCurrentChange(e,t==="current",Re.EMPTY_BYTE_STRING);await Fn(s,o,a);break}case"rejected":await Ii(s.localStore,e,!0),bi(s,e,r);break;default:U(64155,t)}}async function QR(n,e,t){let r=Cu(n);if(r.Su){for(let s of e){if(r.Vu.has(s)&&r.sharedClientState.isActiveQueryTarget(s)){D(Rr,"Adding an already active target "+s);continue}let i=await XT(r.localStore,s),o=await Ti(r.localStore,i);await Tm(r,pI(i),o.targetId,!1,o.resumeToken),bu(r.remoteStore,o)}for(let s of t)r.Vu.has(s)&&await Ii(r.localStore,s,!1).then(()=>{Ai(r.remoteStore,s),bi(r,s)}).catch(Ir)}}function Cu(n){let e=F(n);return e.remoteStore.remoteSyncer.applyRemoteEvent=dI.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=jR.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=MR.bind(null,e),e.Ru.H_=PR.bind(null,e.eventManager),e.Ru.Du=xR.bind(null,e.eventManager),e}function Cm(n){let e=F(n);return e.remoteStore.remoteSyncer.applySuccessfulWrite=FR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=LR.bind(null,e),e}function YR(n,e,t){let r=F(n);(async function(i,o,a){try{let l=await o.getMetadata();if(await(function(v,S){let x=F(v),k=Ne(S.createTime);return x.persistence.runTransaction("hasNewerBundle","readonly",q=>x.Pi.getBundleMetadata(q,S.id)).then(q=>!!q&&q.createTime.compareTo(k)>=0)})(i.localStore,l))return await o.close(),a._completeWith((function(v){return{taskState:"Success",documentsLoaded:v.totalDocuments,bytesLoaded:v.totalBytes,totalDocuments:v.totalDocuments,totalBytes:v.totalBytes}})(l)),Promise.resolve(new Set);a._updateProgress(uI(l));let u=new su(l,o.serializer),d=await o.Fu();for(;d;){let m=await u.Ha(d);m&&a._updateProgress(m),d=await o.Fu()}let p=await u.Xa(i.localStore);return await Fn(i,p.eu,void 0),await(function(v,S){let x=F(v);return x.persistence.runTransaction("Save bundle","readwrite",k=>x.Pi.saveBundleMetadata(k,S))})(i.localStore,l),a._completeWith(p.progress),Promise.resolve(p.Ya)}catch(l){return vt(Rr,`Loading bundle failed with ${l}`),a._failWith(l),Promise.resolve(new Set)}})(r,e,t).then(s=>{r.sharedClientState.notifyBundleLoaded(s)})}var Su=(()=>{class n{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(t){this.serializer=xi(t.databaseInfo.databaseId),this.sharedClientState=this.Mu(t),this.persistence=this.xu(t),await this.persistence.start(),this.localStore=this.Ou(t),this.gcScheduler=this.Nu(t,this.localStore),this.indexBackfillerScheduler=this.Bu(t,this.localStore)}Nu(t,r){return null}Bu(t,r){return null}Ou(t){return HT(this.persistence,new $l,t.initialUser,this.serializer)}xu(t){return new wa(Kl.Vi,this.serializer)}Mu(t){return new Jl}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}return n.provider={build:()=>new n},n})(),cu=class extends Su{constructor(e){super(),this.cacheSizeBytes=e}Nu(e,t){B(this.persistence.referenceDelegate instanceof Wl,46915);let r=this.persistence.referenceDelegate.garbageCollector;return new jl(r,e.asyncQueue,t)}xu(e){let t=this.cacheSizeBytes!==void 0?_t.withCacheSize(this.cacheSizeBytes):_t.DEFAULT;return new wa(r=>Wl.Vi(r,t),this.serializer)}},ba=class extends Su{constructor(e,t,r){super(),this.Lu=e,this.cacheSizeBytes=t,this.forceOwnership=r,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Lu.initialize(this,e),await Cm(this.Lu.syncEngine),await Ni(this.Lu.remoteStore),await this.persistence.zi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ou(e){return HT(this.persistence,new $l,e.initialUser,this.serializer)}Nu(e,t){let r=this.persistence.referenceDelegate.garbageCollector;return new jl(r,e.asyncQueue,t)}Bu(e,t){let r=new df(t,this.persistence);return new hf(e.asyncQueue,r)}xu(e){let t=pm(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),r=this.cacheSizeBytes!==void 0?_t.withCacheSize(this.cacheSizeBytes):_t.DEFAULT;return new dp(this.synchronizeTabs,t,e.clientId,r,e.asyncQueue,sI(),pl(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Mu(e){return new Jl}},lu=class extends ba{constructor(e,t){super(e,t,!1),this.Lu=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);let t=this.Lu.syncEngine;this.sharedClientState instanceof na&&(this.sharedClientState.syncEngine={bo:KR.bind(null,t),Do:HR.bind(null,t),Co:QR.bind(null,t),hs:$R.bind(null,t),So:zR.bind(null,t)},await this.sharedClientState.start()),await this.persistence.zi(async r=>{await WR(this.Lu.syncEngine,r),this.gcScheduler&&(r&&!this.gcScheduler.started?this.gcScheduler.start():r||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(r&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():r||this.indexBackfillerScheduler.stop())})}Mu(e){let t=sI();if(!na.v(t))throw new N(R.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let r=pm(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new na(t,e.asyncQueue,r,e.clientId,e.initialUser)}},Ru=(()=>{class n{async initialize(t,r){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(r),this.remoteStore=this.createRemoteStore(r),this.eventManager=this.createEventManager(r),this.syncEngine=this.createSyncEngine(r,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=s=>_E(this.syncEngine,s,1),this.remoteStore.remoteSyncer.handleCredentialChange=qR.bind(null,this.syncEngine),await Rp(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return(function(){return new kp})()}createDatastore(t){let r=xi(t.databaseInfo.databaseId),s=_R(t.databaseInfo);return yR(t.authCredentials,t.appCheckCredentials,s,r)}createRemoteStore(t){return(function(s,i,o,a,l){return new Cp(s,i,o,a,l)})(this.localStore,this.datastore,t.asyncQueue,r=>_E(this.syncEngine,r,0),(function(){return Xl.v()?new Xl:new _p})())}createSyncEngine(t,r){return(function(i,o,a,l,u,d,p){let m=new Mp(i,o,a,l,u,d);return p&&(m.Su=!0),m})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,r)}async terminate(){await(async function(r){let s=F(r);D(pn,"RemoteStore shutting down."),s.da.add(5),await ki(s),s.fa.shutdown(),s.ga.set("Unknown")})(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}return n.provider={build:()=>new n},n})();function vE(n,e=10240){let t=0;return{async read(){if(t{this.muted||e(t)},0)}};var Lp=class{constructor(e,t){this.qu=e,this.serializer=t,this.metadata=new ze,this.buffer=new Uint8Array,this.Uu=(function(){return new TextDecoder("utf-8")})(),this.$u().then(r=>{r&&r.Ga()?this.metadata.resolve(r.Qa.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is ${JSON.stringify(r?.Qa)}`))},r=>this.metadata.reject(r))}close(){return this.qu.cancel()}async getMetadata(){return this.metadata.promise}async Fu(){return await this.getMetadata(),this.$u()}async $u(){let e=await this.Wu();if(e===null)return null;let t=this.Uu.decode(e),r=Number(t);isNaN(r)&&this.Qu(`length string (${t}) is not valid number`);let s=await this.Gu(r);return new Dp(JSON.parse(s),e.length+r)}zu(){return this.buffer.findIndex(e=>e===123)}async Wu(){for(;this.zu()<0&&!await this.ju(););if(this.buffer.length===0)return null;let e=this.zu();e<0&&this.Qu("Reached the end of bundle when a length string is expected.");let t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Gu(e){for(;this.buffer.length0)throw this.lastTransactionError=new N(R.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let t=await(async function(s,i){let o=F(s),a={documents:i.map(p=>ga(o.serializer,p))},l=await o.jo("BatchGetDocuments",o.serializer.databaseId,ie.emptyPath(),a,i.length),u=new Map;l.forEach(p=>{let m=X0(o.serializer,p);u.set(m.key.toString(),m)});let d=[];return i.forEach(p=>{let m=u.get(p.toString());B(!!m,55234,{key:p}),d.push(m)}),d})(this.datastore,e);return t.forEach(r=>this.recordVersion(r)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(r){this.lastTransactionError=r}this.writtenDocs.add(e.toString())}delete(e){this.write(new Mn(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(t=>{e.delete(t.key.toString())}),e.forEach((t,r)=>{let s=O.fromPath(r);this.mutations.push(new da(s,this.precondition(s)))}),await(async function(r,s){let i=F(r),o={writes:s.map(a=>_a(i.serializer,a))};await i.Wo("Commit",i.serializer.databaseId,ie.emptyPath(),o)})(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw U(50498,{Hu:e.constructor.name});t=j.min()}let r=this.readVersions.get(e.key.toString());if(r){if(!t.isEqual(r))throw new N(R.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){let t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(j.min())?Ae.exists(!1):Ae.updateTime(t):Ae.none()}preconditionForUpdate(e){let t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(j.min()))throw new N(R.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ae.updateTime(t)}return Ae.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}};var Bp=class{constructor(e,t,r,s,i){this.asyncQueue=e,this.datastore=t,this.options=r,this.updateFunction=s,this.deferred=i,this.Zu=r.maxAttempts,this.M_=new Ta(this.asyncQueue,"transaction_retry")}Xu(){this.Zu-=1,this.Yu()}Yu(){this.M_.p_(async()=>{let e=new Up(this.datastore),t=this.ec(e);t&&t.then(r=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(r)}).catch(s=>{this.tc(s)}))}).catch(r=>{this.tc(r)})})}ec(e){try{let t=this.updateFunction(e);return!Ra(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(t){return this.deferred.reject(t),null}}tc(e){this.Zu>0&&this.nc(e)?(this.Zu-=1,this.asyncQueue.enqueueAndForget(()=>(this.Yu(),Promise.resolve()))):this.deferred.reject(e)}nc(e){if(e?.name==="FirebaseError"){let t=e.code;return t==="aborted"||t==="failed-precondition"||t==="already-exists"||!IT(t)}return!1}};var wr="FirestoreClient",qp=class{constructor(e,t,r,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=s,this.user=Le.UNAUTHENTICATED,this.clientId=ds.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async o=>{D(wr,"Received user=",o.uid),await this.authCredentialListener(o),this.user=o}),this.appCheckCredentials.start(r,o=>(D(wr,"Received new app check token=",o),this.appCheckCredentialListener(o,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(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new ze;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){let r=Vi(t,"Failed to shutdown persistence");e.reject(r)}}),e.promise}};async function nf(n,e){n.asyncQueue.verifyOperationInProgress(),D(wr,"Initializing OfflineComponentProvider");let t=n.configuration;await e.initialize(t);let r=t.initialUser;n.setCredentialChangeListener(async s=>{r.isEqual(s)||(await QT(e.localStore,s),r=s)}),e.persistence.setDatabaseDeletedListener(()=>n.terminate()),n._offlineComponents=e}async function wE(n,e){n.asyncQueue.verifyOperationInProgress();let t=await Sm(n);D(wr,"Initializing OnlineComponentProvider"),await e.initialize(t,n.configuration),n.setCredentialChangeListener(r=>pE(e.remoteStore,r)),n.setAppCheckTokenChangeListener((r,s)=>pE(e.remoteStore,s)),n._onlineComponents=e}async function Sm(n){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){D(wr,"Using user provided OfflineComponentProvider");try{await nf(n,n._uninitializedComponentsProvider._offline)}catch(e){let t=e;if(!(function(s){return s.name==="FirebaseError"?s.code===R.FAILED_PRECONDITION||s.code===R.UNIMPLEMENTED:!(typeof DOMException<"u"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11})(t))throw t;vt("Error using user provided cache. Falling back to memory cache: "+t),await nf(n,new Su)}}else D(wr,"Using default OfflineComponentProvider"),await nf(n,new cu(void 0));return n._offlineComponents}async function Pu(n){return n._onlineComponents||(n._uninitializedComponentsProvider?(D(wr,"Using user provided OnlineComponentProvider"),await wE(n,n._uninitializedComponentsProvider._online)):(D(wr,"Using default OnlineComponentProvider"),await wE(n,new Ru))),n._onlineComponents}function mI(n){return Sm(n).then(e=>e.persistence)}function Rm(n){return Sm(n).then(e=>e.localStore)}function gI(n){return Pu(n).then(e=>e.remoteStore)}function Pm(n){return Pu(n).then(e=>e.syncEngine)}function JR(n){return Pu(n).then(e=>e.datastore)}async function Si(n){let e=await Pu(n),t=e.eventManager;return t.onListen=kR.bind(null,e.syncEngine),t.onUnlisten=DR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=NR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=VR.bind(null,e.syncEngine),t}function XR(n){return n.asyncQueue.enqueue(async()=>{let e=await mI(n),t=await gI(n);return e.setNetworkEnabled(!0),(function(s){let i=F(s);return i.da.delete(0),Va(i)})(t)})}function ZR(n){return n.asyncQueue.enqueue(async()=>{let e=await mI(n),t=await gI(n);return e.setNetworkEnabled(!1),(async function(s){let i=F(s);i.da.add(0),await ki(i),i.ga.set("Offline")})(t)})}function _I(n,e,t,r){let s=new Ci(r),i=new Aa(e,s,t);return n.asyncQueue.enqueueAndForget(async()=>vm(await Si(n),i)),()=>{s.Ku(),n.asyncQueue.enqueueAndForget(async()=>wm(await Si(n),i))}}function yI(n,e){let t=new ze;return n.asyncQueue.enqueueAndForget(async()=>(async function(s,i,o){try{let a=await(function(u,d){let p=F(u);return p.persistence.runTransaction("read document","readonly",m=>p.localDocuments.getDocument(m,d))})(s,i);a.isFoundDocument()?o.resolve(a):a.isNoDocument()?o.resolve(null):o.reject(new N(R.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(a){let l=Vi(a,`Failed to get document '${i} from cache`);o.reject(l)}})(await Rm(n),e,t)),t.promise}function xm(n,e,t={}){let r=new ze;return n.asyncQueue.enqueueAndForget(async()=>(function(i,o,a,l,u){let d=new Ci({next:m=>{d.Ku(),o.enqueueAndForget(()=>wm(i,p));let v=m.docs.has(a);!v&&m.fromCache?u.reject(new N(R.UNAVAILABLE,"Failed to get document because the client is offline.")):v&&m.fromCache&&l&&l.source==="server"?u.reject(new N(R.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.)')):u.resolve(m)},error:m=>u.reject(m)}),p=new Aa(Es(a.path),d,{includeMetadataChanges:!0,Wa:!0});return vm(i,p)})(await Si(n),n.asyncQueue,e,t,r)),r.promise}function vI(n,e){let t=new ze;return n.asyncQueue.enqueueAndForget(async()=>(async function(s,i,o){try{let a=await Hl(s,i,!0),l=new au(i,a.ks),u=l._u(a.documents),d=l.applyChanges(u,!1);o.resolve(d.snapshot)}catch(a){let l=Vi(a,`Failed to execute query '${i} against cache`);o.reject(l)}})(await Rm(n),e,t)),t.promise}function km(n,e,t={}){let r=new ze;return n.asyncQueue.enqueueAndForget(async()=>(function(i,o,a,l,u){let d=new Ci({next:m=>{d.Ku(),o.enqueueAndForget(()=>wm(i,p)),m.fromCache&&l.source==="server"?u.reject(new N(R.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.)')):u.resolve(m)},error:m=>u.reject(m)}),p=new Aa(a,d,{includeMetadataChanges:!0,Wa:!0});return vm(i,p)})(await Si(n),n.asyncQueue,e,t,r)),r.promise}function wI(n,e){let t=new ze;return n.asyncQueue.enqueueAndForget(async()=>OR(await Pm(n),e,t)),t.promise}function EI(n,e){let t=new Ci(e);return n.asyncQueue.enqueueAndForget(async()=>(function(s,i){F(s).xa.add(i),i.next()})(await Si(n),t)),()=>{t.Ku(),n.asyncQueue.enqueueAndForget(async()=>(function(s,i){F(s).xa.delete(i)})(await Si(n),t))}}function TI(n,e,t){let r=new ze;return n.asyncQueue.enqueueAndForget(async()=>{let s=await JR(n);new Bp(n.asyncQueue,s,t,e,r).Xu()}),r.promise}function eP(n,e,t,r){let s=(function(o,a){let l;return l=typeof o=="string"?bT().encode(o):o,(function(d,p){return new Lp(d,p)})((function(d,p){if(d instanceof Uint8Array)return vE(d,p);if(d instanceof ArrayBuffer)return vE(new Uint8Array(d),p);if(d instanceof ReadableStream)return d.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")})(l),a)})(t,xi(e));n.asyncQueue.enqueueAndForget(async()=>{YR(await Pm(n),s,r)})}function tP(n,e){return n.asyncQueue.enqueue(async()=>(function(r,s){let i=F(r);return i.persistence.runTransaction("Get named query","readonly",o=>i.Pi.getNamedQuery(o,s))})(await Rm(n),e))}function II(n){let e={};return n.timeoutSeconds!==void 0&&(e.timeoutSeconds=n.timeoutSeconds),e}var nP="ComponentProvider",EE=new Map;function rP(n,e,t,r,s){return new gf(n,e,t,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,II(s.experimentalLongPollingOptions),s.useFetchStreams,s.isUsingEmulator,r)}var AI="firestore.googleapis.com",TE=!0,uu=class{constructor(e){if(e.host===void 0){if(e.ssl!==void 0)throw new N(R.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=AI,this.ssl=TE}else this.host=e.host,this.ssl=e.ssl??TE;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=qT;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes30)throw new N(R.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(function(r,s){return r.timeoutSeconds===s.timeoutSeconds})(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},ws=class{constructor(e,t,r,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new uu({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new N(R.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(e){if(this._settingsFrozen)throw new N(R.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 uu(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(r){if(!r)return new gl;switch(r.type){case"firstParty":return new of(r.sessionIndex||"0",r.iamToken||null,r.authTokenFactory||null);case"provider":return r.client;default:throw new N(R.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_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(t){let r=EE.get(t);r&&(D(nP,"Removing Datastore"),EE.delete(t),r.terminate())})(this),Promise.resolve()}};function Nm(n,e,t,r={}){n=ae(n,ws);let s=Ws(e),i=n._getSettings(),o=tt(Q({},i),{emulatorOptions:n._getEmulatorOptions()}),a=`${e}:${t}`;s&&Wc(`https://${a}`),i.host!==AI&&i.host!==a&&vt("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let l=tt(Q({},i),{host:a,ssl:s,emulatorOptions:r});if(!Hr(l,o)&&(n._setSettings(l),r.mockUserToken)){let u,d;if(typeof r.mockUserToken=="string")u=r.mockUserToken,d=Le.MOCK_USER;else{u=jc(r.mockUserToken,n._app?.options.projectId);let p=r.mockUserToken.sub||r.mockUserToken.user_id;if(!p)throw new N(R.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");d=new Le(p)}n._authCredentials=new rf(new ml(u,d))}}var Ke=class n{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new n(this.firestore,e,this._query)}},he=class n{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}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(e){return new n(this.firestore,e,this._key)}toJSON(){return{type:n._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(Pi(t,n._jsonSchema))return new n(e,r||null,new O(ie.fromString(t.referencePath)))}};he._jsonSchemaVersion="firestore/documentReference/1.0",he._jsonSchema={type:ke("string",he._jsonSchemaVersion),referencePath:ke("string")};var Gt=class n extends Ke{constructor(e,t,r){super(e,t,Es(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new he(this.firestore,null,new O(e))}withConverter(e){return new n(this.firestore,e,this._path)}};function xu(n,e,...t){if(n=te(n),Jp("collection","path",e),n instanceof ws){let r=ie.fromString(e,...t);return _w(r),new Gt(n,null,r)}{if(!(n instanceof he||n instanceof Gt))throw new N(R.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=n._path.child(ie.fromString(e,...t));return _w(r),new Gt(n.firestore,null,r)}}function Dm(n,e){if(n=ae(n,ws),Jp("collectionGroup","collection id",e),e.indexOf("/")>=0)throw new N(R.INVALID_ARGUMENT,`Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ke(n,null,(function(r){return new Wt(ie.emptyPath(),r)})(e))}function Ts(n,e,...t){if(n=te(n),arguments.length===1&&(e=ds.newId()),Jp("doc","path",e),n instanceof ws){let r=ie.fromString(e,...t);return gw(r),new he(n,null,new O(r))}{if(!(n instanceof he||n instanceof Gt))throw new N(R.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=n._path.child(ie.fromString(e,...t));return gw(r),new he(n.firestore,n instanceof Gt?n.converter:null,new O(r))}}function ku(n,e){return n=te(n),e=te(e),(n instanceof he||n instanceof Gt)&&(e instanceof he||e instanceof Gt)&&n.firestore===e.firestore&&n.path===e.path&&n.converter===e.converter}function Oa(n,e){return n=te(n),e=te(e),n instanceof Ke&&e instanceof Ke&&n.firestore===e.firestore&&Na(n._query,e._query)&&n.converter===e.converter}var IE="AsyncQueue",hu=class{constructor(e=Promise.resolve()){this.rc=[],this.sc=!1,this.oc=[],this._c=null,this.ac=!1,this.uc=!1,this.cc=[],this.M_=new Ta(this,"async_queue_retry"),this.lc=()=>{let r=pl();r&&D(IE,"Visibility state changed to "+r.visibilityState),this.M_.w_()},this.hc=e;let t=pl();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this.lc)}get isShuttingDown(){return this.sc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pc(),this.Tc(e)}enterRestrictedMode(e){if(!this.sc){this.sc=!0,this.uc=e||!1;let t=pl();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this.lc)}}enqueue(e){if(this.Pc(),this.sc)return new Promise(()=>{});let t=new ze;return this.Tc(()=>this.sc&&this.uc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.rc.push(e),this.Ic()))}async Ic(){if(this.rc.length!==0){try{await this.rc[0](),this.rc.shift(),this.M_.reset()}catch(e){if(!Ar(e))throw e;D(IE,"Operation failed with retryable error: "+e)}this.rc.length>0&&this.M_.p_(()=>this.Ic())}}Tc(e){let t=this.hc.then(()=>(this.ac=!0,e().catch(r=>{throw this._c=r,this.ac=!1,xe("INTERNAL UNHANDLED ERROR: ",AE(r)),r}).then(r=>(this.ac=!1,r))));return this.hc=t,t}enqueueAfterDelay(e,t,r){this.Pc(),this.cc.indexOf(e)>-1&&(t=0);let s=Pp.createAndSchedule(this,e,t,r,i=>this.Ec(i));return this.oc.push(s),s}Pc(){this._c&&U(47125,{Rc:AE(this._c)})}verifyOperationInProgress(){}async Ac(){let e;do e=this.hc,await e;while(e!==this.hc)}Vc(e){for(let t of this.oc)if(t.timerId===e)return!0;return!1}dc(e){return this.Ac().then(()=>{this.oc.sort((t,r)=>t.targetTimeMs-r.targetTimeMs);for(let t of this.oc)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Ac()})}mc(e){this.cc.push(e)}Ec(e){let t=this.oc.indexOf(e);this.oc.splice(t,1)}};function AE(n){let e=n.message||"";return n.stack&&(e=n.stack.includes(n.message)?n.stack:n.message+` `+n.stack),e}var du=class{constructor(){this._progressObserver={},this._taskCompletionResolver=new ze,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,r){this._progressObserver={next:e,error:t,complete:r}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}};var Vm=-1,Ee=class extends ws{constructor(e,t,r,s){super(e,t,r,s),this.type="firestore",this._queue=new hu,this._persistenceKey=s?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new hu(e),this._firestoreClient=void 0,await e}}};function $e(n){if(n._terminated)throw new N(R.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||bI(n),n._firestoreClient}function bI(n){let e=n._freezeSettings(),t=rP(n._databaseId,n._app?.options.appId||"",n._persistenceKey,n._app?.options.apiKey,e);n._componentsProvider||e.localCache?._offlineComponentProvider&&e.localCache?._onlineComponentProvider&&(n._componentsProvider={_offline:e.localCache._offlineComponentProvider,_online:e.localCache._onlineComponentProvider}),n._firestoreClient=new qp(n._authCredentials,n._appCheckCredentials,n._queue,t,n._componentsProvider&&(function(s){let i=s?._online.build();return{_offline:s?._offline.build(i),_online:i}})(n._componentsProvider))}function Om(n,e){vt("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=n._freezeSettings();return CI(n,Ru.provider,{build:r=>new ba(r,t.cacheSizeBytes,e?.forceOwnership)}),Promise.resolve()}async function Mm(n){vt("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let e=n._freezeSettings();CI(n,Ru.provider,{build:t=>new lu(t,e.cacheSizeBytes)})}function CI(n,e,t){if((n=ae(n,Ee))._firestoreClient||n._terminated)throw new N(R.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(n._componentsProvider||n._getSettings().localCache)throw new N(R.FAILED_PRECONDITION,"SDK cache is already specified.");n._componentsProvider={_online:e,_offline:t},bI(n)}function Fm(n){if(n._initialized&&!n._terminated)throw new N(R.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let e=new ze;return n._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await(async function(r){if(!hr.v())return Promise.resolve();let s=r+$T;await hr.delete(s)})(pm(n._databaseId,n._persistenceKey)),e.resolve()}catch(t){e.reject(t)}}),e.promise}function Lm(n){return(function(t){let r=new ze;return t.asyncQueue.enqueueAndForget(async()=>UR(await Pm(t),r)),r.promise})($e(n=ae(n,Ee)))}function Um(n){return XR($e(n=ae(n,Ee)))}function Bm(n){return ZR($e(n=ae(n,Ee)))}function Nu(n,e){let t=$e(n=ae(n,Ee)),r=new du;return eP(t,n._databaseId,e,r),r}function Du(n,e){return tP($e(n=ae(n,Ee)),e).then(t=>t?new Ke(n,null,t.query):null)}var lt=class n{constructor(e){this._byteString=e}static fromBase64String(e){try{return new n(Re.fromBase64String(e))}catch(t){throw new N(R.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new n(Re.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:n._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Pi(e,n._jsonSchema))return n.fromBase64String(e.bytes)}};lt._jsonSchemaVersion="firestore/bytes/1.0",lt._jsonSchema={type:ke("string",lt._jsonSchemaVersion),bytes:ke("string")};var Ot=class{constructor(...e){for(let t=0;t90)throw new N(R.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new N(R.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return W(this._lat,e._lat)||W(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:n._jsonSchemaVersion}}static fromJSON(e){if(Pi(e,n._jsonSchema))return new n(e.latitude,e.longitude)}};zt._jsonSchemaVersion="firestore/geoPoint/1.0",zt._jsonSchema={type:ke("string",zt._jsonSchemaVersion),latitude:ke("number"),longitude:ke("number")};var dn=class n{constructor(e){this._values=(e||[]).map(t=>t)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(r,s){if(r.length!==s.length)return!1;for(let i=0;itypeof t=="number"))return new n(e.vectorValues);throw new N(R.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};dn._jsonSchemaVersion="firestore/vectorValue/1.0",dn._jsonSchema={type:ke("string",dn._jsonSchemaVersion),vectorValues:ke("object")};var sP=/^__.*__$/,jp=class{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return this.fieldMask!==null?new Ht(e,this.data,this.fieldMask,t,this.fieldTransforms):new _r(e,this.data,t,this.fieldTransforms)}},fu=class{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new Ht(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function SI(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw U(40011,{dataSource:n})}}var pu=class n{constructor(e,t,r,s,i,o){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=s,i===void 0&&this.fc(),this.fieldTransforms=i||[],this.fieldMask=o||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}i(e){return new n(Q(Q({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}yc(e){let t=this.path?.child(e),r=this.i({path:t,arrayElement:!1});return r.wc(e),r}Sc(e){let t=this.path?.child(e),r=this.i({path:t,arrayElement:!1});return r.fc(),r}bc(e){return this.i({path:void 0,arrayElement:!0})}Dc(e){return mu(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return this.fieldMask.find(t=>e.isPrefixOf(t))!==void 0||this.fieldTransforms.find(t=>e.isPrefixOf(t.field))!==void 0}fc(){if(this.path)for(let e=0;el.covers(p.field))}else l=null,u=o.fieldTransforms;return new jp(new Ze(a),l,u)}var Ca=class n extends mn{_toFieldTransform(e){if(e.dataSource!==2)throw e.dataSource===1?e.Dc(`${this._methodName}() can only appear at the top level of your update data`):e.Dc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof n}};function RI(n,e,t){return new pu({dataSource:3,targetDoc:e.settings.targetDoc,methodName:n._methodName,arrayElement:t},e.databaseId,e.serializer,e.ignoreUndefinedProperties)}var zp=class n extends mn{_toFieldTransform(e){return new ms(e.path,new mr)}isEqual(e){return e instanceof n}},Kp=class n extends mn{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=RI(this,e,!0),r=this.vc.map(i=>Is(i,t)),s=new Vn(r);return new ms(e.path,s)}isEqual(e){return e instanceof n&&Hr(this.vc,e.vc)}},Wp=class n extends mn{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=RI(this,e,!0),r=this.vc.map(i=>Is(i,t)),s=new On(r);return new ms(e.path,s)}isEqual(e){return e instanceof n&&Hr(this.vc,e.vc)}},$p=class n extends mn{constructor(e,t){super(e),this.Fc=t}_toFieldTransform(e){let t=new gr(e.serializer,gT(e.serializer,this.Fc));return new ms(e.path,t)}isEqual(e){return e instanceof n&&this.Fc===e.Fc}};function Vu(n,e,t,r){let s=n.V(1,e,t);jm("Data must be an object, but it was:",s,r);let i=[],o=Ze.empty();br(r,(l,u)=>{let d=Gm(e,l,t);u=te(u);let p=s.Sc(d);if(u instanceof Ca)i.push(d);else{let m=Is(u,p);m!=null&&(i.push(d),o.set(d,m))}});let a=new St(i);return new fu(o,a,s.fieldTransforms)}function Ou(n,e,t,r,s,i){let o=n.V(1,e,t),a=[Er(e,r,t)],l=[s];if(i.length%2!=0)throw new N(R.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let m=0;m=0;--m)if(!kI(u,a[m])){let v=a[m],S=l[m];S=te(S);let x=o.Sc(v);if(S instanceof Ca)u.push(v);else{let k=Is(S,x);k!=null&&(u.push(v),d.set(v,k))}}let p=new St(u);return new fu(d,p,o.fieldTransforms)}function qm(n,e,t,r=!1){return Is(t,n.V(r?4:3,e))}function Is(n,e){if(xI(n=te(n)))return jm("Unsupported field value:",e,n),PI(n,e);if(n instanceof mn)return(function(r,s){if(!SI(s.dataSource))throw s.Dc(`${r._methodName}() can only be used with update() and set()`);if(!s.path)throw s.Dc(`${r._methodName}() is not currently supported inside arrays`);let i=r._toFieldTransform(s);i&&s.fieldTransforms.push(i)})(n,e),null;if(n===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),n instanceof Array){if(e.settings.arrayElement&&e.dataSource!==4)throw e.Dc("Nested arrays are not supported");return(function(r,s){let i=[],o=0;for(let a of r){let l=Is(a,s.bc(o));l==null&&(l={nullValue:"NULL_VALUE"}),i.push(l),o++}return{arrayValue:{values:i}}})(n,e)}return(function(r,s){if((r=te(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return gT(s.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){let i=me.fromDate(r);return{timestampValue:Ei(s.serializer,i)}}if(r instanceof me){let i=new me(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:Ei(s.serializer,i)}}if(r instanceof zt)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof lt)return{bytesValue:CT(s.serializer,r._byteString)};if(r instanceof he){let i=s.databaseId,o=r.firestore._databaseId;if(!o.isEqual(i))throw s.Dc(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:hm(r.firestore._databaseId||s.databaseId,r._key.path)}}if(r instanceof dn)return(function(o,a){let l=o instanceof dn?o.toArray():o;return{mapValue:{fields:{[om]:{stringValue:am},[mi]:{arrayValue:{values:l.map(d=>{if(typeof d!="number")throw a.Dc("VectorValues must only contain numeric values.");return um(a.serializer,d)})}}}}}})(r,s);if(FT(r))return r._toProto(s.serializer);throw s.Dc(`Unsupported field value: ${Sa(r)}`)})(n,e)}function PI(n,e){let t={};return zE(n)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):br(n,(r,s)=>{let i=Is(s,e.yc(r));i!=null&&(t[r]=i)}),{mapValue:{fields:t}}}function xI(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof me||n instanceof zt||n instanceof lt||n instanceof he||n instanceof mn||n instanceof dn||FT(n))}function jm(n,e,t){if(!xI(t)||!RE(t)){let r=Sa(t);throw r==="an object"?e.Dc(n+" a custom object"):e.Dc(n+" "+r)}}function Er(n,e,t){if((e=te(e))instanceof Ot)return e._internalPath;if(typeof e=="string")return Gm(n,e);throw mu("Field path arguments must be of type string or ",n,!1,void 0,t)}var iP=new RegExp("[~\\*/\\[\\]]");function Gm(n,e,t){if(e.search(iP)>=0)throw mu(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,t);try{return new Ot(...e.split("."))._internalPath}catch{throw mu(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,t)}}function mu(n,e,t,r,s){let i=r&&!r.isEmpty(),o=s!==void 0,a=`Function ${e}() called with invalid data`;t&&(a+=" (via `toFirestore()`)"),a+=". ";let l="";return(i||o)&&(l+=" (found",i&&(l+=` in field ${r}`),o&&(l+=` in document ${s}`),l+=")"),new N(R.INVALID_ARGUMENT,a+n+l)}function kI(n,e){return n.some(t=>t.isEqual(e))}var Tr=class{convertValue(e,t="none"){switch(dr(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Te(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Nn(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw U(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let r={};return br(e,(s,i)=>{r[s]=this.convertValue(i,t)}),r}convertVectorValue(e){let t=e.fields?.[mi].arrayValue?.values?.map(r=>Te(r.doubleValue));return new dn(t)}convertGeoPoint(e){return new zt(Te(e.latitude),Te(e.longitude))}convertArray(e,t){return(e.values||[]).map(r=>this.convertValue(r,t))}convertServerTimestamp(e,t){switch(t){case"previous":let r=wu(e);return r==null?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(ca(e));default:return null}}convertTimestamp(e){let t=kn(e);return new me(t.seconds,t.nanos)}convertDocumentKey(e,t){let r=ie.fromString(e);B(MT(r),9688,{name:e});let s=new Dn(r.get(1),r.get(3)),i=new O(r.popFirst(5));return s.isEqual(t)||xe(`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 (${t.projectId}/${t.database}) instead.`),i}};var gn=class extends Tr{constructor(e){super(),this.firestore=e}convertBytes(e){return new lt(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new he(this.firestore,null,t)}};function zm(){return new Ca("deleteField")}function Km(){return new zp("serverTimestamp")}function Wm(...n){return new Kp("arrayUnion",n)}function $m(...n){return new Wp("arrayRemove",n)}function Hm(n){return new $p("increment",n)}var NI="@firebase/firestore",DI="4.14.1";function Qm(n){return(function(t,r){if(typeof t!="object"||t===null)return!1;let s=t;for(let i of r)if(i in s&&typeof s[i]=="function")return!0;return!1})(n,["next","error","complete"])}var As=class{constructor(e,t,r,s,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new he(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new Ym(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){let t=this._document.data.field(Er("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},Ym=class extends As{data(){return super.data()}};function MI(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new N(R.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Fa=class{},bs=class extends Fa{};function Un(n,e,...t){let r=[];e instanceof Fa&&r.push(e),r=r.concat(t),(function(i){let o=i.filter(l=>l instanceof Jm).length,a=i.filter(l=>l instanceof Mu).length;if(o>1||o>0&&a>0)throw new N(R.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(...)))`.")})(r);for(let s of r)n=s._apply(n);return n}var Mu=class n extends bs{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new n(e,t,r)}_apply(e){let t=this._parse(e);return WI(e._query,t),new Ke(e.firestore,e.converter,Iu(e._query,t))}_parse(e){let t=Pr(e.firestore);return(function(i,o,a,l,u,d,p){let m;if(u.isKeyField()){if(d==="array-contains"||d==="array-contains-any")throw new N(R.INVALID_ARGUMENT,`Invalid Query. You can't perform '${d}' queries on documentId().`);if(d==="in"||d==="not-in"){OI(p,d);let S=[];for(let x of p)S.push(VI(l,i,x));m={arrayValue:{values:S}}}else m=VI(l,i,p)}else d!=="in"&&d!=="not-in"&&d!=="array-contains-any"||OI(p,d),m=qm(a,o,p,d==="in"||d==="not-in");return re.create(u,d,m)})(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}};function FI(n,e,t){let r=e,s=Er("where",n);return Mu._create(s,r,t)}var Jm=class n extends Fa{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new n(e,t)}_parse(e){let t=this._queryConstraints.map(r=>r._parse(e)).filter(r=>r.getFilters().length>0);return t.length===1?t[0]:de.create(t,this._getOperator())}_apply(e){let t=this._parse(e);return t.getFilters().length===0?e:((function(s,i){let o=s,a=i.getFlattenedFilters();for(let l of a)WI(o,l),o=Iu(o,l)})(e._query,t),new Ke(e.firestore,e.converter,Iu(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};var Xm=class n extends bs{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new n(e,t)}_apply(e){let t=(function(s,i,o){if(s.startAt!==null)throw new N(R.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(s.endAt!==null)throw new N(R.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new pr(i,o)})(e._query,this._field,this._direction);return new Ke(e.firestore,e.converter,oT(e._query,t))}};function LI(n,e="asc"){let t=e,r=Er("orderBy",n);return Xm._create(r,t)}var Fu=class n extends bs{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new n(e,t,r)}_apply(e){return new Ke(e.firestore,e.converter,ha(e._query,this._limit,this._limitType))}};function UI(n){return Xp("limit",n),Fu._create("limit",n,"F")}function BI(n){return Xp("limitToLast",n),Fu._create("limitToLast",n,"L")}var Lu=class n extends bs{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new n(e,t,r)}_apply(e){let t=KI(e,this.type,this._docOrFields,this._inclusive);return new Ke(e.firestore,e.converter,aT(e._query,t))}};function qI(...n){return Lu._create("startAt",n,!0)}function jI(...n){return Lu._create("startAfter",n,!1)}var Uu=class n extends bs{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new n(e,t,r)}_apply(e){let t=KI(e,this.type,this._docOrFields,this._inclusive);return new Ke(e.firestore,e.converter,cT(e._query,t))}};function GI(...n){return Uu._create("endBefore",n,!1)}function zI(...n){return Uu._create("endAt",n,!0)}function KI(n,e,t,r){if(t[0]=te(t[0]),t[0]instanceof As)return(function(i,o,a,l,u){if(!l)throw new N(R.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let d=[];for(let p of hs(i))if(p.field.isKeyField())d.push(Cr(o,l.key));else{let m=l.data.field(p.field);if(xa(m))throw new N(R.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+p.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(m===null){let v=p.field.canonicalString();throw new N(R.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${v}' (used as the orderBy) does not exist.`)}d.push(m)}return new Kt(d,u)})(n._query,n.firestore._databaseId,e,t[0]._document,r);{let s=Pr(n.firestore);return(function(o,a,l,u,d,p){let m=o.explicitOrderBy;if(d.length>m.length)throw new N(R.INVALID_ARGUMENT,`Too many arguments provided to ${u}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let v=[];for(let S=0;S=0)return a.op;return null})(n.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[]}})(e.op));if(t!==null)throw t===e.op?new N(R.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new N(R.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${t.toString()}' filters.`)}function qu(n,e,t){let r;return r=n?t&&(t.merge||t.mergeFields)?n.toFirestore(e,t):n.toFirestore(e):e,r}var Zm=class extends Tr{constructor(e){super(),this.firestore=e}convertBytes(e){return new lt(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new he(this.firestore,null,t)}};var Ln=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},ut=class n extends As{constructor(e,t,r,s,i,o){super(e,t,r,s,o),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new kr(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let r=this._document.data.field(Er("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new N(R.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=n._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?t:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),t.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),t)}};ut._jsonSchemaVersion="firestore/documentSnapshot/1.0",ut._jsonSchema={type:ke("string",ut._jsonSchemaVersion),bundleSource:ke("string","DocumentSnapshot"),bundleName:ke("string"),bundle:ke("string")};var kr=class extends ut{data(e={}){return super.data(e)}},wt=class n{constructor(e,t,r,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Ln(s.hasPendingWrites,s.fromCache),this.query=r}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,t){this._snapshot.docs.forEach(r=>{e.call(t,new kr(this._firestore,this._userDataWriter,r.key,r,new Ln(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new N(R.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=(function(s,i){if(s._snapshot.oldDocs.isEmpty()){let o=0;return s._snapshot.docChanges.map(a=>{let l=new kr(s._firestore,s._userDataWriter,a.doc.key,a.doc,new Ln(s._snapshot.mutatedKeys.has(a.doc.key),s._snapshot.fromCache),s.query.converter);return a.doc,{type:"added",doc:l,oldIndex:-1,newIndex:o++}})}{let o=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(a=>i||a.type!==3).map(a=>{let l=new kr(s._firestore,s._userDataWriter,a.doc.key,a.doc,new Ln(s._snapshot.mutatedKeys.has(a.doc.key),s._snapshot.fromCache),s.query.converter),u=-1,d=-1;return a.type!==0&&(u=o.indexOf(a.doc.key),o=o.delete(a.doc.key)),a.type!==1&&(o=o.add(a.doc),d=o.indexOf(a.doc.key)),{type:oP(a.type),doc:l,oldIndex:u,newIndex:d}})}})(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new N(R.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=n._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=ds.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],r=[],s=[];return this.docs.forEach(i=>{i._document!==null&&(t.push(i._document),r.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),s.push(i.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function oP(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return U(61501,{type:n})}}function ng(n,e){return n instanceof ut&&e instanceof ut?n._firestore===e._firestore&&n._key.isEqual(e._key)&&(n._document===null?e._document===null:n._document.isEqual(e._document))&&n._converter===e._converter:n instanceof wt&&e instanceof wt&&n._firestore===e._firestore&&Oa(n.query,e.query)&&n.metadata.isEqual(e.metadata)&&n._snapshot.isEqual(e._snapshot)}wt._jsonSchemaVersion="firestore/querySnapshot/1.0",wt._jsonSchema={type:ke("string",wt._jsonSchemaVersion),bundleSource:ke("string","QuerySnapshot"),bundleName:ke("string"),bundle:ke("string")};var aP={maxAttempts:5};var Bu=class{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Pr(e)}set(e,t,r){this._verifyNotCommitted();let s=xr(e,this._firestore),i=qu(s.converter,t,r),o=Ma(this._dataReader,"WriteBatch.set",s._key,i,s.converter!==null,r);return this._mutations.push(o.toMutation(s._key,Ae.none())),this}update(e,t,r,...s){this._verifyNotCommitted();let i=xr(e,this._firestore),o;return o=typeof(t=te(t))=="string"||t instanceof Ot?Ou(this._dataReader,"WriteBatch.update",i._key,t,r,s):Vu(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(o.toMutation(i._key,Ae.exists(!0))),this}delete(e){this._verifyNotCommitted();let t=xr(e,this._firestore);return this._mutations=this._mutations.concat(new Mn(t._key,Ae.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 N(R.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}};function xr(n,e){if((n=te(n)).firestore!==e)throw new N(R.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}var eg=class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=Pr(e)}get(e){let t=xr(e,this._firestore),r=new Zm(this._firestore);return this._transaction.lookup([t._key]).then(s=>{if(!s||s.length!==1)return U(24041);let i=s[0];if(i.isFoundDocument())return new As(this._firestore,r,i.key,i,t.converter);if(i.isNoDocument())return new As(this._firestore,r,t._key,null,t.converter);throw U(18433,{doc:i})})}set(e,t,r){let s=xr(e,this._firestore),i=qu(s.converter,t,r),o=Ma(this._dataReader,"Transaction.set",s._key,i,s.converter!==null,r);return this._transaction.set(s._key,o),this}update(e,t,r,...s){let i=xr(e,this._firestore),o;return o=typeof(t=te(t))=="string"||t instanceof Ot?Ou(this._dataReader,"Transaction.update",i._key,t,r,s):Vu(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,o),this}delete(e){let t=xr(e,this._firestore);return this._transaction.delete(t._key),this}};var tg=class extends eg{constructor(e,t){super(e,t),this._firestore=e}get(e){let t=xr(e,this._firestore),r=new gn(this._firestore);return super.get(e).then(s=>new ut(this._firestore,r,t._key,s._document,new Ln(!1,!1),t.converter))}};function $I(n,e,t){n=ae(n,Ee);let r=Q(Q({},aP),t);(function(o){if(o.maxAttempts<1)throw new N(R.INVALID_ARGUMENT,"Max attempts must be at least 1")})(r);let s=$e(n);return TI(s,i=>e(new tg(n,i)),r)}function HI(n){n=ae(n,he);let e=ae(n.firestore,Ee),t=$e(e);return xm(t,n._key).then(r=>og(e,n,r))}function QI(n){n=ae(n,he);let e=ae(n.firestore,Ee),t=$e(e),r=new gn(e);return yI(t,n._key).then(s=>new ut(e,r,n._key,s,new Ln(s!==null&&s.hasLocalMutations,!0),n.converter))}function YI(n){n=ae(n,he);let e=ae(n.firestore,Ee),t=$e(e);return xm(t,n._key,{source:"server"}).then(r=>og(e,n,r))}function JI(n){n=ae(n,Ke);let e=ae(n.firestore,Ee),t=$e(e),r=new gn(e);return MI(n._query),km(t,n._query).then(s=>new wt(e,r,n,s))}function XI(n){n=ae(n,Ke);let e=ae(n.firestore,Ee),t=$e(e),r=new gn(e);return vI(t,n._query).then(s=>new wt(e,r,n,s))}function ZI(n){n=ae(n,Ke);let e=ae(n.firestore,Ee),t=$e(e),r=new gn(e);return km(t,n._query,{source:"server"}).then(s=>new wt(e,r,n,s))}function rg(n,e,t){n=ae(n,he);let r=ae(n.firestore,Ee),s=qu(n.converter,e,t),i=Pr(r);return Oi(r,[Ma(i,"setDoc",n._key,s,n.converter!==null,t).toMutation(n._key,Ae.none())])}function sg(n,e,t,...r){n=ae(n,he);let s=ae(n.firestore,Ee),i=Pr(s),o;return o=typeof(e=te(e))=="string"||e instanceof Ot?Ou(i,"updateDoc",n._key,e,t,r):Vu(i,"updateDoc",n._key,e),Oi(s,[o.toMutation(n._key,Ae.exists(!0))])}function eA(n){return Oi(ae(n.firestore,Ee),[new Mn(n._key,Ae.none())])}function tA(n,e){let t=ae(n.firestore,Ee),r=Ts(n),s=qu(n.converter,e),i=Pr(n.firestore);return Oi(t,[Ma(i,"addDoc",r._key,s,n.converter!==null,{}).toMutation(r._key,Ae.exists(!1))]).then(()=>r)}function ig(n,...e){n=te(n);let t={includeMetadataChanges:!1,source:"default"},r=0;typeof e[r]!="object"||Qm(e[r])||(t=e[r++]);let s={includeMetadataChanges:t.includeMetadataChanges,source:t.source};if(Qm(e[r])){let u=e[r];e[r]=u.next?.bind(u),e[r+1]=u.error?.bind(u),e[r+2]=u.complete?.bind(u)}let i,o,a;if(n instanceof he)o=ae(n.firestore,Ee),a=Es(n._key.path),i={next:u=>{e[r]&&e[r](og(o,n,u))},error:e[r+1],complete:e[r+2]};else{let u=ae(n,Ke);o=ae(u.firestore,Ee),a=u._query;let d=new gn(o);i={next:p=>{e[r]&&e[r](new wt(o,d,u,p))},error:e[r+1],complete:e[r+2]},MI(n._query)}let l=$e(o);return _I(l,a,s,i)}function nA(n,e){n=ae(n,Ee);let t=$e(n),r=Qm(e)?e:{next:e};return EI(t,r)}function Oi(n,e){let t=$e(n);return wI(t,e)}function og(n,e,t){let r=t.docs.get(e._key),s=new gn(n);return new ut(n,s,e._key,r,new Ln(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){bE(Qc),Qr(new At("firestore",(r,{instanceIdentifier:s,options:i})=>{let o=r.getProvider("app").getImmediate(),a=new Ee(new _l(r.getProvider("auth-internal")),new vl(o,r.getProvider("app-check-internal")),QE(o,s),o);return i=Q({useFetchStreams:t},i),a._setSettings(i),a},"PUBLIC").setMultipleInstances(!0)),Bt(NI,DI,e),Bt(NI,DI,"esm2020")})();var cP="@firebase/firestore-compat",lP="0.4.9";function dg(n,e){if(e===void 0)return{merge:!1};if(e.mergeFields!==void 0&&e.merge!==void 0)throw new N("invalid-argument",`Invalid options passed to function ${n}(): You cannot specify both "merge" and "mergeFields".`);return e}function rA(){if(typeof Uint8Array>"u")throw new N("unimplemented","Uint8Arrays are not available in this environment.")}function sA(){if(!im())throw new N("unimplemented","Blobs are unavailable in Firestore in this environment.")}var ju=class n{constructor(e){this._delegate=e}static fromBase64String(e){return sA(),new n(lt.fromBase64String(e))}static fromUint8Array(e){return rA(),new n(lt.fromUint8Array(e))}toBase64(){return sA(),this._delegate.toBase64()}toUint8Array(){return rA(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}};function ag(n){return uP(n,["next","error","complete"])}function uP(n,e){if(typeof n!="object"||n===null)return!1;let t=n;for(let r of e)if(r in t&&typeof t[r]=="function")return!0;return!1}var cg=class{enableIndexedDbPersistence(e,t){return Om(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return Mm(e._delegate)}clearIndexedDbPersistence(e){return Fm(e._delegate)}},Gu=class{constructor(e,t,r){this._delegate=t,this._persistenceProvider=r,this.INTERNAL={delete:()=>this.terminate()},e instanceof Dn||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){let t=this._delegate._getSettings();!e.merge&&t.host!==e.host&&vt("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&(e=Q(Q({},t),e),delete e.merge),this._delegate._setSettings(e)}useEmulator(e,t,r={}){Nm(this._delegate,e,t,r)}enableNetwork(){return Um(this._delegate)}disableNetwork(){return Bm(this._delegate)}enablePersistence(e){let t=!1,r=!1;return e&&(t=!!e.synchronizeTabs,r=!!e.experimentalForceOwningTab,gu("synchronizeTabs",t,"experimentalForceOwningTab",r)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,r)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return Lm(this._delegate)}onSnapshotsInSync(e){return nA(this._delegate,e)}get app(){if(!this._appCompat)throw new N("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Li(this,xu(this._delegate,e))}catch(t){throw ht(t,"collection()","Firestore.collection()")}}doc(e){try{return new _n(this,Ts(this._delegate,e))}catch(t){throw ht(t,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Ps(this,Dm(this._delegate,e))}catch(t){throw ht(t,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return $I(this._delegate,t=>e(new zu(this,t)))}batch(){return $e(this._delegate),new Ku(new Bu(this._delegate,e=>Oi(this._delegate,e)))}loadBundle(e){return Nu(this._delegate,e)}namedQuery(e){return Du(this._delegate,e).then(t=>t?new Ps(this,t):null)}},Mi=class extends Tr{constructor(e){super(),this.firestore=e}convertBytes(e){return new ju(new lt(e))}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return _n.forKey(t,this.firestore,null)}};function hP(n){Hp(n)}var zu=class{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Mi(e)}get(e){let t=Cs(e);return this._delegate.get(t).then(r=>new Ss(this._firestore,new ut(this._firestore._delegate,this._userDataWriter,r._key,r._document,r.metadata,t.converter)))}set(e,t,r){let s=Cs(e);return r?(dg("Transaction.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){let i=Cs(e);return arguments.length===2?this._delegate.update(i,t):this._delegate.update(i,t,r,...s),this}delete(e){let t=Cs(e);return this._delegate.delete(t),this}},Ku=class{constructor(e){this._delegate=e}set(e,t,r){let s=Cs(e);return r?(dg("WriteBatch.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){let i=Cs(e);return arguments.length===2?this._delegate.update(i,t):this._delegate.update(i,t,r,...s),this}delete(e){let t=Cs(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}},Fi=class n{constructor(e,t,r){this._firestore=e,this._userDataWriter=t,this._delegate=r}fromFirestore(e,t){let r=new kr(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Rs(this._firestore,r),t??{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){let r=n.INSTANCES,s=r.get(e);s||(s=new WeakMap,r.set(e,s));let i=s.get(t);return i||(i=new n(e,new Mi(e),t),s.set(t,i)),i}};Fi.INSTANCES=new WeakMap;var _n=class n{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Mi(e)}static forPath(e,t,r){if(e.length%2!==0)throw new N("invalid-argument",`Invalid document reference. Document references must have an even number of segments, but ${e.canonicalString()} has ${e.length}`);return new n(t,new he(t._delegate,r,new O(e)))}static forKey(e,t,r){return new n(t,new he(t._delegate,r,e))}get id(){return this._delegate.id}get parent(){return new Li(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Li(this.firestore,xu(this._delegate,e))}catch(t){throw ht(t,"collection()","DocumentReference.collection()")}}isEqual(e){return e=te(e),e instanceof he?ku(this._delegate,e):!1}set(e,t){t=dg("DocumentReference.set",t);try{return t?rg(this._delegate,e,t):rg(this._delegate,e)}catch(r){throw ht(r,"setDoc()","DocumentReference.set()")}}update(e,t,...r){try{return arguments.length===1?sg(this._delegate,e):sg(this._delegate,e,t,...r)}catch(s){throw ht(s,"updateDoc()","DocumentReference.update()")}}delete(){return eA(this._delegate)}onSnapshot(...e){let t=iA(e),r=oA(e,s=>new Ss(this.firestore,new ut(this.firestore._delegate,this._userDataWriter,s._key,s._document,s.metadata,this._delegate.converter)));return ig(this._delegate,t,r)}get(e){let t;return e?.source==="cache"?t=QI(this._delegate):e?.source==="server"?t=YI(this._delegate):t=HI(this._delegate),t.then(r=>new Ss(this.firestore,new ut(this.firestore._delegate,this._userDataWriter,r._key,r._document,r.metadata,this._delegate.converter)))}withConverter(e){return new n(this.firestore,e?this._delegate.withConverter(Fi.getInstance(this.firestore,e)):this._delegate.withConverter(null))}};function ht(n,e,t){return n.message=n.message.replace(e,t),n}function iA(n){for(let e of n)if(typeof e=="object"&&!ag(e))return e;return{}}function oA(n,e){let t;return ag(n[0])?t=n[0]:ag(n[1])?t=n[1]:typeof n[0]=="function"?t={next:n[0],error:n[1],complete:n[2]}:t={next:n[1],error:n[2],complete:n[3]},{next:r=>{t.next&&t.next(e(r))},error:t.error?.bind(t),complete:t.complete?.bind(t)}}var Ss=class{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new _n(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return ng(this._delegate,e._delegate)}},Rs=class extends Ss{data(e){let t=this._delegate.data(e);return this._delegate._converter||Yp(t!==void 0,"Document in a QueryDocumentSnapshot should exist"),t}},Ps=class n{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Mi(e)}where(e,t,r){try{return new n(this.firestore,Un(this._delegate,FI(e,t,r)))}catch(s){throw ht(s,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(e,t){try{return new n(this.firestore,Un(this._delegate,LI(e,t)))}catch(r){throw ht(r,/(orderBy|where)\(\)/,"Query.$1()")}}limit(e){try{return new n(this.firestore,Un(this._delegate,UI(e)))}catch(t){throw ht(t,"limit()","Query.limit()")}}limitToLast(e){try{return new n(this.firestore,Un(this._delegate,BI(e)))}catch(t){throw ht(t,"limitToLast()","Query.limitToLast()")}}startAt(...e){try{return new n(this.firestore,Un(this._delegate,qI(...e)))}catch(t){throw ht(t,"startAt()","Query.startAt()")}}startAfter(...e){try{return new n(this.firestore,Un(this._delegate,jI(...e)))}catch(t){throw ht(t,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new n(this.firestore,Un(this._delegate,GI(...e)))}catch(t){throw ht(t,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new n(this.firestore,Un(this._delegate,zI(...e)))}catch(t){throw ht(t,"endAt()","Query.endAt()")}}isEqual(e){return Oa(this._delegate,e._delegate)}get(e){let t;return e?.source==="cache"?t=XI(this._delegate):e?.source==="server"?t=ZI(this._delegate):t=JI(this._delegate),t.then(r=>new La(this.firestore,new wt(this.firestore._delegate,this._userDataWriter,this._delegate,r._snapshot)))}onSnapshot(...e){let t=iA(e),r=oA(e,s=>new La(this.firestore,new wt(this.firestore._delegate,this._userDataWriter,this._delegate,s._snapshot)));return ig(this._delegate,t,r)}withConverter(e){return new n(this.firestore,e?this._delegate.withConverter(Fi.getInstance(this.firestore,e)):this._delegate.withConverter(null))}},lg=class{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Rs(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}},La=class{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Ps(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new Rs(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(t=>new lg(this._firestore,t))}forEach(e,t){this._delegate.forEach(r=>{e.call(t,new Rs(this._firestore,r))})}isEqual(e){return ng(this._delegate,e._delegate)}},Li=class n extends Ps{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){let e=this._delegate.parent;return e?new _n(this.firestore,e):null}doc(e){try{return e===void 0?new _n(this.firestore,Ts(this._delegate)):new _n(this.firestore,Ts(this._delegate,e))}catch(t){throw ht(t,"doc()","CollectionReference.doc()")}}add(e){return tA(this._delegate,e).then(t=>new _n(this.firestore,t))}isEqual(e){return ku(this._delegate,e._delegate)}withConverter(e){return new n(this.firestore,e?this._delegate.withConverter(Fi.getInstance(this.firestore,e)):this._delegate.withConverter(null))}};function Cs(n){return ae(n,he)}var ug=class n{constructor(...e){this._delegate=new Ot(...e)}static documentId(){return new n(Se.keyField().canonicalString())}isEqual(e){return e=te(e),e instanceof Ot?this._delegate._internalPath.isEqual(e._internalPath):!1}};var hg=class n{static serverTimestamp(){let e=Km();return e._methodName="FieldValue.serverTimestamp",new n(e)}static delete(){let e=zm();return e._methodName="FieldValue.delete",new n(e)}static arrayUnion(...e){let t=Wm(...e);return t._methodName="FieldValue.arrayUnion",new n(t)}static arrayRemove(...e){let t=$m(...e);return t._methodName="FieldValue.arrayRemove",new n(t)}static increment(e){let t=Hm(e);return t._methodName="FieldValue.increment",new n(t)}constructor(e){this._delegate=e}isEqual(e){return this._delegate.isEqual(e._delegate)}};var dP={Firestore:Gu,GeoPoint:zt,Timestamp:me,Blob:ju,Transaction:zu,WriteBatch:Ku,DocumentReference:_n,DocumentSnapshot:Ss,Query:Ps,QueryDocumentSnapshot:Rs,QuerySnapshot:La,CollectionReference:Li,FieldPath:ug,FieldValue:hg,setLogLevel:hP,CACHE_SIZE_UNLIMITED:Vm};function fP(n,e){n.INTERNAL.registerComponent(new At("firestore-compat",t=>{let r=t.getProvider("app-compat").getImmediate(),s=t.getProvider("firestore").getImmediate();return e(r,s)},"PUBLIC").setServiceProps(Q({},dP)))}function pP(n){fP(n,(e,t)=>new Gu(e,t,new cg)),n.registerVersion(cP,lP)}pP(Ge);function mP(n,e=js){return new Zt(t=>{let r;return e!=null?e.schedule(()=>{r=n.onSnapshot({includeMetadataChanges:!0},t)}):r=n.onSnapshot({includeMetadataChanges:!0},t),()=>{r?.()}})}function aA(n,e){return mP(n,e)}function gP(n,e){return aA(n,e).pipe(Uc(void 0),Lc(),_e(t=>{let[r,s]=t;return s.exists?r?.exists?{payload:s,type:"modified"}:{payload:s,type:"added"}:{payload:s,type:"removed"}}))}function mg(n,e){return aA(n,e).pipe(_e(t=>({payload:t,type:"query"})))}var Wu=class{ref;afs;injector=se(An);constructor(e,t){this.ref=e,this.afs=t}set(e,t){return this.ref.set(e,t)}update(e){return this.ref.update(e)}delete(){return this.ref.delete()}collection(e,t){let r=this.ref.collection(e),{ref:s,query:i}=dA(r,t);return new Hu(s,i,this.afs)}snapshotChanges(){return gP(this.ref,this.afs.schedulers.outsideAngular).pipe(Pe(this.injector))}valueChanges(e={}){return this.snapshotChanges().pipe(_e(({payload:t})=>e.idField?tt(Q({},t.data()),{[e.idField]:t.id}):t.data()))}get(e){return Qn(this.ref.get(e)).pipe(Pe(this.injector))}};function $u(n,e){return mg(n,e).pipe(Uc(void 0),Lc(),_e(t=>{let[r,s]=t,i=s.payload.docChanges(),o=i.map(a=>({type:a.type,payload:a}));return r&&JSON.stringify(r.payload.metadata)!==JSON.stringify(s.payload.metadata)&&s.payload.docs.forEach((a,l)=>{let u=i.find(p=>p.doc.ref.isEqual(a.ref)),d=r?.payload.docs.find(p=>p.ref.isEqual(a.ref));u&&JSON.stringify(u.doc.metadata)===JSON.stringify(a.metadata)||!u&&d&&JSON.stringify(d.metadata)===JSON.stringify(a.metadata)||o.push({type:"modified",payload:{oldIndex:l,newIndex:l,type:"modified",doc:a}})}),o}))}function cA(n,e,t){return $u(n,t).pipe(Wr((r,s)=>_P(r,s.map(i=>i.payload),e),[]),Fc(),_e(r=>r.map(s=>({type:s.type,payload:s}))))}function _P(n,e,t){return e.forEach(r=>{t.includes(r.type)&&(n=yP(n,r))}),n}function fg(n,e,t,...r){let s=n.slice();return s.splice(e,t,...r),s}function yP(n,e){switch(e.type){case"added":if(!n[e.newIndex]?.doc.ref.isEqual(e.doc.ref))return fg(n,e.newIndex,0,e);break;case"modified":if(n[e.oldIndex]==null||n[e.oldIndex].doc.ref.isEqual(e.doc.ref))if(e.oldIndex!==e.newIndex){let t=n.slice();return t.splice(e.oldIndex,1),t.splice(e.newIndex,0,e),t}else return fg(n,e.newIndex,1,e);break;case"removed":if(n[e.oldIndex]?.doc.ref.isEqual(e.doc.ref))return fg(n,e.oldIndex,1);break}return n}function lA(n){return(!n||n.length===0)&&(n=["added","removed","modified"]),n}var Hu=class{ref;query;afs;injector=se(An);constructor(e,t,r){this.ref=e,this.query=t,this.afs=r}stateChanges(e){let t=$u(this.query,this.afs.schedulers.outsideAngular);return e&&e.length>0&&(t=t.pipe(_e(r=>r.filter(s=>e.includes(s.type))))),t.pipe(Uc(void 0),Lc(),Eo(([r,s])=>s.length>0||!r),_e(([,r])=>r),Pe(this.injector))}auditTrail(e){return this.stateChanges(e).pipe(Wr((t,r)=>[...t,...r],[]))}snapshotChanges(e){let t=lA(e);return cA(this.query,t,this.afs.schedulers.outsideAngular).pipe(Pe(this.injector))}valueChanges(e={}){return mg(this.query,this.afs.schedulers.outsideAngular).pipe(_e(t=>t.payload.docs.map(r=>e.idField?tt(Q({},r.data()),{[e.idField]:r.id}):r.data())),Pe(this.injector))}get(e){return Qn(this.query.get(e)).pipe(Pe(this.injector))}add(e){return this.ref.add(e)}doc(e){return new Wu(this.ref.doc(e),this.afs)}},pg=class{query;afs;injector=se(An);constructor(e,t){this.query=e,this.afs=t}stateChanges(e){return!e||e.length===0?$u(this.query,this.afs.schedulers.outsideAngular).pipe(Pe(this.injector)):$u(this.query,this.afs.schedulers.outsideAngular).pipe(_e(t=>t.filter(r=>e.includes(r.type))),Eo(t=>t.length>0),Pe(this.injector))}auditTrail(e){return this.stateChanges(e).pipe(Wr((t,r)=>[...t,...r],[]))}snapshotChanges(e){let t=lA(e);return cA(this.query,t,this.afs.schedulers.outsideAngular).pipe(Pe(this.injector))}valueChanges(e={}){return mg(this.query,this.afs.schedulers.outsideAngular).pipe(_e(r=>r.payload.docs.map(s=>e.idField?Q({[e.idField]:s.id},s.data()):s.data())),Pe(this.injector))}get(e){return Qn(this.query.get(e)).pipe(Pe(this.injector))}},uA=new De("angularfire2.enableFirestorePersistence"),hA=new De("angularfire2.firestore.persistenceSettings"),vP=new De("angularfire2.firestore.settings"),wP=new De("angularfire2.firestore.use-emulator");function dA(n,e=t=>t){return{query:e(n),ref:n}}var EP=(()=>{class n{schedulers;firestore;persistenceEnabled$;ngZone=se(Ve);constructor(t,r,s,i,o,a,l,u,d,p,m,v,S,x,k,q,G){this.schedulers=l;let L=Xr(t,a,r),H=d;p&&Uo(L,a,m,S,x,k,v,q),[this.firestore,this.persistenceEnabled$]=$s(`${L.name}.firestore`,"AngularFirestore",L.name,()=>{let J=a.runOutsideAngular(()=>L.firestore());if(i&&J.settings(i),H&&J.useEmulator(...H),s&&!Bc(o)){let oe=()=>{try{return Qn(J.enablePersistence(u||void 0).then(()=>!0,()=>!1))}catch(E){return typeof console<"u"&&console.warn(E),tn(!1)}};return[J,a.runOutsideAngular(oe)]}else return[J,tn(!1)]},[i,H,s])}collection(t,r){let s;typeof t=="string"?s=this.firestore.collection(t):s=t;let{ref:i,query:o}=dA(s,r),a=this.ngZone.run(()=>i);return new Hu(a,o,this)}collectionGroup(t,r){let s=r||(o=>o),i=this.firestore.collectionGroup(t);return new pg(s(i),this)}doc(t){let r;typeof t=="string"?r=this.firestore.doc(t):r=t;let s=this.ngZone.run(()=>r);return new Wu(s,this)}createId(){return this.firestore.collection("_").doc().id}static \u0275fac=function(r){return new(r||n)(K(er),K(tr,8),K(uA,8),K(vP,8),K(Yn),K(Ve),K(Jr),K(hA,8),K(wP,8),K(Bo,8),K(Do,8),K(Vo,8),K(Oo,8),K(Mo,8),K(Fo,8),K(Lo,8),K(rr,8))};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"any"})}return n})(),IV=(()=>{class n{constructor(){Ge.registerVersion("angularfire",on.full,"fst-compat")}static enablePersistence(t){return{ngModule:n,providers:[{provide:uA,useValue:!0},{provide:hA,useValue:t}]}}static \u0275fac=function(r){return new(r||n)};static \u0275mod=rn({type:n});static \u0275inj=nn({providers:[EP]})}return n})();var fA="@firebase/database",pA="1.1.3";var S_="";function R_(n){S_=n}var Ig=class{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){t==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Oe(t))}get(e){let t=this.domStorage_.getItem(this.prefixedName_(e));return t==null?null:zc(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}};var Ag=class{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){t==null?delete this.cache_[e]:this.cache_[e]=t}get(e){return Nt(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}};var KA=function(n){try{if(typeof window<"u"&&typeof window[n]<"u"){let e=window[n];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new Ig(e)}}catch{}return new Ag},ks=KA("localStorage"),bg=KA("sessionStorage");var ji=new Zn("@firebase/database"),WA=(function(){let n=1;return function(){return n++}})(),$A=function(n){let e=$v(n),t=new Wv;t.update(e);let r=t.digest();return qc.encodeByteArray(r)},cc=function(...n){let e="";for(let t=0;t{document.readyState==="complete"&&t()}),window.attachEvent("onload",t))}},Or="[MIN_NAME]",Bn="[MAX_NAME]",Vs=function(n,e){if(n===e)return 0;if(n===Or||e===Bn)return-1;if(e===Or||n===Bn)return 1;{let t=gA(n),r=gA(e);return t!==null?r!==null?t-r===0?n.length-e.length:t-r:-1:r!==null?1:nt?r.push(n.substring(s,t)):r.push(n.substring(s,s+e));return r};function Je(n,e){for(let t in n)n.hasOwnProperty(t)&&e(t,n[t])}var YA=function(n){V(!Th(n),"Invalid JSON number");let e=11,t=52,r=(1<=Math.pow(2,1-r)?(a=Math.min(Math.floor(Math.log(n)/Math.LN2),r),i=a+r,o=Math.round(n*Math.pow(2,t-a)-Math.pow(2,t))):(i=0,o=Math.round(n/Math.pow(2,1-r-t))));let u=[];for(l=t;l;l-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(l=e;l;l-=1)u.push(i%2?1:0),i=Math.floor(i/2);u.push(s?1:0),u.reverse();let d=u.join(""),p="";for(l=0;l<64;l+=8){let m=parseInt(d.substr(l,8),2).toString(16);m.length===1&&(m="0"+m),p=p+m}return p.toLowerCase()},bP=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},CP=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function SP(n,e){let t="Unknown Error";n==="too_big"?t="The data requested exceeds the maximum size that can be accessed with a single request.":n==="permission_denied"?t="Client doesn't have permission to access the desired data.":n==="unavailable"&&(t="The service is unavailable");let r=new Error(n+" at "+e._path.toString()+": "+t);return r.code=n.toUpperCase(),r}var RP=new RegExp("^-?(0*)\\d{1,10}$"),PP=-2147483648,xP=2147483647,gA=function(n){if(RP.test(n)){let e=Number(n);if(e>=PP&&e<=xP)return e}return null},Ji=function(n){try{n()}catch(e){setTimeout(()=>{let t=e.stack||"";throw st("Exception was thrown by user callback.",t),e},Math.floor(0))}},kP=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Ga=function(n,e){let t=setTimeout(n,e);return typeof t=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(t):typeof t=="object"&&t.unref&&t.unref(),t};var Sg=class{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,Hc(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(r=>this.appCheck=r)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((t,r)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,r):t(null)},0)})}addTokenChangeListener(e){this.appCheckProvider?.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){st(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}};var Rg=class{constructor(e,t,r){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(s=>this.auth_=s)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(t=>t&&t.code==="auth/token-not-initialized"?(Ye("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(t)):new Promise((t,r)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,r):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',st(e)}},za=(()=>{class n{constructor(t){this.accessToken=t}getToken(t){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(t){t(this.accessToken)}removeTokenChangeListener(t){}notifyForInvalidToken(){}}n.OWNER="owner";return n})(),Yu="5",JA="v",XA="s",ZA="r",eb="f",tb=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,nb="ls",rb="p",Pg="ac",sb="websocket",ib="long_polling";var Ju=class{constructor(e,t,r,s,i=!1,o="",a=!1,l=!1,u=null){this.secure=t,this.namespace=r,this.webSocketOnly=s,this.nodeAdmin=i,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=l,this.emulatorOptions=u,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ks.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&ks.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}};function NP(n){return n.host!==n.internalHost||n.isCustomHost()||n.includeNamespaceInQueryParams}function ob(n,e,t){V(typeof e=="string","typeof type must == string"),V(typeof t=="object","typeof params must == object");let r;if(e===sb)r=(n.secure?"wss://":"ws://")+n.internalHost+"/.ws?";else if(e===ib)r=(n.secure?"https://":"http://")+n.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);NP(n)&&(t.ns=n.namespace);let s=[];return Je(t,(i,o)=>{s.push(i+"="+o)}),r+s.join("&")}var xg=class{constructor(){this.counters_={}}incrementCounter(e,t=1){Nt(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return Uv(this.counters_)}};var gg={},_g={};function x_(n){let e=n.toString();return gg[e]||(gg[e]=new xg),gg[e]}function DP(n,e){let t=n.toString();return _g[t]||(_g[t]=e()),_g[t]}var kg=class{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse{this.onMessage_(r[s])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}};var _A="start",VP="close",OP="pLPCommand",MP="pRTLPCB",ab="id",cb="pw",lb="ser",FP="cb",LP="seg",UP="ts",BP="d",qP="dframe",ub=1870,hb=30,jP=ub-hb,GP=25e3,zP=3e4,Ha=class n{constructor(e,t,r,s,i,o,a){this.connId=e,this.repoInfo=t,this.applicationId=r,this.appCheckToken=s,this.authToken=i,this.transportSessionId=o,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=lc(e),this.stats_=x_(t),this.urlFn=l=>(this.appCheckToken&&(l[Pg]=this.appCheckToken),ob(t,ib,l))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new kg(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(zP)),IP(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Ng((...i)=>{let[o,a,l,u,d]=i;if(this.incrementIncomingBytes_(i),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===_A)this.id=a,this.password=l;else if(o===VP)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...i)=>{let[o,a]=i;this.incrementIncomingBytes_(i),this.myPacketOrderer.handleResponse(o,a)},()=>{this.onClosed_()},this.urlFn);let r={};r[_A]="t",r[lb]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(r[FP]=this.scriptTagHolder.uniqueCallbackIdentifier),r[JA]=Yu,this.transportSessionId&&(r[XA]=this.transportSessionId),this.lastSessionId&&(r[nb]=this.lastSessionId),this.applicationId&&(r[rb]=this.applicationId),this.appCheckToken&&(r[Pg]=this.appCheckToken),typeof location<"u"&&location.hostname&&tb.test(location.hostname)&&(r[ZA]=eb);let s=this.urlFn(r);this.log_("Connecting via long-poll to "+s),this.scriptTagHolder.addTag(s,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){n.forceAllow_=!0}static forceDisallow(){n.forceDisallow_=!0}static isAvailable(){return sn()?!1:n.forceAllow_?!0:!n.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!bP()&&!CP()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){let t=Oe(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let r=Lv(t),s=QA(r,jP);for(let i=0;idocument.domain="'+document.domain+'";<\/script>');let o=""+i+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(a){Ye("frame writing exception"),a.stack&&Ye(a.stack),Ye(a)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||Ye("No IE domain setting required")}catch{let r=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+r+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;let e={};e[ab]=this.myID,e[cb]=this.myPW,e[lb]=this.currentSerial;let t=this.urlFn(e),r="",s=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+hb+r.length<=ub;){let o=this.pendingSegs.shift();r=r+"&"+LP+s+"="+o.seg+"&"+UP+s+"="+o.ts+"&"+BP+s+"="+o.d,s++}return t=t+r,this.addLongPollTag_(t,this.currentSerial),!0}else return!1}enqueueSegment(e,t,r){this.pendingSegs.push({seg:e,ts:t,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let r=()=>{this.outstandingRequests.delete(t),this.newRequest_()},s=setTimeout(r,Math.floor(GP)),i=()=>{clearTimeout(s),r()};this.addTag(e,i)}addTag(e,t){sn()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;let r=this.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){let s=r.readyState;(!s||s==="loaded"||s==="complete")&&(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),t())},r.onerror=()=>{Ye("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(r)}catch{}},Math.floor(1))}};var KP=16384,WP=45e3,Xu=null;typeof MozWebSocket<"u"?Xu=MozWebSocket:typeof WebSocket<"u"&&(Xu=WebSocket);var Bi=(()=>{class n{constructor(t,r,s,i,o,a,l){this.connId=t,this.applicationId=s,this.appCheckToken=i,this.authToken=o,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=lc(this.connId),this.stats_=x_(r),this.connURL=n.connectionURL_(r,a,l,i,s),this.nodeAdmin=r.nodeAdmin}static connectionURL_(t,r,s,i,o){let a={};return a[JA]=Yu,!sn()&&typeof location<"u"&&location.hostname&&tb.test(location.hostname)&&(a[ZA]=eb),r&&(a[XA]=r),s&&(a[nb]=s),i&&(a[Pg]=i),o&&(a[rb]=o),ob(t,sb,a)}open(t,r){this.onDisconnect=r,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ks.set("previous_websocket_failure",!0);try{let s;if(sn()){let i=this.nodeAdmin?"AdminNode":"Node";s={headers:{"User-Agent":`Firebase/${Yu}/${S_}/${process.platform}/${i}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(s.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(s.headers["X-Firebase-AppCheck"]=this.appCheckToken);let o=process.env,a=this.connURL.indexOf("wss://")===0?o.HTTPS_PROXY||o.https_proxy:o.HTTP_PROXY||o.http_proxy;a&&(s.proxy={origin:a})}this.mySock=new Xu(this.connURL,[],s)}catch(s){this.log_("Error instantiating WebSocket.");let i=s.message||s.data;i&&this.log_(i),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=s=>{this.handleIncomingFrame(s)},this.mySock.onerror=s=>{this.log_("WebSocket error. Closing connection.");let i=s.message||s.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){n.forceDisallow_=!0}static isAvailable(){let t=!1;if(typeof navigator<"u"&&navigator.userAgent){let r=/Android ([0-9]{0,}\.[0-9]{0,})/,s=navigator.userAgent.match(r);s&&s.length>1&&parseFloat(s[1])<4.4&&(t=!0)}return!t&&Xu!==null&&!n.forceDisallow_}static previouslyFailed(){return ks.isInMemoryStorage||ks.get("previous_websocket_failure")===!0}markConnectionHealthy(){ks.remove("previous_websocket_failure")}appendFrame_(t){if(this.frames.push(t),this.frames.length===this.totalFrames){let r=this.frames.join("");this.frames=null;let s=zc(r);this.onMessage(s)}}handleNewFrameCount_(t){this.totalFrames=t,this.frames=[]}extractFrameCount_(t){if(V(this.frames===null,"We already have a frame buffer"),t.length<=6){let r=Number(t);if(!isNaN(r))return this.handleNewFrameCount_(r),null}return this.handleNewFrameCount_(1),t}handleIncomingFrame(t){if(this.mySock===null)return;let r=t.data;if(this.bytesReceived+=r.length,this.stats_.incrementCounter("bytes_received",r.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(r);else{let s=this.extractFrameCount_(r);s!==null&&this.appendFrame_(s)}}send(t){this.resetKeepAlive();let r=Oe(t);this.bytesSent+=r.length,this.stats_.incrementCounter("bytes_sent",r.length);let s=QA(r,KP);s.length>1&&this.sendString_(String(s.length));for(let i=0;i{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(WP))}sendString_(t){try{this.mySock.send(t)}catch(r){this.log_("Exception thrown from WebSocket.send():",r.message||r.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}n.responsesRequiredToBeHealthy=2,n.healthyTimeout=3e4;return n})(),db=(()=>{class n{static get ALL_TRANSPORTS(){return[Ha,Bi]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(t){this.initTransports_(t)}initTransports_(t){let r=Bi&&Bi.isAvailable(),s=r&&!Bi.previouslyFailed();if(t.webSocketOnly&&(r||st("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),s=!0),s)this.transports_=[Bi];else{let i=this.transports_=[];for(let o of n.ALL_TRANSPORTS)o&&o.isAvailable()&&i.push(o);n.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}n.globalTransportInitialized_=!1;return n})(),$P=6e4,HP=5e3,QP=10*1024,YP=100*1024,yg="t",yA="d",JP="s",vA="r",XP="e",wA="o",EA="a",TA="n",IA="p",ZP="h",Dg=class{constructor(e,t,r,s,i,o,a,l,u,d){this.id=e,this.repoInfo_=t,this.applicationId_=r,this.appCheckToken_=s,this.authToken_=i,this.onMessage_=o,this.onReady_=a,this.onDisconnect_=l,this.onKill_=u,this.lastSessionId=d,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=lc("c:"+this.id+":"),this.transportManager_=new db(t),this.log_("Connection created"),this.start_()}start_(){let e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,r)},Math.floor(0));let s=e.healthyTimeout||0;s>0&&(this.healthyTimeout_=Ga(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>YP?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>QP?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(s)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){let t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(yg in e){let t=e[yg];t===EA?this.upgradeIfSecondaryHealthy_():t===vA?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):t===wA&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=Ua("t",e),r=Ua("d",e);if(t==="c")this.onSecondaryControl_(r);else if(t==="d")this.pendingDataMessages.push(r);else throw new Error("Unknown protocol layer: "+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:IA,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:EA,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:TA,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=Ua("t",e),r=Ua("d",e);t==="c"?this.onControl_(r):t==="d"&&this.onDataMessage_(r)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){let t=Ua(yg,e);if(yA in e){let r=e[yA];if(t===ZP){let s=Q({},r);this.repoInfo_.isUsingEmulator&&(s.h=this.repoInfo_.host),this.onHandshake_(s)}else if(t===TA){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let s=0;s{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor($P))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Ga(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(HP))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:IA,d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ks.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}};var Zu=class{put(e,t,r,s){}merge(e,t,r,s){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,r){}onDisconnectMerge(e,t,r){}onDisconnectCancel(e,t){}reportStats(e){}};var eh=class{constructor(e){this.allowedEvents_=e,this.listeners_={},V(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let r=[...this.listeners_[e]];for(let s=0;st===e),"Unknown event: "+e)}};var th=class n extends eh{static getInstance(){return new n}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!Pd()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return V(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}};var AA=32,bA=768,ue=class{constructor(e,t){if(t===void 0){this.pieces_=e.split("/");let r=0;for(let s=0;s0&&(this.pieces_[r]=this.pieces_[s],r++);this.pieces_.length=r,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t=n.pieces_.length?null:n.pieces_[n.pieceNum_]}function Mr(n){return n.pieces_.length-n.pieceNum_}function ge(n){let e=n.pieceNum_;return e=n.pieces_.length)return null;let e=[];for(let t=n.pieceNum_;t0&&t.push(r[s])}return new ue(t,0)}function ee(n){return n.pieceNum_>=n.pieces_.length}function dt(n,e){let t=Z(n),r=Z(e);if(t===null)return e;if(t===r)return dt(ge(n),ge(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+n+")")}function tx(n,e){let t=Qa(n,0),r=Qa(e,0);for(let s=0;sMr(e))return!1;for(;t0&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=Po(e),pb(n)}function rx(n){let e=n.parts_.pop();n.byteLength_-=Po(e),n.parts_.length>0&&(n.byteLength_-=1)}function pb(n){if(n.byteLength_>bA)throw new Error(n.errorPrefix_+"has a key path longer than "+bA+" bytes ("+n.byteLength_+").");if(n.parts_.length>AA)throw new Error(n.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+AA+") or object contains a cycle "+xs(n))}function xs(n){return n.parts_.length===0?"":"in property '"+n.parts_.join(".")+"'"}var Og=class n extends eh{static getInstance(){return new n}constructor(){super(["visible"]);let e,t;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(t="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(t="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(t="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{let r=!document[e];r!==this.visible_&&(this.visible_=r,this.trigger("visible",r))},!1)}getInitialEvent(e){return V(e==="visible","Unknown event type: "+e),[this.visible_]}};var Ba=1e3,sx=300*1e3,CA=30*1e3,ix=1.3,ox=3e4,ax="server_kill",SA=3,D_=(()=>{class n extends Zu{constructor(t,r,s,i,o,a,l,u){if(super(),this.repoInfo_=t,this.applicationId_=r,this.onDataUpdate_=s,this.onConnectStatus_=i,this.onServerInfoUpdate_=o,this.authTokenProvider_=a,this.appCheckTokenProvider_=l,this.authOverride_=u,this.id=n.nextPersistentConnectionId_++,this.log_=lc("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=Ba,this.maxReconnectDelay_=sx,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,u&&!sn())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Og.getInstance().on("visible",this.onVisible_,this),t.host.indexOf("fblocal")===-1&&th.getInstance().on("online",this.onOnline_,this)}sendRequest(t,r,s){let i=++this.requestNumber_,o={r:i,a:t,b:r};this.log_(Oe(o)),V(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(o),s&&(this.requestCBHash_[i]=s)}get(t){this.initConnection_();let r=new Qe,i={action:"g",request:{p:t._path.toString(),q:t._queryObject},onComplete:a=>{let l=a.d;a.s==="ok"?r.resolve(l):r.reject(l)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;let o=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(o),r.promise}listen(t,r,s,i){this.initConnection_();let o=t._queryIdentifier,a=t._path.toString();this.log_("Listen called for "+a+" "+o),this.listens.has(a)||this.listens.set(a,new Map),V(t._queryParams.isDefault()||!t._queryParams.loadsAllData(),"listen() called for non-default but complete query"),V(!this.listens.get(a).has(o),"listen() called twice for same path/queryId.");let l={onComplete:i,hashFn:r,query:t,tag:s};this.listens.get(a).set(o,l),this.connected_&&this.sendListen_(l)}sendGet_(t){let r=this.outstandingGets_[t];this.sendRequest("g",r.request,s=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),r.onComplete&&r.onComplete(s)})}sendListen_(t){let r=t.query,s=r._path.toString(),i=r._queryIdentifier;this.log_("Listen on "+s+" for "+i);let o={p:s},a="q";t.tag&&(o.q=r._queryObject,o.t=t.tag),o.h=t.hashFn(),this.sendRequest(a,o,l=>{let u=l.d,d=l.s;n.warnOnListenWarnings_(u,r),(this.listens.get(s)&&this.listens.get(s).get(i))===t&&(this.log_("listen response",l),d!=="ok"&&this.removeListen_(s,i),t.onComplete&&t.onComplete(d,u))})}static warnOnListenWarnings_(t,r){if(t&&typeof t=="object"&&Nt(t,"w")){let s=Xn(t,"w");if(Array.isArray(s)&&~s.indexOf("no_index")){let i='".indexOn": "'+r._queryParams.getIndex().toString()+'"',o=r._path.toString();st(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${o} to your security rules for better performance.`)}}}refreshAuthToken(t){this.authToken_=t,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(t)}reduceReconnectDelayIfAdminCredential_(t){(t&&t.length===40||zv(t))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=CA)}refreshAppCheckToken(t){this.appCheckToken_=t,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let t=this.authToken_,r=Gv(t)?"auth":"gauth",s={cred:t};this.authOverride_===null?s.noauth=!0:typeof this.authOverride_=="object"&&(s.authvar=this.authOverride_),this.sendRequest(r,s,i=>{let o=i.s,a=i.d||"error";this.authToken_===t&&(o==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(o,a))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},t=>{let r=t.s,s=t.d||"error";r==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(r,s)})}unlisten(t,r){let s=t._path.toString(),i=t._queryIdentifier;this.log_("Unlisten called for "+s+" "+i),V(t._queryParams.isDefault()||!t._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(s,i)&&this.connected_&&this.sendUnlisten_(s,i,t._queryObject,r)}sendUnlisten_(t,r,s,i){this.log_("Unlisten on "+t+" for "+r);let o={p:t},a="n";i&&(o.q=s,o.t=i),this.sendRequest(a,o)}onDisconnectPut(t,r,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",t,r,s):this.onDisconnectRequestQueue_.push({pathString:t,action:"o",data:r,onComplete:s})}onDisconnectMerge(t,r,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",t,r,s):this.onDisconnectRequestQueue_.push({pathString:t,action:"om",data:r,onComplete:s})}onDisconnectCancel(t,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",t,null,r):this.onDisconnectRequestQueue_.push({pathString:t,action:"oc",data:null,onComplete:r})}sendOnDisconnect_(t,r,s,i){let o={p:r,d:s};this.log_("onDisconnect "+t,o),this.sendRequest(t,o,a=>{i&&setTimeout(()=>{i(a.s,a.d)},Math.floor(0))})}put(t,r,s,i){this.putInternal("p",t,r,s,i)}merge(t,r,s,i){this.putInternal("m",t,r,s,i)}putInternal(t,r,s,i,o){this.initConnection_();let a={p:r,d:s};o!==void 0&&(a.h=o),this.outstandingPuts_.push({action:t,request:a,onComplete:i}),this.outstandingPutCount_++;let l=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(l):this.log_("Buffering put: "+r)}sendPut_(t){let r=this.outstandingPuts_[t].action,s=this.outstandingPuts_[t].request,i=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(r,s,o=>{this.log_(r+" response",o),delete this.outstandingPuts_[t],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(o.s,o.d)})}reportStats(t){if(this.connected_){let r={c:t};this.log_("reportStats",r),this.sendRequest("s",r,s=>{if(s.s!=="ok"){let o=s.d;this.log_("reportStats","Error sending stats: "+o)}})}}onDataMessage_(t){if("r"in t){this.log_("from server: "+Oe(t));let r=t.r,s=this.requestCBHash_[r];s&&(delete this.requestCBHash_[r],s(t.b))}else{if("error"in t)throw"A server-side error has occurred: "+t.error;"a"in t&&this.onDataPush_(t.a,t.b)}}onDataPush_(t,r){this.log_("handleServerMessage",t,r),t==="d"?this.onDataUpdate_(r.p,r.d,!1,r.t):t==="m"?this.onDataUpdate_(r.p,r.d,!0,r.t):t==="c"?this.onListenRevoked_(r.p,r.q):t==="ac"?this.onAuthRevoked_(r.s,r.d):t==="apc"?this.onAppCheckRevoked_(r.s,r.d):t==="sd"?this.onSecurityDebugPacket_(r):Cg("Unrecognized action received from server: "+Oe(t)+` Are you using the latest client?`)}onReady_(t,r){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(t),this.lastSessionId=r,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(t){V(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(t))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(t){t&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=Ba,this.realtime_||this.scheduleConnect_(0)),this.visible_=t}onOnline_(t){t?(this.log_("Browser went online."),this.reconnectDelay_=Ba,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>ox&&(this.reconnectDelay_=Ba),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let t=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_),r=Math.max(0,this.reconnectDelay_-t);r=Math.random()*r,this.log_("Trying to reconnect in "+r+"ms"),this.scheduleConnect_(r),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*ix)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let t=this.onDataMessage_.bind(this),r=this.onReady_.bind(this),s=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+n.nextConnectionId_++,o=this.lastSessionId,a=!1,l=null,u=function(){l?l.close():(a=!0,s())},d=function(m){V(l,"sendRequest call when we're not connected not allowed."),l.sendRequest(m)};this.realtime_={close:u,sendRequest:d};let p=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[m,v]=await Promise.all([this.authTokenProvider_.getToken(p),this.appCheckTokenProvider_.getToken(p)]);a?Ye("getToken() completed but was canceled"):(Ye("getToken() completed. Creating connection."),this.authToken_=m&&m.accessToken,this.appCheckToken_=v&&v.token,l=new Dg(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,t,r,s,S=>{st(S+" ("+this.repoInfo_.toString()+")"),this.interrupt(ax)},o))}catch(m){this.log_("Failed to get token: "+m),a||(this.repoInfo_.nodeAdmin&&st(m),u())}}}interrupt(t){Ye("Interrupting connection for reason: "+t),this.interruptReasons_[t]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(t){Ye("Resuming connection for reason: "+t),delete this.interruptReasons_[t],Kc(this.interruptReasons_)&&(this.reconnectDelay_=Ba,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(t){let r=t-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:r})}cancelSentTransactions_(){for(let t=0;tP_(o)).join("$"):s="default";let i=this.removeListen_(t,s);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(t,r){let s=new ue(t).toString(),i;if(this.listens.has(s)){let o=this.listens.get(s);i=o.get(r),o.delete(r),o.size===0&&this.listens.delete(s)}else i=void 0;return i}onAuthRevoked_(t,r){Ye("Auth token revoked: "+t+"/"+r),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(t==="invalid_token"||t==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=SA&&(this.reconnectDelay_=CA,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(t,r){Ye("App check token revoked: "+t+"/"+r),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(t==="invalid_token"||t==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=SA&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(t){this.securityDebugCallback_?this.securityDebugCallback_(t):"msg"in t&&console.log("FIREBASE: "+t.msg.replace(` `,` FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(let t of this.listens.values())for(let r of t.values())this.sendListen_(r);for(let t=0;t0}peek(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}},Qt=(()=>{class n{constructor(t,r,s,i,o){this.key=t,this.value=r,this.color=s??n.RED,this.left=i??Ft.EMPTY_NODE,this.right=o??Ft.EMPTY_NODE}copy(t,r,s,i,o){return new n(t??this.key,r??this.value,s??this.color,i??this.left,o??this.right)}count(){return this.left.count()+1+this.right.count()}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,r,s){let i=this,o=s(t,i.key);return o<0?i=i.copy(null,null,null,i.left.insert(t,r,s),null):o===0?i=i.copy(null,r,null,null,null):i=i.copy(null,null,null,null,i.right.insert(t,r,s)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Ft.EMPTY_NODE;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,r){let s,i;if(s=this,r(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,r),null);else{if(s.left.isRed_()&&(s=s.rotateRight_()),!s.right.isEmpty()&&!s.right.isRed_()&&!s.right.left.isRed_()&&(s=s.moveRedRight_()),r(t,s.key)===0){if(s.right.isEmpty())return Ft.EMPTY_NODE;i=s.right.min_(),s=s.copy(i.key,i.value,null,null,s.right.removeMin_())}s=s.copy(null,null,null,null,s.right.remove(t,r))}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_(){let t=this.copy(null,null,n.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight_(){let t=this.copy(null,null,n.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip_(){let t=this.left.copy(null,null,!this.left.color,null,null),r=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,r)}checkMaxDepth_(){let t=this.check_();return Math.pow(2,t)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");let t=this.left.check_();if(t!==this.right.check_())throw new Error("Black depths differ");return t+(this.isRed_()?0:1)}}return n.RED=!0,n.BLACK=!1,n})(),Mg=class{copy(e,t,r,s,i){return this}insert(e,t,r){return new Qt(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}},Ft=class n{constructor(e,t=n.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new n(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Qt.BLACK,null,null))}remove(e){return new n(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Qt.BLACK,null,null))}get(e){let t,r=this.root_;for(;!r.isEmpty();){if(t=this.comparator_(e,r.key),t===0)return r.value;t<0?r=r.left:t>0&&(r=r.right)}return null}getPredecessorKey(e){let t,r=this.root_,s=null;for(;!r.isEmpty();)if(t=this.comparator_(e,r.key),t===0){if(r.left.isEmpty())return s?s.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}else t<0?r=r.left:t>0&&(s=r,r=r.right);throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new qi(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new qi(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new qi(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new qi(this.root_,null,this.comparator_,!0,e)}};Ft.EMPTY_NODE=new Mg;function cx(n,e){return Vs(n.name,e.name)}function V_(n,e){return Vs(n,e)}var Fg;function lx(n){Fg=n}var mb=function(n){return typeof n=="number"?"number:"+YA(n):"string:"+n},gb=function(n){if(n.isLeafNode()){let e=n.val();V(typeof e=="string"||typeof e=="number"||typeof e=="object"&&Nt(e,".sv"),"Priority must be a string or number.")}else V(n===Fg||n.isEmpty(),"priority of unexpected type.");V(n===Fg||n.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};var RA,zi=(()=>{class n{static set __childrenNodeConstructor(t){RA=t}static get __childrenNodeConstructor(){return RA}constructor(t,r=n.__childrenNodeConstructor.EMPTY_NODE){this.value_=t,this.priorityNode_=r,this.lazyHash_=null,V(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),gb(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(t){return new n(this.value_,t)}getImmediateChild(t){return t===".priority"?this.priorityNode_:n.__childrenNodeConstructor.EMPTY_NODE}getChild(t){return ee(t)?this:Z(t)===".priority"?this.priorityNode_:n.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(t,r){return null}updateImmediateChild(t,r){return t===".priority"?this.updatePriority(r):r.isEmpty()&&t!==".priority"?this:n.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(t,r).updatePriority(this.priorityNode_)}updateChild(t,r){let s=Z(t);return s===null?r:r.isEmpty()&&s!==".priority"?this:(V(s!==".priority"||Mr(t)===1,".priority must be the last token in a path"),this.updateImmediateChild(s,n.__childrenNodeConstructor.EMPTY_NODE.updateChild(ge(t),r)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(t,r){return!1}val(t){return t&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let t="";this.priorityNode_.isEmpty()||(t+="priority:"+mb(this.priorityNode_.val())+":");let r=typeof this.value_;t+=r+":",r==="number"?t+=YA(this.value_):t+=this.value_,this.lazyHash_=$A(t)}return this.lazyHash_}getValue(){return this.value_}compareTo(t){return t===n.__childrenNodeConstructor.EMPTY_NODE?1:t instanceof n.__childrenNodeConstructor?-1:(V(t.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(t))}compareToLeafNode_(t){let r=typeof t.value_,s=typeof this.value_,i=n.VALUE_TYPE_ORDER.indexOf(r),o=n.VALUE_TYPE_ORDER.indexOf(s);return V(i>=0,"Unknown leaf type: "+r),V(o>=0,"Unknown leaf type: "+s),i===o?s==="object"?0:this.value_parseInt(Math.log(i)/dx,10),r=i=>parseInt(Array(i+1).join("1"),2);this.count=t(e+1),this.current_=this.count-1;let s=r(this.count);this.bits_=e+1&s}nextBitIsOne(){let e=!(this.bits_&1<{let o=Xn(this.indexSet_,i);if(V(o,"Missing index implementation for "+i),s===Ui)if(o.isDefinedOn(e.node)){let a=[],l=t.getIterator(ne.Wrap),u=l.getNext();for(;u;)u.name!==e.name&&a.push(u),u=l.getNext();return a.push(e),rh(a,o.getCompare())}else return Ui;else{let a=t.get(e.name),l=s;return a&&(l=l.remove(new ne(e.name,a))),l.insert(e,e.node)}});return new n(r,this.indexSet_)}removeFromIndexes(e,t){let r=Ro(this.indexes_,s=>{if(s===Ui)return s;{let i=t.get(e.name);return i?s.remove(new ne(e.name,i)):s}});return new n(r,this.indexSet_)}};var qa,Y=(()=>{class n{static get EMPTY_NODE(){return qa||(qa=new n(new Ft(V_),null,Ki.Default))}constructor(t,r,s){this.children_=t,this.priorityNode_=r,this.indexMap_=s,this.lazyHash_=null,this.priorityNode_&&gb(this.priorityNode_),this.children_.isEmpty()&&V(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||qa}updatePriority(t){return this.children_.isEmpty()?this:new n(this.children_,t,this.indexMap_)}getImmediateChild(t){if(t===".priority")return this.getPriority();{let r=this.children_.get(t);return r===null?qa:r}}getChild(t){let r=Z(t);return r===null?this:this.getImmediateChild(r).getChild(ge(t))}hasChild(t){return this.children_.get(t)!==null}updateImmediateChild(t,r){if(V(r,"We should always be passing snapshot nodes"),t===".priority")return this.updatePriority(r);{let s=new ne(t,r),i,o;r.isEmpty()?(i=this.children_.remove(t),o=this.indexMap_.removeFromIndexes(s,this.children_)):(i=this.children_.insert(t,r),o=this.indexMap_.addToIndexes(s,this.children_));let a=i.isEmpty()?qa:this.priorityNode_;return new n(i,a,o)}}updateChild(t,r){let s=Z(t);if(s===null)return r;{V(Z(t)!==".priority"||Mr(t)===1,".priority must be the last token in a path");let i=this.getImmediateChild(s).updateChild(ge(t),r);return this.updateImmediateChild(s,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(t){if(this.isEmpty())return null;let r={},s=0,i=0,o=!0;if(this.forEachChild(ve,(a,l)=>{r[a]=l.val(t),s++,o&&n.INTEGER_REGEXP_.test(a)?i=Math.max(i,Number(a)):o=!1}),!t&&o&&i<2*s){let a=[];for(let l in r)a[l]=r[l];return a}else return t&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(this.lazyHash_===null){let t="";this.getPriority().isEmpty()||(t+="priority:"+mb(this.getPriority().val())+":"),this.forEachChild(ve,(r,s)=>{let i=s.hash();i!==""&&(t+=":"+r+":"+i)}),this.lazyHash_=t===""?"":$A(t)}return this.lazyHash_}getPredecessorChildName(t,r,s){let i=this.resolveIndex_(s);if(i){let o=i.getPredecessorKey(new ne(t,r));return o?o.name:null}else return this.children_.getPredecessorKey(t)}getFirstChildName(t){let r=this.resolveIndex_(t);if(r){let s=r.minKey();return s&&s.name}else return this.children_.minKey()}getFirstChild(t){let r=this.getFirstChildName(t);return r?new ne(r,this.children_.get(r)):null}getLastChildName(t){let r=this.resolveIndex_(t);if(r){let s=r.maxKey();return s&&s.name}else return this.children_.maxKey()}getLastChild(t){let r=this.getLastChildName(t);return r?new ne(r,this.children_.get(r)):null}forEachChild(t,r){let s=this.resolveIndex_(t);return s?s.inorderTraversal(i=>r(i.name,i.node)):this.children_.inorderTraversal(r)}getIterator(t){return this.getIteratorFrom(t.minPost(),t)}getIteratorFrom(t,r){let s=this.resolveIndex_(r);if(s)return s.getIteratorFrom(t,i=>i);{let i=this.children_.getIteratorFrom(t.name,ne.Wrap),o=i.peek();for(;o!=null&&r.compare(o,t)<0;)i.getNext(),o=i.peek();return i}}getReverseIterator(t){return this.getReverseIteratorFrom(t.maxPost(),t)}getReverseIteratorFrom(t,r){let s=this.resolveIndex_(r);if(s)return s.getReverseIteratorFrom(t,i=>i);{let i=this.children_.getReverseIteratorFrom(t.name,ne.Wrap),o=i.peek();for(;o!=null&&r.compare(o,t)>0;)i.getNext(),o=i.peek();return i}}compareTo(t){return this.isEmpty()?t.isEmpty()?0:-1:t.isLeafNode()||t.isEmpty()?1:t===uc?-1:0}withIndex(t){if(t===vn||this.indexMap_.hasIndex(t))return this;{let r=this.indexMap_.addIndex(t,this.children_);return new n(this.children_,this.priorityNode_,r)}}isIndexed(t){return t===vn||this.indexMap_.hasIndex(t)}equals(t){if(t===this)return!0;if(t.isLeafNode())return!1;{let r=t;if(this.getPriority().equals(r.getPriority()))if(this.children_.count()===r.children_.count()){let s=this.getIterator(ve),i=r.getIterator(ve),o=s.getNext(),a=i.getNext();for(;o&&a;){if(o.name!==a.name||!o.node.equals(a.node))return!1;o=s.getNext(),a=i.getNext()}return o===null&&a===null}else return!1;else return!1}}resolveIndex_(t){return t===vn?null:this.indexMap_.get(t.toString())}}return n.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,n})(),Bg=class extends Y{constructor(){super(new Ft(V_),Y.EMPTY_NODE,Ki.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return Y.EMPTY_NODE}isEmpty(){return!1}},uc=new Bg;Object.defineProperties(ne,{MIN:{value:new ne(Or,Y.EMPTY_NODE)},MAX:{value:new ne(Bn,uc)}});nh.__EMPTY_NODE=Y.EMPTY_NODE;zi.__childrenNodeConstructor=Y;lx(uc);hx(uc);var fx=!0;function be(n,e=null){if(n===null)return Y.EMPTY_NODE;if(typeof n=="object"&&".priority"in n&&(e=n[".priority"]),V(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof n=="object"&&".value"in n&&n[".value"]!==null&&(n=n[".value"]),typeof n!="object"||".sv"in n){let t=n;return new zi(t,be(e))}if(!(n instanceof Array)&&fx){let t=[],r=!1;if(Je(n,(o,a)=>{if(o.substring(0,1)!=="."){let l=be(a);l.isEmpty()||(r=r||!l.getPriority().isEmpty(),t.push(new ne(o,l)))}}),t.length===0)return Y.EMPTY_NODE;let i=rh(t,cx,o=>o.name,V_);if(r){let o=rh(t,ve.getCompare());return new Y(i,be(e),new Ki({".priority":o},{".priority":ve}))}else return new Y(i,be(e),Ki.Default)}else{let t=Y.EMPTY_NODE;return Je(n,(r,s)=>{if(Nt(n,r)&&r.substring(0,1)!=="."){let i=be(s);(i.isLeafNode()||!i.isEmpty())&&(t=t.updateImmediateChild(r,i))}}),t.updatePriority(be(e))}}ux(be);var Ya=class extends Gi{constructor(e){super(),this.indexPath_=e,V(!ee(e)&&Z(e)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){let r=this.extractChild(e.node),s=this.extractChild(t.node),i=r.compareTo(s);return i===0?Vs(e.name,t.name):i}makePost(e,t){let r=be(e),s=Y.EMPTY_NODE.updateChild(this.indexPath_,r);return new ne(t,s)}maxPost(){let e=Y.EMPTY_NODE.updateChild(this.indexPath_,uc);return new ne(Bn,e)}toString(){return Qa(this.indexPath_,0).join("/")}};var qg=class extends Gi{compare(e,t){let r=e.node.compareTo(t.node);return r===0?Vs(e.name,t.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return ne.MIN}maxPost(){return ne.MAX}makePost(e,t){let r=be(e);return new ne(t,r)}toString(){return".value"}},O_=new qg;function vb(n){return{type:"value",snapshotNode:n}}function Wi(n,e){return{type:"child_added",snapshotNode:e,childName:n}}function Ja(n,e){return{type:"child_removed",snapshotNode:e,childName:n}}function Xa(n,e,t){return{type:"child_changed",snapshotNode:e,childName:n,oldSnap:t}}function px(n,e){return{type:"child_moved",snapshotNode:e,childName:n}}var Za=class{constructor(e){this.index_=e}updateChild(e,t,r,s,i,o){V(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let a=e.getImmediateChild(t);return a.getChild(s).equals(r.getChild(s))&&a.isEmpty()===r.isEmpty()||(o!=null&&(r.isEmpty()?e.hasChild(t)?o.trackChildChange(Ja(t,a)):V(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Wi(t,r)):o.trackChildChange(Xa(t,r,a))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(t,r).withIndex(this.index_)}updateFullNode(e,t,r){return r!=null&&(e.isLeafNode()||e.forEachChild(ve,(s,i)=>{t.hasChild(s)||r.trackChildChange(Ja(s,i))}),t.isLeafNode()||t.forEachChild(ve,(s,i)=>{if(e.hasChild(s)){let o=e.getImmediateChild(s);o.equals(i)||r.trackChildChange(Xa(s,i,o))}else r.trackChildChange(Wi(s,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?Y.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}};var sh=class n{constructor(e){this.indexedFilter_=new Za(e.getIndex()),this.index_=e.getIndex(),this.startPost_=n.getStartPost_(e),this.endPost_=n.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&r}updateChild(e,t,r,s,i,o){return this.matches(new ne(t,r))||(r=Y.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,r,s,i,o)}updateFullNode(e,t,r){t.isLeafNode()&&(t=Y.EMPTY_NODE);let s=t.withIndex(this.index_);s=s.updatePriority(Y.EMPTY_NODE);let i=this;return t.forEachChild(ve,(o,a)=>{i.matches(new ne(o,a))||(s=s.updateImmediateChild(o,Y.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,s,r)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}else return e.getIndex().maxPost()}};var jg=class{constructor(e){this.withinDirectionalStart=t=>this.reverse_?this.withinEndPost(t):this.withinStartPost(t),this.withinDirectionalEnd=t=>this.reverse_?this.withinStartPost(t):this.withinEndPost(t),this.withinStartPost=t=>{let r=this.index_.compare(this.rangedFilter_.getStartPost(),t);return this.startIsInclusive_?r<=0:r<0},this.withinEndPost=t=>{let r=this.index_.compare(t,this.rangedFilter_.getEndPost());return this.endIsInclusive_?r<=0:r<0},this.rangedFilter_=new sh(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,r,s,i,o){return this.rangedFilter_.matches(new ne(t,r))||(r=Y.EMPTY_NODE),e.getImmediateChild(t).equals(r)?e:e.numChildren()p(v,m)}else o=this.index_.getCompare();let a=e;V(a.numChildren()===this.limit_,"");let l=new ne(t,r),u=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),d=this.rangedFilter_.matches(l);if(a.hasChild(t)){let p=a.getImmediateChild(t),m=s.getChildAfterChild(this.index_,u,this.reverse_);for(;m!=null&&(m.name===t||a.hasChild(m.name));)m=s.getChildAfterChild(this.index_,m,this.reverse_);let v=m==null?1:o(m,l);if(d&&!r.isEmpty()&&v>=0)return i?.trackChildChange(Xa(t,r,p)),a.updateImmediateChild(t,r);{i?.trackChildChange(Ja(t,p));let x=a.updateImmediateChild(t,Y.EMPTY_NODE);return m!=null&&this.rangedFilter_.matches(m)?(i?.trackChildChange(Wi(m.name,m.node)),x.updateImmediateChild(m.name,m.node)):x}}else return r.isEmpty()?e:d&&o(u,l)>=0?(i!=null&&(i.trackChildChange(Ja(u.name,u.node)),i.trackChildChange(Wi(t,r))),a.updateImmediateChild(t,r).updateImmediateChild(u.name,Y.EMPTY_NODE)):e}};var ec=class n{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=ve}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return V(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return V(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Or}hasEnd(){return this.endSet_}getIndexEndValue(){return V(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return V(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Bn}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return V(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===ve}copy(){let e=new n;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}};function mx(n){return n.loadsAllData()?new Za(n.getIndex()):n.hasLimit()?new jg(n):new sh(n)}function gx(n,e){let t=n.copy();return t.limitSet_=!0,t.limit_=e,t.viewFrom_="l",t}function _x(n,e){let t=n.copy();return t.limitSet_=!0,t.limit_=e,t.viewFrom_="r",t}function Gg(n,e,t){let r=n.copy();return r.startSet_=!0,e===void 0&&(e=null),r.indexStartValue_=e,t!=null?(r.startNameSet_=!0,r.indexStartName_=t):(r.startNameSet_=!1,r.indexStartName_=""),r}function yx(n,e,t){let r;return n.index_===vn||t?r=Gg(n,e,t):r=Gg(n,e,Bn),r.startAfterSet_=!0,r}function zg(n,e,t){let r=n.copy();return r.endSet_=!0,e===void 0&&(e=null),r.indexEndValue_=e,t!==void 0?(r.endNameSet_=!0,r.indexEndName_=t):(r.endNameSet_=!1,r.indexEndName_=""),r}function vx(n,e,t){let r;return n.index_===vn||t?r=zg(n,e,t):r=zg(n,e,Or),r.endBeforeSet_=!0,r}function Ih(n,e){let t=n.copy();return t.index_=e,t}function PA(n){let e={};if(n.isDefault())return e;let t;if(n.index_===ve?t="$priority":n.index_===O_?t="$value":n.index_===vn?t="$key":(V(n.index_ instanceof Ya,"Unrecognized index type!"),t=n.index_.toString()),e.orderBy=Oe(t),n.startSet_){let r=n.startAfterSet_?"startAfter":"startAt";e[r]=Oe(n.indexStartValue_),n.startNameSet_&&(e[r]+=","+Oe(n.indexStartName_))}if(n.endSet_){let r=n.endBeforeSet_?"endBefore":"endAt";e[r]=Oe(n.indexEndValue_),n.endNameSet_&&(e[r]+=","+Oe(n.indexEndName_))}return n.limitSet_&&(n.isViewFromLeft()?e.limitToFirst=n.limit_:e.limitToLast=n.limit_),e}function xA(n){let e={};if(n.startSet_&&(e.sp=n.indexStartValue_,n.startNameSet_&&(e.sn=n.indexStartName_),e.sin=!n.startAfterSet_),n.endSet_&&(e.ep=n.indexEndValue_,n.endNameSet_&&(e.en=n.indexEndName_),e.ein=!n.endBeforeSet_),n.limitSet_){e.l=n.limit_;let t=n.viewFrom_;t===""&&(n.isViewFromLeft()?t="l":t="r"),e.vf=t}return n.index_!==ve&&(e.i=n.index_.toString()),e}var Kg=class n extends Zu{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return t!==void 0?"tag$"+t:(V(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,r,s){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=r,this.appCheckTokenProvider_=s,this.log_=lc("p:rest:"),this.listens_={}}listen(e,t,r,s){let i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);let o=n.getListenId_(e,r),a={};this.listens_[o]=a;let l=PA(e._queryParams);this.restRequest_(i+".json",l,(u,d)=>{let p=d;if(u===404&&(p=null,u=null),u===null&&this.onDataUpdate_(i,p,!1,r),Xn(this.listens_,o)===a){let m;u?u===401?m="permission_denied":m="rest_error:"+u:m="ok",s(m,null)}})}unlisten(e,t){let r=n.getListenId_(e,t);delete this.listens_[r]}get(e){let t=PA(e._queryParams),r=e._path.toString(),s=new Qe;return this.restRequest_(r+".json",t,(i,o)=>{let a=o;i===404&&(a=null,i=null),i===null?(this.onDataUpdate_(r,a,!1,null),s.resolve(a)):s.reject(new Error(a))}),s.promise}refreshAuthToken(e){}restRequest_(e,t={},r){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([s,i])=>{s&&s.accessToken&&(t.auth=s.accessToken),i&&i.token&&(t.ac=i.token);let o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+Kv(t);this.log_("Sending REST request for "+o);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(r&&a.readyState===4){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let l=null;if(a.status>=200&&a.status<300){try{l=zc(a.responseText)}catch{st("Failed to parse JSON response for "+o+": "+a.responseText)}r(null,l)}else a.status!==401&&a.status!==404&&st("Got unsuccessful REST response for "+o+" Status: "+a.status),r(a.status);r=null}},a.open("GET",o,!0),a.send()})}};var Wg=class{constructor(){this.rootNode_=Y.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}};function ih(){return{value:null,children:new Map}}function Xi(n,e,t){if(ee(e))n.value=t,n.children.clear();else if(n.value!==null)n.value=n.value.updateChild(e,t);else{let r=Z(e);n.children.has(r)||n.children.set(r,ih());let s=n.children.get(r);e=ge(e),Xi(s,e,t)}}function $g(n,e){if(ee(e))return n.value=null,n.children.clear(),!0;if(n.value!==null){if(n.value.isLeafNode())return!1;{let t=n.value;return n.value=null,t.forEachChild(ve,(r,s)=>{Xi(n,new ue(r),s)}),$g(n,e)}}else if(n.children.size>0){let t=Z(e);return e=ge(e),n.children.has(t)&&$g(n.children.get(t),e)&&n.children.delete(t),n.children.size===0}else return!0}function Hg(n,e,t){n.value!==null?t(e,n.value):wx(n,(r,s)=>{let i=new ue(e.toString()+"/"+r);Hg(s,i,t)})}function wx(n,e){n.children.forEach((t,r)=>{e(r,t)})}var Qg=class{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t=Q({},e);return this.last_&&Je(this.last_,(r,s)=>{t[r]=t[r]-s}),this.last_=e,t}};var kA=10*1e3,Ex=30*1e3,Tx=300*1e3,Yg=class{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Qg(e);let r=kA+(Ex-kA)*Math.random();Ga(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){let e=this.statsListener_.get(),t={},r=!1;Je(e,(s,i)=>{i>0&&Nt(this.statsToReport_,s)&&(t[s]=i,r=!0)}),r&&this.server_.reportStats(t),Ga(this.reportStats_.bind(this),Math.floor(Math.random()*2*Tx))}};var yn=(function(n){return n[n.OVERWRITE=0]="OVERWRITE",n[n.MERGE=1]="MERGE",n[n.ACK_USER_WRITE=2]="ACK_USER_WRITE",n[n.LISTEN_COMPLETE=3]="LISTEN_COMPLETE",n})(yn||{});function M_(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function F_(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function L_(n){return{fromUser:!1,fromServer:!0,queryId:n,tagged:!0}}var Jg=class n{constructor(e,t,r){this.path=e,this.affectedTree=t,this.revert=r,this.type=yn.ACK_USER_WRITE,this.source=M_()}operationForChild(e){if(ee(this.path)){if(this.affectedTree.value!=null)return V(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let t=this.affectedTree.subtree(new ue(e));return new n(le(),t,this.revert)}}else return V(Z(this.path)===e,"operationForChild called for unrelated child."),new n(ge(this.path),this.affectedTree,this.revert)}};var oh=class n{constructor(e,t){this.source=e,this.path=t,this.type=yn.LISTEN_COMPLETE}operationForChild(e){return ee(this.path)?new n(this.source,le()):new n(this.source,ge(this.path))}};var $i=class n{constructor(e,t,r){this.source=e,this.path=t,this.snap=r,this.type=yn.OVERWRITE}operationForChild(e){return ee(this.path)?new n(this.source,le(),this.snap.getImmediateChild(e)):new n(this.source,ge(this.path),this.snap)}};var tc=class n{constructor(e,t,r){this.source=e,this.path=t,this.children=r,this.type=yn.MERGE}operationForChild(e){if(ee(this.path)){let t=this.children.subtree(new ue(e));return t.isEmpty()?null:t.value?new $i(this.source,le(),t.value):new n(this.source,le(),t)}else return V(Z(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new n(this.source,ge(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}};var En=class{constructor(e,t,r){this.node_=e,this.fullyInitialized_=t,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(ee(e))return this.isFullyInitialized()&&!this.filtered_;let t=Z(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}};var Xg=class{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}};function Ix(n,e,t,r){let s=[],i=[];return e.forEach(o=>{o.type==="child_changed"&&n.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&i.push(px(o.childName,o.snapshotNode))}),ja(n,s,"child_removed",e,r,t),ja(n,s,"child_added",e,r,t),ja(n,s,"child_moved",i,r,t),ja(n,s,"child_changed",e,r,t),ja(n,s,"value",e,r,t),s}function ja(n,e,t,r,s,i){let o=r.filter(a=>a.type===t);o.sort((a,l)=>bx(n,a,l)),o.forEach(a=>{let l=Ax(n,a,i);s.forEach(u=>{u.respondsTo(a.type)&&e.push(u.createEvent(l,n.query_))})})}function Ax(n,e,t){return e.type==="value"||e.type==="child_removed"||(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,n.index_)),e}function bx(n,e,t){if(e.childName==null||t.childName==null)throw Ks("Should only compare child_ events.");let r=new ne(e.childName,e.snapshotNode),s=new ne(t.childName,t.snapshotNode);return n.index_.compare(r,s)}function Ah(n,e){return{eventCache:n,serverCache:e}}function Ka(n,e,t,r){return Ah(new En(e,t,r),n.serverCache)}function wb(n,e,t,r){return Ah(n.eventCache,new En(e,t,r))}function ah(n){return n.eventCache.isFullyInitialized()?n.eventCache.getNode():null}function Ds(n){return n.serverCache.isFullyInitialized()?n.serverCache.getNode():null}var wg,Cx=()=>(wg||(wg=new Ft(AP)),wg),ft=class n{static fromObject(e){let t=new n(null);return Je(e,(r,s)=>{t=t.set(new ue(r),s)}),t}constructor(e,t=Cx()){this.value=e,this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value))return{path:le(),value:this.value};if(ee(e))return null;{let r=Z(e),s=this.children.get(r);if(s!==null){let i=s.findRootMostMatchingPathAndValue(ge(e),t);return i!=null?{path:Ie(new ue(r),i.path),value:i.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(ee(e))return this;{let t=Z(e),r=this.children.get(t);return r!==null?r.subtree(ge(e)):new n(null)}}set(e,t){if(ee(e))return new n(t,this.children);{let r=Z(e),i=(this.children.get(r)||new n(null)).set(ge(e),t),o=this.children.insert(r,i);return new n(this.value,o)}}remove(e){if(ee(e))return this.children.isEmpty()?new n(null):new n(null,this.children);{let t=Z(e),r=this.children.get(t);if(r){let s=r.remove(ge(e)),i;return s.isEmpty()?i=this.children.remove(t):i=this.children.insert(t,s),this.value===null&&i.isEmpty()?new n(null):new n(this.value,i)}else return this}}get(e){if(ee(e))return this.value;{let t=Z(e),r=this.children.get(t);return r?r.get(ge(e)):null}}setTree(e,t){if(ee(e))return t;{let r=Z(e),i=(this.children.get(r)||new n(null)).setTree(ge(e),t),o;return i.isEmpty()?o=this.children.remove(r):o=this.children.insert(r,i),new n(this.value,o)}}fold(e){return this.fold_(le(),e)}fold_(e,t){let r={};return this.children.inorderTraversal((s,i)=>{r[s]=i.fold_(Ie(e,s),t)}),t(e,this.value,r)}findOnPath(e,t){return this.findOnPath_(e,le(),t)}findOnPath_(e,t,r){let s=this.value?r(t,this.value):!1;if(s)return s;if(ee(e))return null;{let i=Z(e),o=this.children.get(i);return o?o.findOnPath_(ge(e),Ie(t,i),r):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,le(),t)}foreachOnPath_(e,t,r){if(ee(e))return this;{this.value&&r(t,this.value);let s=Z(e),i=this.children.get(s);return i?i.foreachOnPath_(ge(e),Ie(t,s),r):new n(null)}}foreach(e){this.foreach_(le(),e)}foreach_(e,t){this.children.inorderTraversal((r,s)=>{s.foreach_(Ie(e,r),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,r)=>{r.value&&e(t,r.value)})}};var Yt=class n{constructor(e){this.writeTree_=e}static empty(){return new n(new ft(null))}};function Wa(n,e,t){if(ee(e))return new Yt(new ft(t));{let r=n.writeTree_.findRootMostValueAndPath(e);if(r!=null){let s=r.path,i=r.value,o=dt(s,e);return i=i.updateChild(o,t),new Yt(n.writeTree_.set(s,i))}else{let s=new ft(t),i=n.writeTree_.setTree(e,s);return new Yt(i)}}}function Zg(n,e,t){let r=n;return Je(t,(s,i)=>{r=Wa(r,Ie(e,s),i)}),r}function NA(n,e){if(ee(e))return Yt.empty();{let t=n.writeTree_.setTree(e,new ft(null));return new Yt(t)}}function e_(n,e){return Os(n,e)!=null}function Os(n,e){let t=n.writeTree_.findRootMostValueAndPath(e);return t!=null?n.writeTree_.get(t.path).getChild(dt(t.path,e)):null}function DA(n){let e=[],t=n.writeTree_.value;return t!=null?t.isLeafNode()||t.forEachChild(ve,(r,s)=>{e.push(new ne(r,s))}):n.writeTree_.children.inorderTraversal((r,s)=>{s.value!=null&&e.push(new ne(r,s.value))}),e}function Dr(n,e){if(ee(e))return n;{let t=Os(n,e);return t!=null?new Yt(new ft(t)):new Yt(n.writeTree_.subtree(e))}}function t_(n){return n.writeTree_.isEmpty()}function Hi(n,e){return Eb(le(),n.writeTree_,e)}function Eb(n,e,t){if(e.value!=null)return t.updateChild(n,e.value);{let r=null;return e.children.inorderTraversal((s,i)=>{s===".priority"?(V(i.value!==null,"Priority writes must always be leaf nodes"),r=i.value):t=Eb(Ie(n,s),i,t)}),!t.getChild(n).isEmpty()&&r!==null&&(t=t.updateChild(Ie(n,".priority"),r)),t}}function bh(n,e){return bb(e,n)}function Sx(n,e,t,r,s){V(r>n.lastWriteId,"Stacking an older write on top of newer ones"),s===void 0&&(s=!0),n.allWrites.push({path:e,snap:t,writeId:r,visible:s}),s&&(n.visibleWrites=Wa(n.visibleWrites,e,t)),n.lastWriteId=r}function Rx(n,e,t,r){V(r>n.lastWriteId,"Stacking an older merge on top of newer ones"),n.allWrites.push({path:e,children:t,writeId:r,visible:!0}),n.visibleWrites=Zg(n.visibleWrites,e,t),n.lastWriteId=r}function Px(n,e){for(let t=0;ta.writeId===e);V(t>=0,"removeWrite called with nonexistent writeId.");let r=n.allWrites[t];n.allWrites.splice(t,1);let s=r.visible,i=!1,o=n.allWrites.length-1;for(;s&&o>=0;){let a=n.allWrites[o];a.visible&&(o>=t&&kx(a,r.path)?s=!1:Mt(r.path,a.path)&&(i=!0)),o--}if(s){if(i)return Nx(n),!0;if(r.snap)n.visibleWrites=NA(n.visibleWrites,r.path);else{let a=r.children;Je(a,l=>{n.visibleWrites=NA(n.visibleWrites,Ie(r.path,l))})}return!0}else return!1}function kx(n,e){if(n.snap)return Mt(n.path,e);for(let t in n.children)if(n.children.hasOwnProperty(t)&&Mt(Ie(n.path,t),e))return!0;return!1}function Nx(n){n.visibleWrites=Tb(n.allWrites,Dx,le()),n.allWrites.length>0?n.lastWriteId=n.allWrites[n.allWrites.length-1].writeId:n.lastWriteId=-1}function Dx(n){return n.visible}function Tb(n,e,t){let r=Yt.empty();for(let s=0;s{r=r.updateImmediateChild(i,o)}),r;if(t){let i=Dr(n.visibleWrites,e);return t.forEachChild(ve,(o,a)=>{let l=Hi(Dr(i,new ue(o)),a);r=r.updateImmediateChild(o,l)}),DA(i).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}else{let i=Dr(n.visibleWrites,e);return DA(i).forEach(o=>{r=r.updateImmediateChild(o.name,o.node)}),r}}function Ox(n,e,t,r,s){V(r||s,"Either existingEventSnap or existingServerSnap must exist");let i=Ie(e,t);if(e_(n.visibleWrites,i))return null;{let o=Dr(n.visibleWrites,i);return t_(o)?s.getChild(t):Hi(o,s.getChild(t))}}function Mx(n,e,t,r){let s=Ie(e,t),i=Os(n.visibleWrites,s);if(i!=null)return i;if(r.isCompleteForChild(t)){let o=Dr(n.visibleWrites,s);return Hi(o,r.getNode().getImmediateChild(t))}else return null}function Fx(n,e){return Os(n.visibleWrites,e)}function Lx(n,e,t,r,s,i,o){let a,l=Dr(n.visibleWrites,e),u=Os(l,le());if(u!=null)a=u;else if(t!=null)a=Hi(l,t);else return[];if(a=a.withIndex(o),!a.isEmpty()&&!a.isLeafNode()){let d=[],p=o.getCompare(),m=i?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o),v=m.getNext();for(;v&&d.length0||!n.eventCache.isFullyInitialized()||s&&!r.getNode().equals(i)||!r.getNode().getPriority().equals(i.getPriority()))&&t.push(vb(ah(e)))}}function Sb(n,e,t,r,s,i){let o=e.eventCache;if(lh(r,t)!=null)return e;{let a,l;if(ee(t))if(V(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){let u=Ds(e),d=u instanceof Y?u:Y.EMPTY_NODE,p=U_(r,d);a=n.filter.updateFullNode(e.eventCache.getNode(),p,i)}else{let u=ch(r,Ds(e));a=n.filter.updateFullNode(e.eventCache.getNode(),u,i)}else{let u=Z(t);if(u===".priority"){V(Mr(t)===1,"Can't have a priority with additional path components");let d=o.getNode();l=e.serverCache.getNode();let p=VA(r,t,d,l);p!=null?a=n.filter.updatePriority(d,p):a=o.getNode()}else{let d=ge(t),p;if(o.isCompleteForChild(u)){l=e.serverCache.getNode();let m=VA(r,t,o.getNode(),l);m!=null?p=o.getNode().getImmediateChild(u).updateChild(d,m):p=o.getNode().getImmediateChild(u)}else p=B_(r,u,e.serverCache);p!=null?a=n.filter.updateChild(o.getNode(),u,p,d,s,i):a=o.getNode()}}return Ka(e,a,o.isFullyInitialized()||ee(t),n.filter.filtersNodes())}}function uh(n,e,t,r,s,i,o,a){let l=e.serverCache,u,d=o?n.filter:n.filter.getIndexedFilter();if(ee(t))u=d.updateFullNode(l.getNode(),r,null);else if(d.filtersNodes()&&!l.isFiltered()){let v=l.getNode().updateChild(t,r);u=d.updateFullNode(l.getNode(),v,null)}else{let v=Z(t);if(!l.isCompleteForPath(t)&&Mr(t)>1)return e;let S=ge(t),k=l.getNode().getImmediateChild(v).updateChild(S,r);v===".priority"?u=d.updatePriority(l.getNode(),k):u=d.updateChild(l.getNode(),v,k,S,Cb,null)}let p=wb(e,u,l.isFullyInitialized()||ee(t),d.filtersNodes()),m=new nc(s,p,i);return Sb(n,p,t,s,m,a)}function s_(n,e,t,r,s,i,o){let a=e.eventCache,l,u,d=new nc(s,e,i);if(ee(t))u=n.filter.updateFullNode(e.eventCache.getNode(),r,o),l=Ka(e,u,!0,n.filter.filtersNodes());else{let p=Z(t);if(p===".priority")u=n.filter.updatePriority(e.eventCache.getNode(),r),l=Ka(e,u,a.isFullyInitialized(),a.isFiltered());else{let m=ge(t),v=a.getNode().getImmediateChild(p),S;if(ee(m))S=r;else{let x=d.getCompleteChild(p);x!=null?k_(m)===".priority"&&x.getChild(fb(m)).isEmpty()?S=x:S=x.updateChild(m,r):S=Y.EMPTY_NODE}if(v.equals(S))l=e;else{let x=n.filter.updateChild(a.getNode(),p,S,m,d,o);l=Ka(e,x,a.isFullyInitialized(),n.filter.filtersNodes())}}}return l}function OA(n,e){return n.eventCache.isCompleteForChild(e)}function Kx(n,e,t,r,s,i,o){let a=e;return r.foreach((l,u)=>{let d=Ie(t,l);OA(e,Z(d))&&(a=s_(n,a,d,u,s,i,o))}),r.foreach((l,u)=>{let d=Ie(t,l);OA(e,Z(d))||(a=s_(n,a,d,u,s,i,o))}),a}function MA(n,e,t){return t.foreach((r,s)=>{e=e.updateChild(r,s)}),e}function i_(n,e,t,r,s,i,o,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let l=e,u;ee(t)?u=r:u=new ft(null).setTree(t,r);let d=e.serverCache.getNode();return u.children.inorderTraversal((p,m)=>{if(d.hasChild(p)){let v=e.serverCache.getNode().getImmediateChild(p),S=MA(n,v,m);l=uh(n,l,new ue(p),S,s,i,o,a)}}),u.children.inorderTraversal((p,m)=>{let v=!e.serverCache.isCompleteForChild(p)&&m.value===null;if(!d.hasChild(p)&&!v){let S=e.serverCache.getNode().getImmediateChild(p),x=MA(n,S,m);l=uh(n,l,new ue(p),x,s,i,o,a)}}),l}function Wx(n,e,t,r,s,i,o){if(lh(s,t)!=null)return e;let a=e.serverCache.isFiltered(),l=e.serverCache;if(r.value!=null){if(ee(t)&&l.isFullyInitialized()||l.isCompleteForPath(t))return uh(n,e,t,l.getNode().getChild(t),s,i,a,o);if(ee(t)){let u=new ft(null);return l.getNode().forEachChild(vn,(d,p)=>{u=u.set(new ue(d),p)}),i_(n,e,t,u,s,i,a,o)}else return e}else{let u=new ft(null);return r.foreach((d,p)=>{let m=Ie(t,d);l.isCompleteForPath(m)&&(u=u.set(d,l.getNode().getChild(m)))}),i_(n,e,t,u,s,i,a,o)}}function $x(n,e,t,r,s){let i=e.serverCache,o=wb(e,i.getNode(),i.isFullyInitialized()||ee(t),i.isFiltered());return Sb(n,o,t,r,Cb,s)}function Hx(n,e,t,r,s,i){let o;if(lh(r,t)!=null)return e;{let a=new nc(r,e,s),l=e.eventCache.getNode(),u;if(ee(t)||Z(t)===".priority"){let d;if(e.serverCache.isFullyInitialized())d=ch(r,Ds(e));else{let p=e.serverCache.getNode();V(p instanceof Y,"serverChildren would be complete if leaf node"),d=U_(r,p)}d=d,u=n.filter.updateFullNode(l,d,i)}else{let d=Z(t),p=B_(r,d,e.serverCache);p==null&&e.serverCache.isCompleteForChild(d)&&(p=l.getImmediateChild(d)),p!=null?u=n.filter.updateChild(l,d,p,ge(t),a,i):e.eventCache.getNode().hasChild(d)?u=n.filter.updateChild(l,d,Y.EMPTY_NODE,ge(t),a,i):u=l,u.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=ch(r,Ds(e)),o.isLeafNode()&&(u=n.filter.updateFullNode(u,o,i)))}return o=e.serverCache.isFullyInitialized()||lh(r,le())!=null,Ka(e,u,o,n.filter.filtersNodes())}}var o_=class{constructor(e,t){this.query_=e,this.eventRegistrations_=[];let r=this.query_._queryParams,s=new Za(r.getIndex()),i=mx(r);this.processor_=qx(i);let o=t.serverCache,a=t.eventCache,l=s.updateFullNode(Y.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(Y.EMPTY_NODE,a.getNode(),null),d=new En(l,o.isFullyInitialized(),s.filtersNodes()),p=new En(u,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Ah(p,d),this.eventGenerator_=new Xg(this.query_)}get query(){return this.query_}};function Qx(n){return n.viewCache_.serverCache.getNode()}function Yx(n){return ah(n.viewCache_)}function Jx(n,e){let t=Ds(n.viewCache_);return t&&(n.query._queryParams.loadsAllData()||!ee(e)&&!t.getImmediateChild(Z(e)).isEmpty())?t.getChild(e):null}function FA(n){return n.eventRegistrations_.length===0}function Xx(n,e){n.eventRegistrations_.push(e)}function LA(n,e,t){let r=[];if(t){V(e==null,"A cancel should cancel all event registrations.");let s=n.query._path;n.eventRegistrations_.forEach(i=>{let o=i.createCancelEvent(t,s);o&&r.push(o)})}if(e){let s=[];for(let i=0;i{r.push(Wi(i,o))}),t.isFullyInitialized()&&r.push(vb(t.getNode())),Rb(n,r,t.getNode(),e)}function Rb(n,e,t,r){let s=r?[r]:n.eventRegistrations_;return Ix(n.eventGenerator_,e,t,s)}var hh,dh=class{constructor(){this.views=new Map}};function ek(n){V(!hh,"__referenceConstructor has already been defined"),hh=n}function tk(){return V(hh,"Reference.ts has not been loaded"),hh}function nk(n){return n.views.size===0}function q_(n,e,t,r){let s=e.source.queryId;if(s!==null){let i=n.views.get(s);return V(i!=null,"SyncTree gave us an op for an invalid query."),UA(i,e,t,r)}else{let i=[];for(let o of n.views.values())i=i.concat(UA(o,e,t,r));return i}}function Pb(n,e,t,r,s){let i=e._queryIdentifier,o=n.views.get(i);if(!o){let a=ch(t,s?r:null),l=!1;a?l=!0:r instanceof Y?(a=U_(t,r),l=!1):(a=Y.EMPTY_NODE,l=!1);let u=Ah(new En(a,l,!1),new En(r,s,!1));return new o_(e,u)}return o}function rk(n,e,t,r,s,i){let o=Pb(n,e,r,s,i);return n.views.has(e._queryIdentifier)||n.views.set(e._queryIdentifier,o),Xx(o,t),Zx(o,t)}function sk(n,e,t,r){let s=e._queryIdentifier,i=[],o=[],a=Fr(n);if(s==="default")for(let[l,u]of n.views.entries())o=o.concat(LA(u,t,r)),FA(u)&&(n.views.delete(l),u.query._queryParams.loadsAllData()||i.push(u.query));else{let l=n.views.get(s);l&&(o=o.concat(LA(l,t,r)),FA(l)&&(n.views.delete(s),l.query._queryParams.loadsAllData()||i.push(l.query)))}return a&&!Fr(n)&&i.push(new(tk())(e._repo,e._path)),{removed:i,events:o}}function xb(n){let e=[];for(let t of n.views.values())t.query._queryParams.loadsAllData()||e.push(t);return e}function Vr(n,e){let t=null;for(let r of n.views.values())t=t||Jx(r,e);return t}function kb(n,e){if(e._queryParams.loadsAllData())return Ch(n);{let r=e._queryIdentifier;return n.views.get(r)}}function Nb(n,e){return kb(n,e)!=null}function Fr(n){return Ch(n)!=null}function Ch(n){for(let e of n.views.values())if(e.query._queryParams.loadsAllData())return e;return null}var fh;function ik(n){V(!fh,"__referenceConstructor has already been defined"),fh=n}function ok(){return V(fh,"Reference.ts has not been loaded"),fh}var ak=1,ph=class{constructor(e){this.listenProvider_=e,this.syncPointTree_=new ft(null),this.pendingWriteTree_=Ux(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}};function j_(n,e,t,r,s){return Sx(n.pendingWriteTree_,e,t,r,s),s?Zi(n,new $i(M_(),e,t)):[]}function ck(n,e,t,r){Rx(n.pendingWriteTree_,e,t,r);let s=ft.fromObject(t);return Zi(n,new tc(M_(),e,s))}function Nr(n,e,t=!1){let r=Px(n.pendingWriteTree_,e);if(xx(n.pendingWriteTree_,e)){let i=new ft(null);return r.snap!=null?i=i.set(le(),!0):Je(r.children,o=>{i=i.set(new ue(o),!0)}),Zi(n,new Jg(r.path,i,t))}else return[]}function hc(n,e,t){return Zi(n,new $i(F_(),e,t))}function lk(n,e,t){let r=ft.fromObject(t);return Zi(n,new tc(F_(),e,r))}function uk(n,e){return Zi(n,new oh(F_(),e))}function hk(n,e,t){let r=G_(n,t);if(r){let s=z_(r),i=s.path,o=s.queryId,a=dt(i,e),l=new oh(L_(o),a);return K_(n,i,l)}else return[]}function mh(n,e,t,r,s=!1){let i=e._path,o=n.syncPointTree_.get(i),a=[];if(o&&(e._queryIdentifier==="default"||Nb(o,e))){let l=sk(o,e,t,r);nk(o)&&(n.syncPointTree_=n.syncPointTree_.remove(i));let u=l.removed;if(a=l.events,!s){let d=u.findIndex(m=>m._queryParams.loadsAllData())!==-1,p=n.syncPointTree_.findOnPath(i,(m,v)=>Fr(v));if(d&&!p){let m=n.syncPointTree_.subtree(i);if(!m.isEmpty()){let v=pk(m);for(let S=0;S0&&!r&&(d?n.listenProvider_.stopListening($a(e),null):u.forEach(m=>{let v=n.queryToTagMap.get(Rh(m));n.listenProvider_.stopListening($a(m),v)}))}mk(n,u)}return a}function Db(n,e,t,r){let s=G_(n,r);if(s!=null){let i=z_(s),o=i.path,a=i.queryId,l=dt(o,e),u=new $i(L_(a),l,t);return K_(n,o,u)}else return[]}function dk(n,e,t,r){let s=G_(n,r);if(s){let i=z_(s),o=i.path,a=i.queryId,l=dt(o,e),u=ft.fromObject(t),d=new tc(L_(a),l,u);return K_(n,o,d)}else return[]}function a_(n,e,t,r=!1){let s=e._path,i=null,o=!1;n.syncPointTree_.foreachOnPath(s,(m,v)=>{let S=dt(m,s);i=i||Vr(v,S),o=o||Fr(v)});let a=n.syncPointTree_.get(s);a?(o=o||Fr(a),i=i||Vr(a,le())):(a=new dh,n.syncPointTree_=n.syncPointTree_.set(s,a));let l;i!=null?l=!0:(l=!1,i=Y.EMPTY_NODE,n.syncPointTree_.subtree(s).foreachChild((v,S)=>{let x=Vr(S,le());x&&(i=i.updateImmediateChild(v,x))}));let u=Nb(a,e);if(!u&&!e._queryParams.loadsAllData()){let m=Rh(e);V(!n.queryToTagMap.has(m),"View does not exist, but we have a tag");let v=gk();n.queryToTagMap.set(m,v),n.tagToQueryMap.set(v,m)}let d=bh(n.pendingWriteTree_,s),p=rk(a,e,t,d,i,l);if(!u&&!o&&!r){let m=kb(a,e);p=p.concat(_k(n,e,m))}return p}function Sh(n,e,t){let s=n.pendingWriteTree_,i=n.syncPointTree_.findOnPath(e,(o,a)=>{let l=dt(o,e),u=Vr(a,l);if(u)return u});return Ib(s,e,i,t,!0)}function fk(n,e){let t=e._path,r=null;n.syncPointTree_.foreachOnPath(t,(u,d)=>{let p=dt(u,t);r=r||Vr(d,p)});let s=n.syncPointTree_.get(t);s?r=r||Vr(s,le()):(s=new dh,n.syncPointTree_=n.syncPointTree_.set(t,s));let i=r!=null,o=i?new En(r,!0,!1):null,a=bh(n.pendingWriteTree_,e._path),l=Pb(s,e,a,i?o.getNode():Y.EMPTY_NODE,i);return Yx(l)}function Zi(n,e){return Vb(e,n.syncPointTree_,null,bh(n.pendingWriteTree_,le()))}function Vb(n,e,t,r){if(ee(n.path))return Ob(n,e,t,r);{let s=e.get(le());t==null&&s!=null&&(t=Vr(s,le()));let i=[],o=Z(n.path),a=n.operationForChild(o),l=e.children.get(o);if(l&&a){let u=t?t.getImmediateChild(o):null,d=Ab(r,o);i=i.concat(Vb(a,l,u,d))}return s&&(i=i.concat(q_(s,n,r,t))),i}}function Ob(n,e,t,r){let s=e.get(le());t==null&&s!=null&&(t=Vr(s,le()));let i=[];return e.children.inorderTraversal((o,a)=>{let l=t?t.getImmediateChild(o):null,u=Ab(r,o),d=n.operationForChild(o);d&&(i=i.concat(Ob(d,a,l,u)))}),s&&(i=i.concat(q_(s,n,r,t))),i}function Mb(n,e){let t=e.query,r=rc(n,t);return{hashFn:()=>(Qx(e)||Y.EMPTY_NODE).hash(),onComplete:s=>{if(s==="ok")return r?hk(n,t._path,r):uk(n,t._path);{let i=SP(s,t);return mh(n,t,null,i)}}}}function rc(n,e){let t=Rh(e);return n.queryToTagMap.get(t)}function Rh(n){return n._path.toString()+"$"+n._queryIdentifier}function G_(n,e){return n.tagToQueryMap.get(e)}function z_(n){let e=n.indexOf("$");return V(e!==-1&&e{if(t&&Fr(t))return[Ch(t)];{let s=[];return t&&(s=xb(t)),Je(r,(i,o)=>{s=s.concat(o)}),s}})}function $a(n){return n._queryParams.loadsAllData()&&!n._queryParams.isDefault()?new(ok())(n._repo,n._path):n}function mk(n,e){for(let t=0;t{if(!ee(u)&&d&&Fr(d))return[Ch(d).query];{let m=[];return d&&(m=m.concat(xb(d).map(v=>v.query))),Je(p,(v,S)=>{m=m.concat(S)}),m}});for(let u=0;u{let u=$_(l,e.getImmediateChild(a),t);u!==l&&(i=i.updateImmediateChild(a,u))}),i}}var sc=class{constructor(e="",t=null,r={children:{},childCount:0}){this.name=e,this.parent=t,this.node=r}};function Ph(n,e){let t=e instanceof ue?e:new ue(e),r=n,s=Z(t);for(;s!==null;){let i=Xn(r.node.children,s)||{children:{},childCount:0};r=new sc(s,r,i),t=ge(t),s=Z(t)}return r}function Ms(n){return n.node.value}function H_(n,e){n.node.value=e,u_(n)}function Lb(n){return n.node.childCount>0}function Ek(n){return Ms(n)===void 0&&!Lb(n)}function xh(n,e){Je(n.node.children,(t,r)=>{e(new sc(t,n,r))})}function Ub(n,e,t,r){t&&!r&&e(n),xh(n,s=>{Ub(s,e,!0,r)}),t&&r&&e(n)}function Tk(n,e,t){let r=t?n:n.parent;for(;r!==null;){if(e(r))return!0;r=r.parent}return!1}function dc(n){return new ue(n.parent===null?n.name:dc(n.parent)+"/"+n.name)}function u_(n){n.parent!==null&&Ik(n.parent,n.name,n)}function Ik(n,e,t){let r=Ek(t),s=Nt(n.node.children,e);r&&s?(delete n.node.children[e],n.node.childCount--,u_(n)):!r&&!s&&(n.node.children[e]=t.node,n.node.childCount++,u_(n))}var Ak=/[\[\].#$\/\u0000-\u001F\u007F]/,bk=/[\[\].#$\u0000-\u001F\u007F]/,Eg=10*1024*1024,kh=function(n){return typeof n=="string"&&n.length!==0&&!Ak.test(n)},Bb=function(n){return typeof n=="string"&&n.length!==0&&!bk.test(n)},Ck=function(n){return n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Bb(n)},ic=function(n){return n===null||typeof n=="string"||typeof n=="number"&&!Th(n)||n&&typeof n=="object"&&Nt(n,".sv")},Tn=function(n,e,t,r){r&&e===void 0||fc(gt(n,"value"),e,t)},fc=function(n,e,t){let r=t instanceof ue?new Vg(t,n):t;if(e===void 0)throw new Error(n+"contains undefined "+xs(r));if(typeof e=="function")throw new Error(n+"contains a function "+xs(r)+" with contents = "+e.toString());if(Th(e))throw new Error(n+"contains "+e.toString()+" "+xs(r));if(typeof e=="string"&&e.length>Eg/3&&Po(e)>Eg)throw new Error(n+"contains a string greater than "+Eg+" utf8 bytes "+xs(r)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let s=!1,i=!1;if(Je(e,(o,a)=>{if(o===".value")s=!0;else if(o!==".priority"&&o!==".sv"&&(i=!0,!kh(o)))throw new Error(n+" contains an invalid key ("+o+") "+xs(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);nx(r,o),fc(n,a,r),rx(r)}),s&&i)throw new Error(n+' contains ".value" child '+xs(r)+" in addition to actual children.")}},Sk=function(n,e){let t,r;for(t=0;t{let l=new ue(o);if(fc(s,a,Ie(t,l)),k_(l)===".priority"&&!ic(a))throw new Error(s+"contains an invalid value for '"+l.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");i.push(l)}),Sk(s,i)},Q_=function(n,e,t){if(!(t&&e===void 0)){if(Th(e))throw new Error(gt(n,"priority")+"is "+e.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!ic(e))throw new Error(gt(n,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},pc=function(n,e,t,r){if(!(r&&t===void 0)&&!kh(t))throw new Error(gt(n,e)+'was an invalid key = "'+t+`". Firebase keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]").`)},eo=function(n,e,t,r){if(!(r&&t===void 0)&&!Bb(t))throw new Error(gt(n,e)+'was an invalid path = "'+t+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Rk=function(n,e,t,r){t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),eo(n,e,t,r)},Rt=function(n,e){if(Z(e)===".info")throw new Error(n+" failed = Can't modify data under /.info/")},jb=function(n,e){let t=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!kh(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||t.length!==0&&!Ck(t))throw new Error(gt(n,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};var h_=class{constructor(){this.eventLists_=[],this.recursionDepth_=0}};function Nh(n,e){let t=null;for(let r=0;rN_(r,e))}function Pt(n,e,t){Nh(n,t),zb(n,r=>Mt(r,e)||Mt(e,r))}function zb(n,e){n.recursionDepth_++;let t=!0;for(let r=0;r{qA(n,r,s,i,o)},n.authTokenProvider_,n.appCheckProvider_),setTimeout(()=>jA(n,!0),0);else{if(typeof t<"u"&&t!==null){if(typeof t!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Oe(t)}catch(r){throw new Error("Invalid authOverride provided: "+r)}}n.persistentConnection_=new D_(n.repoInfo_,e,(r,s,i,o)=>{qA(n,r,s,i,o)},r=>{jA(n,r)},r=>{Nk(n,r)},n.authTokenProvider_,n.appCheckProvider_,t),n.server_=n.persistentConnection_}n.authTokenProvider_.addTokenChangeListener(r=>{n.server_.refreshAuthToken(r)}),n.appCheckProvider_.addTokenChangeListener(r=>{n.server_.refreshAppCheckToken(r.token)}),n.statsReporter_=DP(n.repoInfo_,()=>new Yg(n.stats_,n.server_)),n.infoData_=new Wg,n.infoSyncTree_=new ph({startListening:(r,s,i,o)=>{let a=[],l=n.infoData_.getNode(r._path);return l.isEmpty()||(a=hc(n.infoSyncTree_,r._path,l),setTimeout(()=>{o("ok")},0)),a},stopListening:()=>{}}),Y_(n,"connected",!1),n.serverSyncTree_=new ph({startListening:(r,s,i,o)=>(n.server_.listen(r,i,s,(a,l)=>{let u=o(a,l);Pt(n.eventQueue_,r._path,u)}),[]),stopListening:(r,s)=>{n.server_.unlisten(r,s)}})}function Wb(n){let t=n.infoData_.getNode(new ue(".info/serverTimeOffset")).val()||0;return new Date().getTime()+t}function mc(n){return yk({timestamp:Wb(n)})}function qA(n,e,t,r,s){n.dataUpdateCount++;let i=new ue(e);t=n.interceptServerDataCallback_?n.interceptServerDataCallback_(e,t):t;let o=[];if(s)if(r){let l=Ro(t,u=>be(u));o=dk(n.serverSyncTree_,i,l,s)}else{let l=be(t);o=Db(n.serverSyncTree_,i,l,s)}else if(r){let l=Ro(t,u=>be(u));o=lk(n.serverSyncTree_,i,l)}else{let l=be(t);o=hc(n.serverSyncTree_,i,l)}let a=i;o.length>0&&(a=Qi(n,i)),Pt(n.eventQueue_,a,o)}function jA(n,e){Y_(n,"connected",e),e===!1&&Ok(n)}function Nk(n,e){Je(e,(t,r)=>{Y_(n,t,r)})}function Y_(n,e,t){let r=new ue("/.info/"+e),s=be(t);n.infoData_.updateSnapshot(r,s);let i=hc(n.infoSyncTree_,r,s);Pt(n.eventQueue_,r,i)}function Dh(n){return n.nextWriteId_++}function Dk(n,e,t){let r=fk(n.serverSyncTree_,e);return r!=null?Promise.resolve(r):n.server_.get(e).then(s=>{let i=be(s).withIndex(e._queryParams.getIndex());a_(n.serverSyncTree_,e,t,!0);let o;if(e._queryParams.loadsAllData())o=hc(n.serverSyncTree_,e._path,i);else{let a=rc(n.serverSyncTree_,e);o=Db(n.serverSyncTree_,e._path,i,a)}return Pt(n.eventQueue_,e._path,o),mh(n.serverSyncTree_,e,t,null,!0),i},s=>(to(n,"get for query "+Oe(e)+" failed: "+s),Promise.reject(new Error(s))))}function J_(n,e,t,r,s){to(n,"set",{path:e.toString(),value:t,priority:r});let i=mc(n),o=be(t,r),a=Sh(n.serverSyncTree_,e),l=W_(o,a,i),u=Dh(n),d=j_(n.serverSyncTree_,e,l,u,!0);Nh(n.eventQueue_,d),n.server_.put(e.toString(),o.val(!0),(m,v)=>{let S=m==="ok";S||st("set at "+e+" failed: "+m);let x=Nr(n.serverSyncTree_,u,!S);Pt(n.eventQueue_,e,x),Lr(n,s,m,v)});let p=Z_(n,e);Qi(n,p),Pt(n.eventQueue_,p,[])}function Vk(n,e,t,r){to(n,"update",{path:e.toString(),value:t});let s=!0,i=mc(n),o={};if(Je(t,(a,l)=>{s=!1,o[a]=Fb(Ie(e,a),be(l),n.serverSyncTree_,i)}),s)Ye("update() called with empty data. Don't do anything."),Lr(n,r,"ok",void 0);else{let a=Dh(n),l=ck(n.serverSyncTree_,e,o,a);Nh(n.eventQueue_,l),n.server_.merge(e.toString(),t,(u,d)=>{let p=u==="ok";p||st("update at "+e+" failed: "+u);let m=Nr(n.serverSyncTree_,a,!p),v=m.length>0?Qi(n,e):e;Pt(n.eventQueue_,v,m),Lr(n,r,u,d)}),Je(t,u=>{let d=Z_(n,Ie(e,u));Qi(n,d)}),Pt(n.eventQueue_,e,[])}}function Ok(n){to(n,"onDisconnectEvents");let e=mc(n),t=ih();Hg(n.onDisconnect_,le(),(s,i)=>{let o=Fb(s,i,n.serverSyncTree_,e);Xi(t,s,o)});let r=[];Hg(t,le(),(s,i)=>{r=r.concat(hc(n.serverSyncTree_,s,i));let o=Z_(n,s);Qi(n,o)}),n.onDisconnect_=ih(),Pt(n.eventQueue_,le(),r)}function Mk(n,e,t){n.server_.onDisconnectCancel(e.toString(),(r,s)=>{r==="ok"&&$g(n.onDisconnect_,e),Lr(n,t,r,s)})}function GA(n,e,t,r){let s=be(t);n.server_.onDisconnectPut(e.toString(),s.val(!0),(i,o)=>{i==="ok"&&Xi(n.onDisconnect_,e,s),Lr(n,r,i,o)})}function Fk(n,e,t,r,s){let i=be(t,r);n.server_.onDisconnectPut(e.toString(),i.val(!0),(o,a)=>{o==="ok"&&Xi(n.onDisconnect_,e,i),Lr(n,s,o,a)})}function Lk(n,e,t,r){if(Kc(t)){Ye("onDisconnect().update() called with empty data. Don't do anything."),Lr(n,r,"ok",void 0);return}n.server_.onDisconnectMerge(e.toString(),t,(s,i)=>{s==="ok"&&Je(t,(o,a)=>{let l=be(a);Xi(n.onDisconnect_,Ie(e,o),l)}),Lr(n,r,s,i)})}function Uk(n,e,t){let r;Z(e._path)===".info"?r=a_(n.infoSyncTree_,e,t):r=a_(n.serverSyncTree_,e,t),Gb(n.eventQueue_,e._path,r)}function f_(n,e,t){let r;Z(e._path)===".info"?r=mh(n.infoSyncTree_,e,t):r=mh(n.serverSyncTree_,e,t),Gb(n.eventQueue_,e._path,r)}function $b(n){n.persistentConnection_&&n.persistentConnection_.interrupt(Kb)}function Bk(n){n.persistentConnection_&&n.persistentConnection_.resume(Kb)}function to(n,...e){let t="";n.persistentConnection_&&(t=n.persistentConnection_.id+":"),Ye(t,...e)}function Lr(n,e,t,r){e&&Ji(()=>{if(t==="ok")e(null);else{let s=(t||"error").toUpperCase(),i=s;r&&(i+=": "+r);let o=new Error(i);o.code=s,e(o)}})}function qk(n,e,t,r,s,i){to(n,"transaction on "+e);let o={path:e,update:t,onComplete:r,status:null,order:WA(),applyLocally:i,retryCount:0,unwatcher:s,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=X_(n,e,void 0);o.currentInputSnapshot=a;let l=o.update(a.val());if(l===void 0)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{fc("transaction failed: Data returned ",l,o.path),o.status=0;let u=Ph(n.transactionQueueTree_,e),d=Ms(u)||[];d.push(o),H_(u,d);let p;typeof l=="object"&&l!==null&&Nt(l,".priority")?(p=Xn(l,".priority"),V(ic(p),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):p=(Sh(n.serverSyncTree_,e)||Y.EMPTY_NODE).getPriority().val();let m=mc(n),v=be(l,p),S=W_(v,a,m);o.currentOutputSnapshotRaw=v,o.currentOutputSnapshotResolved=S,o.currentWriteId=Dh(n);let x=j_(n.serverSyncTree_,e,S,o.currentWriteId,o.applyLocally);Pt(n.eventQueue_,e,x),Vh(n,n.transactionQueueTree_)}}function X_(n,e,t){return Sh(n.serverSyncTree_,e,t)||Y.EMPTY_NODE}function Vh(n,e=n.transactionQueueTree_){if(e||Oh(n,e),Ms(e)){let t=Qb(n,e);V(t.length>0,"Sending zero length transaction queue"),t.every(s=>s.status===0)&&jk(n,dc(e),t)}else Lb(e)&&xh(e,t=>{Vh(n,t)})}function jk(n,e,t){let r=t.map(u=>u.currentWriteId),s=X_(n,e,r),i=s,o=s.hash();for(let u=0;u{to(n,"transaction put response",{path:l.toString(),status:u});let d=[];if(u==="ok"){let p=[];for(let m=0;mt[m].onComplete(null,!0,t[m].currentOutputSnapshotResolved)),t[m].unwatcher();Oh(n,Ph(n.transactionQueueTree_,e)),Vh(n,n.transactionQueueTree_),Pt(n.eventQueue_,e,d);for(let m=0;ma.status===0).map(a=>a.currentWriteId);for(let a=0;a=xk)d=!0,p="maxretry",s=s.concat(Nr(n.serverSyncTree_,l.currentWriteId,!0));else{let m=X_(n,l.path,o);l.currentInputSnapshot=m;let v=e[a].update(m.val());if(v!==void 0){fc("transaction failed: Data returned ",v,l.path);let S=be(v);typeof v=="object"&&v!=null&&Nt(v,".priority")||(S=S.updatePriority(m.getPriority()));let k=l.currentWriteId,q=mc(n),G=W_(S,m,q);l.currentOutputSnapshotRaw=S,l.currentOutputSnapshotResolved=G,l.currentWriteId=Dh(n),o.splice(o.indexOf(k),1),s=s.concat(j_(n.serverSyncTree_,l.path,G,l.currentWriteId,l.applyLocally)),s=s.concat(Nr(n.serverSyncTree_,k,!0))}else d=!0,p="nodata",s=s.concat(Nr(n.serverSyncTree_,l.currentWriteId,!0))}Pt(n.eventQueue_,t,s),s=[],d&&(e[a].status=2,(function(m){setTimeout(m,Math.floor(0))})(e[a].unwatcher),e[a].onComplete&&(p==="nodata"?r.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):r.push(()=>e[a].onComplete(new Error(p),!1,null))))}Oh(n,n.transactionQueueTree_);for(let a=0;ar.order-s.order),t}function Yb(n,e,t){let r=Ms(e);if(r)for(let s=0;s{Yb(n,s,t)})}function Oh(n,e){let t=Ms(e);if(t){let r=0;for(let s=0;s0?t:void 0)}xh(e,r=>{Oh(n,r)})}function Z_(n,e){let t=dc(Hb(n,e)),r=Ph(n.transactionQueueTree_,e);return Tk(r,s=>{Tg(n,s)}),Tg(n,r),Ub(r,s=>{Tg(n,s)}),t}function Tg(n,e){let t=Ms(e);if(t){let r=[],s=[],i=-1;for(let o=0;o0){let s=t[r];try{s=decodeURIComponent(s.replace(/\+/g," "))}catch{}e+="/"+s}return e}function Kk(n){let e={};n.charAt(0)==="?"&&(n=n.substring(1));for(let t of n.split("&")){if(t.length===0)continue;let r=t.split("=");r.length===2?e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):st(`Invalid query segment '${t}' in query '${n}'`)}return e}var p_=function(n,e){let t=Wk(n),r=t.namespace;t.domain==="firebase.com"&&wn(t.host+" is no longer supported. Please use .firebaseio.com instead"),(!r||r==="undefined")&&t.domain!=="localhost"&&wn("Cannot parse Firebase url. Please use https://.firebaseio.com"),t.secure||TP();let s=t.scheme==="ws"||t.scheme==="wss";return{repoInfo:new Ju(t.host,t.secure,r,s,e,"",r!==t.subdomain),path:new ue(t.pathString)}},Wk=function(n){let e="",t="",r="",s="",i="",o=!0,a="https",l=443;if(typeof n=="string"){let u=n.indexOf("//");u>=0&&(a=n.substring(0,u-1),n=n.substring(u+2));let d=n.indexOf("/");d===-1&&(d=n.length);let p=n.indexOf("?");p===-1&&(p=n.length),e=n.substring(0,Math.min(d,p)),d=0?(o=a==="https"||a==="wss",l=parseInt(e.substring(u+1),10)):u=e.length;let v=e.slice(0,u);if(v.toLowerCase()==="localhost")t="localhost";else if(v.split(".").length<=2)t=v;else{let S=e.indexOf(".");r=e.substring(0,S).toLowerCase(),t=e.substring(S+1),i=r}"ns"in m&&(i=m.ns)}return{host:e,port:l,domain:t,subdomain:r,secure:o,scheme:a,pathString:s,namespace:i}};var zA="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",$k=(function(){let n=0,e=[];return function(t){let r=t===n;n=t;let s,i=new Array(8);for(s=7;s>=0;s--)i[s]=zA.charAt(t%64),t=Math.floor(t/64);V(t===0,"Cannot push at time == 0");let o=i.join("");if(r){for(s=11;s>=0&&e[s]===63;s--)e[s]=0;e[s]++}else for(s=0;s<12;s++)e[s]=Math.floor(Math.random()*64);for(s=0;s<12;s++)o+=zA.charAt(e[s]);return V(o.length===20,"nextPushId: Length should be 20."),o}})();var gh=class{constructor(e,t,r,s){this.eventType=e,this.eventRegistration=t,this.snapshot=r,this.prevName=s}getPath(){let e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Oe(this.snapshot.exportVal())}},_h=class{constructor(e,t,r){this.eventRegistration=e,this.error=t,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}};var oc=class{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return V(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}};var yh=class{constructor(e,t){this._repo=e,this._path=t}cancel(){let e=new Qe;return Mk(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){Rt("OnDisconnect.remove",this._path);let e=new Qe;return GA(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){Rt("OnDisconnect.set",this._path),Tn("OnDisconnect.set",e,this._path,!1);let t=new Qe;return GA(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){Rt("OnDisconnect.setWithPriority",this._path),Tn("OnDisconnect.setWithPriority",e,this._path,!1),Q_("OnDisconnect.setWithPriority",t,!1);let r=new Qe;return Fk(this._repo,this._path,e,t,r.wrapCallback(()=>{})),r.promise}update(e){Rt("OnDisconnect.update",this._path),qb("OnDisconnect.update",e,this._path,!1);let t=new Qe;return Lk(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}};var pt=class n{constructor(e,t,r,s){this._repo=e,this._path=t,this._queryParams=r,this._orderByCalled=s}get key(){return ee(this._path)?null:k_(this._path)}get ref(){return new xt(this._repo,this._path)}get _queryIdentifier(){let e=xA(this._queryParams),t=P_(e);return t==="{}"?"default":t}get _queryObject(){return xA(this._queryParams)}isEqual(e){if(e=te(e),!(e instanceof n))return!1;let t=this._repo===e._repo,r=N_(this._path,e._path),s=this._queryIdentifier===e._queryIdentifier;return t&&r&&s}toJSON(){return this.toString()}toString(){return this._repo.toString()+ex(this._path)}};function Mh(n,e){if(n._orderByCalled===!0)throw new Error(e+": You can't combine multiple orderBy calls.")}function Br(n){let e=null,t=null;if(n.hasStart()&&(e=n.getIndexStartValue()),n.hasEnd()&&(t=n.getIndexEndValue()),n.getIndex()===vn){let r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",s="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(n.hasStart()){if(n.getIndexStartName()!==Or)throw new Error(r);if(typeof e!="string")throw new Error(s)}if(n.hasEnd()){if(n.getIndexEndName()!==Bn)throw new Error(r);if(typeof t!="string")throw new Error(s)}}else if(n.getIndex()===ve){if(e!=null&&!ic(e)||t!=null&&!ic(t))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(V(n.getIndex()instanceof Ya||n.getIndex()===O_,"unknown index type."),e!=null&&typeof e=="object"||t!=null&&typeof t=="object")throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Fh(n){if(n.hasStart()&&n.hasEnd()&&n.hasLimit()&&!n.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}var xt=class n extends pt{constructor(e,t){super(e,t,new ec,!1)}get parent(){let e=fb(this._path);return e===null?null:new n(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}},Yi=class n{constructor(e,t,r){this._node=e,this.ref=t,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){let t=new ue(e),r=Ur(this.ref,e);return new n(this._node.getChild(t),r,ve)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(r,s)=>e(new n(s,Ur(this.ref,r),ve)))}hasChild(e){let t=new ue(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}};function ey(n,e){return n=te(n),n._checkNotDeleted("ref"),e!==void 0?Ur(n._root,e):n._root}function ty(n,e){n=te(n),n._checkNotDeleted("refFromURL");let t=p_(e,n._repo.repoInfo_.nodeAdmin);jb("refFromURL",t);let r=t.repoInfo;return!n._repo.repoInfo_.isCustomHost()&&r.host!==n._repo.repoInfo_.host&&wn("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+n._repo.repoInfo_.host+")"),ey(n,t.path.toString())}function Ur(n,e){return n=te(n),Z(n._path)===null?Rk("child","path",e,!1):eo("child","path",e,!1),new xt(n._repo,Ie(n._path,e))}function Jb(n,e){n=te(n),Rt("push",n._path),Tn("push",e,n._path,!0);let t=Wb(n._repo),r=$k(t),s=Ur(n,r),i=Ur(n,r),o;return e!=null?o=Lh(i,e).then(()=>i):o=Promise.resolve(i),s.then=o.then.bind(o),s.catch=o.then.bind(o,void 0),s}function Xb(n){return Rt("remove",n._path),Lh(n,null)}function Lh(n,e){n=te(n),Rt("set",n._path),Tn("set",e,n._path,!1);let t=new Qe;return J_(n._repo,n._path,e,null,t.wrapCallback(()=>{})),t.promise}function Zb(n,e){n=te(n),Rt("setPriority",n._path),Q_("setPriority",e,!1);let t=new Qe;return J_(n._repo,Ie(n._path,".priority"),e,null,t.wrapCallback(()=>{})),t.promise}function eC(n,e,t){if(Rt("setWithPriority",n._path),Tn("setWithPriority",e,n._path,!1),Q_("setWithPriority",t,!1),n.key===".length"||n.key===".keys")throw"setWithPriority failed: "+n.key+" is a read-only object.";let r=new Qe;return J_(n._repo,n._path,e,t,r.wrapCallback(()=>{})),r.promise}function tC(n,e){qb("update",e,n._path,!1);let t=new Qe;return Vk(n._repo,n._path,e,t.wrapCallback(()=>{})),t.promise}function nC(n){n=te(n);let e=new oc(()=>{}),t=new ac(e);return Dk(n._repo,n,t).then(r=>new Yi(r,new xt(n._repo,n._path),n._queryParams.getIndex()))}var ac=class n{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,t){let r=t._queryParams.getIndex();return new gh("value",this,new Yi(e.snapshotNode,new xt(t._repo,t._path),r))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new _h(this,e,t):null}matches(e){return e instanceof n?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}},vh=class n{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t=e==="children_added"?"child_added":e;return t=t==="children_removed"?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new _h(this,e,t):null}createEvent(e,t){V(e.childName!=null,"Child events should have a childName.");let r=Ur(new xt(t._repo,t._path),e.childName),s=t._queryParams.getIndex();return new gh(e.type,this,new Yi(e.snapshotNode,r,s),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof n?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}};function gc(n,e,t,r,s){let i;if(typeof r=="object"&&(i=void 0,s=r),typeof r=="function"&&(i=r),s&&s.onlyOnce){let l=t,u=(d,p)=>{f_(n._repo,n,a),l(d,p)};u.userCallback=t.userCallback,u.context=t.context,t=u}let o=new oc(t,i||void 0),a=e==="value"?new ac(o):new vh(e,o);return Uk(n._repo,n,a),()=>f_(n._repo,n,a)}function Uh(n,e,t,r){return gc(n,"value",e,t,r)}function ny(n,e,t,r){return gc(n,"child_added",e,t,r)}function ry(n,e,t,r){return gc(n,"child_changed",e,t,r)}function sy(n,e,t,r){return gc(n,"child_moved",e,t,r)}function iy(n,e,t,r){return gc(n,"child_removed",e,t,r)}function oy(n,e,t){let r=null,s=t?new oc(t):null;e==="value"?r=new ac(s):e&&(r=new vh(e,s)),f_(n._repo,n,r)}var kt=class{},wh=class extends kt{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){Tn("endAt",this._value,e._path,!0);let t=zg(e._queryParams,this._value,this._key);if(Fh(t),Br(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new pt(e._repo,e._path,t,e._orderByCalled)}};function rC(n,e){return pc("endAt","key",e,!0),new wh(n,e)}var m_=class extends kt{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){Tn("endBefore",this._value,e._path,!1);let t=vx(e._queryParams,this._value,this._key);if(Fh(t),Br(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new pt(e._repo,e._path,t,e._orderByCalled)}};function sC(n,e){return pc("endBefore","key",e,!0),new m_(n,e)}var Eh=class extends kt{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){Tn("startAt",this._value,e._path,!0);let t=Gg(e._queryParams,this._value,this._key);if(Fh(t),Br(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new pt(e._repo,e._path,t,e._orderByCalled)}};function iC(n=null,e){return pc("startAt","key",e,!0),new Eh(n,e)}var g_=class extends kt{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){Tn("startAfter",this._value,e._path,!1);let t=yx(e._queryParams,this._value,this._key);if(Fh(t),Br(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new pt(e._repo,e._path,t,e._orderByCalled)}};function oC(n,e){return pc("startAfter","key",e,!0),new g_(n,e)}var __=class extends kt{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new pt(e._repo,e._path,gx(e._queryParams,this._limit),e._orderByCalled)}};function aC(n){if(typeof n!="number"||Math.floor(n)!==n||n<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new __(n)}var y_=class extends kt{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new pt(e._repo,e._path,_x(e._queryParams,this._limit),e._orderByCalled)}};function cC(n){if(typeof n!="number"||Math.floor(n)!==n||n<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new y_(n)}var v_=class extends kt{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Mh(e,"orderByChild");let t=new ue(this._path);if(ee(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");let r=new Ya(t),s=Ih(e._queryParams,r);return Br(s),new pt(e._repo,e._path,s,!0)}};function lC(n){if(n==="$key")throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if(n==="$priority")throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if(n==="$value")throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return eo("orderByChild","path",n,!1),new v_(n)}var w_=class extends kt{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){Mh(e,"orderByKey");let t=Ih(e._queryParams,vn);return Br(t),new pt(e._repo,e._path,t,!0)}};function uC(){return new w_}var E_=class extends kt{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){Mh(e,"orderByPriority");let t=Ih(e._queryParams,ve);return Br(t),new pt(e._repo,e._path,t,!0)}};function hC(){return new E_}var T_=class extends kt{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){Mh(e,"orderByValue");let t=Ih(e._queryParams,O_);return Br(t),new pt(e._repo,e._path,t,!0)}};function dC(){return new T_}var I_=class extends kt{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(Tn("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new wh(this._value,this._key)._apply(new Eh(this._value,this._key)._apply(e))}};function fC(n,e){return pc("equalTo","key",e,!0),new I_(n,e)}function Lt(n,...e){let t=te(n);for(let r of e)t=r._apply(t);return t}ek(xt);ik(xt);var Hk="FIREBASE_DATABASE_EMULATOR_HOST",A_={},Qk=!1;function Yk(n,e,t,r){let s=e.lastIndexOf(":"),i=e.substring(0,s),o=Ws(i);n.repoInfo_=new Ju(e,o,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),r&&(n.authTokenProvider_=r)}function ay(n,e,t,r,s){let i=r||n.options.databaseURL;i===void 0&&(n.options.projectId||wn("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Ye("Using default host for project ",n.options.projectId),i=`${n.options.projectId}-default-rtdb.firebaseio.com`);let o=p_(i,s),a=o.repoInfo,l,u;typeof process<"u"&&process.env&&(u=process.env[Hk]),u?(l=!0,i=`http://${u}?ns=${a.namespace}`,o=p_(i,s),a=o.repoInfo):l=!o.repoInfo.secure;let d=s&&l?new za(za.OWNER):new Rg(n.name,n.options,e);jb("Invalid Firebase Database URL",o),ee(o.path)||wn("Database URL must point to the root of a Firebase Database (not including a child path).");let p=Xk(a,n,d,new Sg(n,t));return new b_(p,n)}function Jk(n,e){let t=A_[e];(!t||t[n.key]!==n)&&wn(`Database ${e}(${n.repoInfo_}) has already been deleted.`),$b(n),delete t[n.key]}function Xk(n,e,t,r){let s=A_[e.name];s||(s={},A_[e.name]=s);let i=s[n.toURLString()];return i&&wn("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),i=new d_(n,Qk,t,r),s[n.toURLString()]=i,i}var b_=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(kk(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new xt(this._repo,le())),this._rootInternal}_delete(){return this._rootInternal!==null&&(Jk(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&wn("Cannot call "+e+" on a deleted database.")}};function pC(){db.IS_TRANSPORT_INITIALIZED&&st("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function mC(){pC(),Ha.forceDisallow()}function gC(){pC(),Bi.forceDisallow(),Ha.forceAllow()}function _C(n,e,t,r={}){n=te(n),n._checkNotDeleted("useEmulator");let s=`${e}:${t}`,i=n._repoInternal;if(n._instanceStarted){if(s===n._repoInternal.repoInfo_.host&&Hr(r,i.repoInfo_.emulatorOptions))return;wn("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o;if(i.repoInfo_.nodeAdmin)r.mockUserToken&&wn('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new za(za.OWNER);else if(r.mockUserToken){let a=typeof r.mockUserToken=="string"?r.mockUserToken:jc(r.mockUserToken,n.app.options.projectId);o=new za(a)}Ws(e)&&Wc(e),Yk(i,s,r,o)}function yC(n){n=te(n),n._checkNotDeleted("goOffline"),$b(n._repo)}function vC(n){n=te(n),n._checkNotDeleted("goOnline"),Bk(n._repo)}function wC(n,e){HA(n,e)}function Zk(n){R_(Qc),Qr(new At("database",(e,{instanceIdentifier:t})=>{let r=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return ay(r,s,i,t)},"PUBLIC").setMultipleInstances(!0)),Bt(fA,pA,n),Bt(fA,pA,"esm2020")}var eN={".sv":"timestamp"};function EC(){return eN}function TC(n){return{".sv":{increment:n}}}var C_=class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function IC(n,e,t){if(n=te(n),Rt("Reference.transaction",n._path),n.key===".length"||n.key===".keys")throw"Reference.transaction failed: "+n.key+" is a read-only object.";let r=t?.applyLocally??!0,s=new Qe,i=(a,l,u)=>{let d=null;a?s.reject(a):(d=new Yi(u,new xt(n._repo,n._path),ve),s.resolve(new C_(l,d)))},o=Uh(n,()=>{});return qk(n._repo,n._path,e,i,o,r),s.promise}D_.prototype.simpleListen=function(n,e){this.sendRequest("q",{p:n},e)};D_.prototype.echo=function(n,e){this.sendRequest("echo",{d:n},e)};Zk();var tN="@firebase/database-compat",nN="2.1.4";var rN=new Zn("@firebase/database-compat"),AC=function(n){let e="FIREBASE WARNING: "+n;rN.warn(e)};var sN=function(n,e,t,r){if(!(r&&t===void 0)&&typeof t!="boolean")throw new Error(gt(n,e)+"must be a boolean.")},iN=function(n,e,t){if(!(t&&e===void 0))switch(e){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(gt(n,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}};var cy=class{constructor(e){this._delegate=e}cancel(e){z("OnDisconnect.cancel",0,1,arguments.length),je("OnDisconnect.cancel","onComplete",e,!0);let t=this._delegate.cancel();return e&&t.then(()=>e(null),r=>e(r)),t}remove(e){z("OnDisconnect.remove",0,1,arguments.length),je("OnDisconnect.remove","onComplete",e,!0);let t=this._delegate.remove();return e&&t.then(()=>e(null),r=>e(r)),t}set(e,t){z("OnDisconnect.set",1,2,arguments.length),je("OnDisconnect.set","onComplete",t,!0);let r=this._delegate.set(e);return t&&r.then(()=>t(null),s=>t(s)),r}setWithPriority(e,t,r){z("OnDisconnect.setWithPriority",2,3,arguments.length),je("OnDisconnect.setWithPriority","onComplete",r,!0);let s=this._delegate.setWithPriority(e,t);return r&&s.then(()=>r(null),i=>r(i)),s}update(e,t){if(z("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){let s={};for(let i=0;it(null),s=>t(s)),r}};var ly=class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return z("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}};var Fs=class n{constructor(e,t){this._database=e,this._delegate=t}val(){return z("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return z("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return z("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return z("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return z("DataSnapshot.child",0,1,arguments.length),e=String(e),eo("DataSnapshot.child","path",e,!1),new n(this._database,this._delegate.child(e))}hasChild(e){return z("DataSnapshot.hasChild",1,1,arguments.length),eo("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return z("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return z("DataSnapshot.forEach",1,1,arguments.length),je("DataSnapshot.forEach","action",e,!1),this._delegate.forEach(t=>e(new n(this._database,t)))}hasChildren(){return z("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return z("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return z("DataSnapshot.ref",0,0,arguments.length),new qn(this._database,this._delegate.ref)}get ref(){return this.getRef()}},Bh=class n{constructor(e,t){this.database=e,this._delegate=t}on(e,t,r,s){z("Query.on",2,4,arguments.length),je("Query.on","callback",t,!1);let i=n.getCancelAndContextArgs_("Query.on",r,s),o=(l,u)=>{t.call(i.context,new Fs(this.database,l),u)};o.userCallback=t,o.context=i.context;let a=i.cancel?.bind(i.context);switch(e){case"value":return Uh(this._delegate,o,a),t;case"child_added":return ny(this._delegate,o,a),t;case"child_removed":return iy(this._delegate,o,a),t;case"child_changed":return ry(this._delegate,o,a),t;case"child_moved":return sy(this._delegate,o,a),t;default:throw new Error(gt("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,r){if(z("Query.off",0,3,arguments.length),iN("Query.off",e,!0),je("Query.off","callback",t,!0),Nd("Query.off","context",r,!0),t){let s=()=>{};s.userCallback=t,s.context=r,oy(this._delegate,e,s)}else oy(this._delegate,e)}get(){return nC(this._delegate).then(e=>new Fs(this.database,e))}once(e,t,r,s){z("Query.once",1,4,arguments.length),je("Query.once","callback",t,!0);let i=n.getCancelAndContextArgs_("Query.once",r,s),o=new Qe,a=(u,d)=>{let p=new Fs(this.database,u);t&&t.call(i.context,p,d),o.resolve(p)};a.userCallback=t,a.context=i.context;let l=u=>{i.cancel&&i.cancel.call(i.context,u),o.reject(u)};switch(e){case"value":Uh(this._delegate,a,l,{onlyOnce:!0});break;case"child_added":ny(this._delegate,a,l,{onlyOnce:!0});break;case"child_removed":iy(this._delegate,a,l,{onlyOnce:!0});break;case"child_changed":ry(this._delegate,a,l,{onlyOnce:!0});break;case"child_moved":sy(this._delegate,a,l,{onlyOnce:!0});break;default:throw new Error(gt("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return o.promise}limitToFirst(e){return z("Query.limitToFirst",1,1,arguments.length),new n(this.database,Lt(this._delegate,aC(e)))}limitToLast(e){return z("Query.limitToLast",1,1,arguments.length),new n(this.database,Lt(this._delegate,cC(e)))}orderByChild(e){return z("Query.orderByChild",1,1,arguments.length),new n(this.database,Lt(this._delegate,lC(e)))}orderByKey(){return z("Query.orderByKey",0,0,arguments.length),new n(this.database,Lt(this._delegate,uC()))}orderByPriority(){return z("Query.orderByPriority",0,0,arguments.length),new n(this.database,Lt(this._delegate,hC()))}orderByValue(){return z("Query.orderByValue",0,0,arguments.length),new n(this.database,Lt(this._delegate,dC()))}startAt(e=null,t){return z("Query.startAt",0,2,arguments.length),new n(this.database,Lt(this._delegate,iC(e,t)))}startAfter(e=null,t){return z("Query.startAfter",0,2,arguments.length),new n(this.database,Lt(this._delegate,oC(e,t)))}endAt(e=null,t){return z("Query.endAt",0,2,arguments.length),new n(this.database,Lt(this._delegate,rC(e,t)))}endBefore(e=null,t){return z("Query.endBefore",0,2,arguments.length),new n(this.database,Lt(this._delegate,sC(e,t)))}equalTo(e,t){return z("Query.equalTo",1,2,arguments.length),new n(this.database,Lt(this._delegate,fC(e,t)))}toString(){return z("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return z("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(z("Query.isEqual",1,1,arguments.length),!(e instanceof n)){let t="Query.isEqual failed: First argument must be an instance of firebase.database.Query.";throw new Error(t)}return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,r){let s={cancel:void 0,context:void 0};if(t&&r)s.cancel=t,je(e,"cancel",s.cancel,!0),s.context=r,Nd(e,"context",s.context,!0);else if(t)if(typeof t=="object"&&t!==null)s.context=t;else if(typeof t=="function")s.cancel=t;else throw new Error(gt(e,"cancelOrContext")+" must either be a cancel callback or a context object.");return s}get ref(){return new qn(this.database,new xt(this._delegate._repo,this._delegate._path))}},qn=class n extends Bh{constructor(e,t){super(e,new pt(t._repo,t._path,new ec,!1)),this.database=e,this._delegate=t}getKey(){return z("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return z("Reference.child",1,1,arguments.length),typeof e=="number"&&(e=String(e)),new n(this.database,Ur(this._delegate,e))}getParent(){z("Reference.parent",0,0,arguments.length);let e=this._delegate.parent;return e?new n(this.database,e):null}getRoot(){return z("Reference.root",0,0,arguments.length),new n(this.database,this._delegate.root)}set(e,t){z("Reference.set",1,2,arguments.length),je("Reference.set","onComplete",t,!0);let r=Lh(this._delegate,e);return t&&r.then(()=>t(null),s=>t(s)),r}update(e,t){if(z("Reference.update",1,2,arguments.length),Array.isArray(e)){let s={};for(let i=0;it(null),s=>t(s)),r}setWithPriority(e,t,r){z("Reference.setWithPriority",2,3,arguments.length),je("Reference.setWithPriority","onComplete",r,!0);let s=eC(this._delegate,e,t);return r&&s.then(()=>r(null),i=>r(i)),s}remove(e){z("Reference.remove",0,1,arguments.length),je("Reference.remove","onComplete",e,!0);let t=Xb(this._delegate);return e&&t.then(()=>e(null),r=>e(r)),t}transaction(e,t,r){z("Reference.transaction",1,3,arguments.length),je("Reference.transaction","transactionUpdate",e,!1),je("Reference.transaction","onComplete",t,!0),sN("Reference.transaction","applyLocally",r,!0);let s=IC(this._delegate,e,{applyLocally:r}).then(i=>new ly(i.committed,new Fs(this.database,i.snapshot)));return t&&s.then(i=>t(null,i.committed,i.snapshot),i=>t(i,!1,null)),s}setPriority(e,t){z("Reference.setPriority",1,2,arguments.length),je("Reference.setPriority","onComplete",t,!0);let r=Zb(this._delegate,e);return t&&r.then(()=>t(null),s=>t(s)),r}push(e,t){z("Reference.push",0,2,arguments.length),je("Reference.push","onComplete",t,!0);let r=Jb(this._delegate,e),s=r.then(o=>new n(this.database,o));t&&s.then(()=>t(null),o=>t(o));let i=new n(this.database,r);return i.then=s.then.bind(s),i.catch=s.catch.bind(s,void 0),i}onDisconnect(){return Rt("Reference.onDisconnect",this._delegate._path),new cy(new yh(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}};var Ls=class{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:mC,forceLongPolling:gC}}useEmulator(e,t,r={}){_C(this._delegate,e,t,r)}ref(e){if(z("database.ref",0,1,arguments.length),e instanceof qn){let t=ty(this._delegate,e.toString());return new qn(this,t)}else{let t=ey(this._delegate,e);return new qn(this,t)}}refFromURL(e){z("database.refFromURL",1,1,arguments.length);let r=ty(this._delegate,e);return new qn(this,r)}goOffline(){return z("database.goOffline",0,0,arguments.length),yC(this._delegate)}goOnline(){return z("database.goOnline",0,0,arguments.length),vC(this._delegate)}};Ls.ServerValue={TIMESTAMP:EC(),increment:n=>TC(n)};function oN({app:n,url:e,version:t,customAuthImpl:r,customAppCheckImpl:s,namespace:i,nodeAdmin:o=!1}){R_(t);let a=new Dd("database-standalone"),l=new $c("auth-internal",a);l.setComponent(new At("auth-internal",()=>r,"PRIVATE"));let u;return s&&(u=new $c("app-check-internal",a),u.setComponent(new At("app-check-internal",()=>s,"PRIVATE"))),{instance:new Ls(ay(n,l,u,e,o),n),namespace:i}}var aN=Object.freeze({__proto__:null,initStandalone:oN});var cN=Ls.ServerValue;function lN(n){n.INTERNAL.registerComponent(new At("database-compat",(e,{instanceIdentifier:t})=>{let r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("database").getImmediate({identifier:t});return new Ls(s,r)},"PUBLIC").setServiceProps({Reference:qn,Query:Bh,Database:Ls,DataSnapshot:Fs,enableLogging:wC,INTERNAL:aN,ServerValue:cN}).setMultipleInstances(!0)),n.registerVersion(tN,nN)}lN(Ge);function _c(n,e,t="on",r=js){return new Zt(s=>{let i=null;return i=n[t](e,(o,a)=>{r.schedule(()=>{s.next({snapshot:o,prevKey:a})}),t==="once"&&r.schedule(()=>s.complete())},o=>{r.schedule(()=>s.error(o))}),t==="on"?{unsubscribe(){i!=null&&n.off(e,i)}}:{unsubscribe(){}}}).pipe(_e(s=>{let{snapshot:i,prevKey:o}=s,a=null;return i.exists()&&(a=i.key),{type:e,payload:i,prevKey:o,key:a}}),wv())}function uN(n){return typeof n=="string"}function hN(n){return typeof n.exportVal=="function"}function PC(n){return n==null}function xC(n){return typeof n.set=="function"}function bC(n,e){return xC(e)?e:n.ref(e)}function kC(n,e){if(uN(n))return e.stringCase();if(xC(n))return e.firebaseCase();if(hN(n))return e.snapshotCase();throw new Error(`Expects a string, snapshot, or reference. Got: ${typeof n}`)}function NC(n){return(PC(n)||n.length===0)&&(n=["child_added","child_removed","child_changed","child_moved"]),n}function DC(n,e,t){e=NC(e);let r=e.map(s=>_c(n,s,"on",t));return wo(...r)}function dN(n,e,t){let r=DC(n,e).pipe(Wr((s,i)=>[...s,i],[]));return pN(n,r,t)}function fN(n,e){return _c(n,"value","on",e).pipe(_e(t=>{let r;return t.payload.forEach(s=>(r=s.key,!1)),{data:t,lastKeyToLoad:r}}))}function pN(n,e,t){return fN(n,t).pipe(Tv(e),_e(([s,i])=>{let o=s.lastKeyToLoad,a=i.map(l=>l.key);return{actions:i,lastKeyToLoad:o,loadedKeys:a}}),Ev(s=>!s.loadedKeys.includes(s.lastKeyToLoad)),_e(s=>s.actions))}function CC(n,e){return function(r,s){return kC(r,{stringCase:()=>n.child(r)[e](s),firebaseCase:()=>r[e](s),snapshotCase:()=>r.ref[e](s)})}}function mN(n){return function(t){return t?kC(t,{stringCase:()=>n.child(t).remove(),firebaseCase:()=>t.remove(),snapshotCase:()=>t.ref.remove()}):n.remove()}}function gN(n,e,t){return _c(n,"value","once",t).pipe(In(r=>{let s=[tn(r)];return e.forEach(i=>s.push(_c(n,i,"on",t))),wo(...s).pipe(Wr(yN,[]))}),Fc())}function VC(n,e){let t=n.length;for(let r=0;r{let u={payload:l,type:"value",prevKey:a,key:l.key};return a=l.key,n=[...n,u],!1})}return n;case"child_added":if(i>-1)(n[i-1]?.key||null)!==r&&(n=n.filter(l=>l.payload.key!==t.key),n.splice(o,0,e));else{if(r==null)return[e,...n];n=n.slice(),n.splice(o,0,e)}return n;case"child_removed":return n.filter(a=>a.payload.key!==t.key);case"child_changed":return n.map(a=>a.payload.key===s?e:a);case"child_moved":if(i>-1){let a=n.splice(i,1)[0];return n=n.slice(),n.splice(o,0,a),n}return n;default:return n}}function SC(n,e,t){return e=NC(e),gN(n,e,t)}function vN(n,e,t){let r=e.schedulers.outsideAngular,s=se(Ve).run(()=>n.ref);return{query:n,update:CC(s,"update"),set:CC(s,"set"),push:i=>s.push(i),remove:mN(s),snapshotChanges(i){return SC(n,i,r).pipe(Pe(t))},stateChanges(i){return DC(n,i,r).pipe(Pe(t))},auditTrail(i){return dN(n,i,r).pipe(Pe(t))},valueChanges(i,o){return SC(n,i,r).pipe(_e(l=>l.map(u=>o?.idField?tt(Q({},u.payload.val()),{[o.idField]:u.key}):u.payload.val())),Pe(t))}}}function RC(n,e){return function(){return _c(n,"value","on",e)}}function wN(n,e,t){return{query:n,snapshotChanges(){return RC(n,e.schedulers.outsideAngular)().pipe(Pe(t))},update(r){return n.ref.update(r)},set(r){return n.ref.set(r)},remove(){return n.ref.remove()},valueChanges(){return RC(n,e.schedulers.outsideAngular)().pipe(Pe(t),_e(s=>s.payload.exists()?s.payload.val():null))}}}var EN=new De("angularfire2.realtimeDatabaseURL"),TN=new De("angularfire2.database.use-emulator"),IN=(()=>{class n{schedulers;database;injector=se(An);constructor(t,r,s,i,o,a,l,u,d,p,m,v,S,x,k){this.schedulers=a;let q=l,G=Xr(t,o,r);u&&Uo(G,o,d,m,v,S,p,x),this.database=$s(`${G.name}.database.${s}`,"AngularFireDatabase",G.name,()=>{let L=o.runOutsideAngular(()=>G.database(s||void 0));return q&&L.useEmulator(...q),L},[q])}list(t,r){let s=se(Ve).runOutsideAngular(()=>bC(this.database,t)),i=s;return r&&(i=r(s)),vN(i,this,this.injector)}object(t){let r=se(Ve).runOutsideAngular(()=>bC(this.database,t));return wN(r,this,this.injector)}createPushId(){return se(Ve).runOutsideAngular(()=>this.database.ref()).push().key}static \u0275fac=function(r){return new(r||n)(K(er),K(tr,8),K(EN,8),K(Yn),K(Ve),K(Jr),K(TN,8),K(Bo,8),K(Do,8),K(Vo,8),K(Oo,8),K(Mo,8),K(Fo,8),K(Lo,8),K(rr,8))};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"any"})}return n})(),ZV=(()=>{class n{constructor(){Ge.registerVersion("angularfire",on.full,"rtdb-compat")}static \u0275fac=function(r){return new(r||n)};static \u0275mod=rn({type:n});static \u0275inj=nn({providers:[IN]})}return n})();var OC=["toast-component",""];function AN(n,e){if(n&1){let t=Id();Ut(0,"button",2),bd("click",function(){pd(t);let s=at();return md(s.remove())}),Ut(1,"span",3),Cn(2,"\xD7"),bn()()}}function bN(n,e){if(n&1&&(Ed(0),Cn(1),Td()),n&2){let t=at(2);qe(),$r("[",t.duplicatesCount+1,"]")}}function CN(n,e){if(n&1&&(Ut(0,"div"),Cn(1),Tt(2,bN,2,1,"ng-container"),bn()),n&2){let t=at(),r=Sn(0);Jn(r.titleClass),Io("aria-label",t.title()),qe(),$r(" ",t.title()," "),qe(),It(t.duplicatesCount?2:-1)}}function SN(n,e){if(n&1&&Ao(0,"div",6),n&2){let t=at(2),r=Sn(0);Jn(r.messageClass),Ad("innerHTML",t.message(),yd)}}function RN(n,e){if(n&1&&(Ut(0,"div",7),Cn(1),bn()),n&2){let t=at(2),r=Sn(0);Jn(r.messageClass),Io("aria-label",t.message()),qe(),$r(" ",t.message()," ")}}function PN(n,e){if(n&1&&Tt(0,SN,1,3,"div",4)(1,RN,2,4,"div",5),n&2){at();let t=Sn(0);It(t.enableHtml?0:1)}}function xN(n,e){if(n&1&&(Ut(0,"div"),Ao(1,"div",8),bn()),n&2){let t=at();qe(),bo("width",t.width()+"%")}}function kN(n,e){if(n&1){let t=Id();Ut(0,"button",2),bd("click",function(){pd(t);let s=at();return md(s.remove())}),Ut(1,"span",3),Cn(2,"\xD7"),bn()()}}function NN(n,e){if(n&1&&(Ed(0),Cn(1),Td()),n&2){let t=at(2);qe(),$r("[",t.duplicatesCount+1,"]")}}function DN(n,e){if(n&1&&(Ut(0,"div"),Cn(1),Tt(2,NN,2,1,"ng-container"),bn()),n&2){let t=at(),r=Sn(0);Jn(r.titleClass),Io("aria-label",t.title()),qe(),$r(" ",t.title()," "),qe(),It(t.duplicatesCount?2:-1)}}function VN(n,e){if(n&1&&Ao(0,"div",6),n&2){let t=at(2),r=Sn(0);Jn(r.messageClass),Ad("innerHTML",t.message(),yd)}}function ON(n,e){if(n&1&&(Ut(0,"div",7),Cn(1),bn()),n&2){let t=at(2),r=Sn(0);Jn(r.messageClass),Io("aria-label",t.message()),qe(),$r(" ",t.message()," ")}}function MN(n,e){if(n&1&&Tt(0,VN,1,3,"div",4)(1,ON,2,4,"div",5),n&2){at();let t=Sn(0);It(t.enableHtml?0:1)}}function FN(n,e){if(n&1&&(Ut(0,"div"),Ao(1,"div",8),bn()),n&2){let t=at();qe(),bo("width",t.width()+"%")}}var yc=class{toastId;config;message;title;toastType;toastRef;_onTap=new en;_onAction=new en;constructor(e,t,r,s,i,o){this.toastId=e,this.config=t,this.message=r,this.title=s,this.toastType=i,this.toastRef=o,this.toastRef.afterClosed().subscribe(()=>{this._onAction.complete(),this._onTap.complete()})}triggerTap(){this._onTap.next(),this.config.tapToDismiss&&this._onTap.complete()}onTap(){return this._onTap.asObservable()}triggerAction(e){this._onAction.next(e)}onAction(){return this._onAction.asObservable()}},MC={maxOpened:0,autoDismiss:!1,newestOnTop:!0,preventDuplicates:!1,countDuplicates:!1,resetTimeoutOnDuplicate:!1,includeTitleDuplicates:!1,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},closeButton:!1,disableTimeOut:!1,timeOut:5e3,extendedTimeOut:1e3,enableHtml:!1,progressBar:!1,toastClass:"ngx-toastr",positionClass:"toast-top-right",titleClass:"toast-title",messageClass:"toast-message",easing:"ease-in",easeTime:300,tapToDismiss:!0,onActivateTick:!1,progressAnimation:"decreasing"},FC=new De("ToastConfig"),uy=class{_attachedHost;component;viewContainerRef;injector;constructor(e,t){this.component=e,this.injector=t}attach(e,t){return this._attachedHost=e,e.attach(this,t)}detach(){let e=this._attachedHost;if(e)return this._attachedHost=void 0,e.detach()}get isAttached(){return this._attachedHost!=null}setAttachedHost(e){this._attachedHost=e}},hy=class{_attachedPortal;_disposeFn;attach(e,t){return this._attachedPortal=e,this.attachComponentPortal(e,t)}detach(){this._attachedPortal&&this._attachedPortal.setAttachedHost(),this._attachedPortal=void 0,this._disposeFn&&(this._disposeFn(),this._disposeFn=void 0)}setDisposeFn(e){this._disposeFn=e}},dy=class extends hy{_hostDomElement;_appRef;constructor(e,t){super(),this._hostDomElement=e,this._appRef=t}attachComponentPortal(e,t){let r=Vv(e.component,{environmentInjector:this._appRef.injector,elementInjector:e.injector});return this._appRef.attachView(r.hostView),this.setDisposeFn(()=>{this._appRef.detachView(r.hostView),r.destroy()}),t?this._hostDomElement.insertBefore(this._getComponentRootNode(r),this._hostDomElement.firstChild):this._hostDomElement.appendChild(this._getComponentRootNode(r)),r}_getComponentRootNode(e){return e.hostView.rootNodes[0]}},LN=(()=>{class n{_document=se(gd);_containerElement;ngOnDestroy(){this._containerElement&&this._containerElement.parentNode&&this._containerElement.parentNode.removeChild(this._containerElement)}getContainerElement(){return this._containerElement||this._createContainer(),this._containerElement}_createContainer(){let t=this._document.createElement("div");t.classList.add("overlay-container"),t.setAttribute("aria-live","polite"),this._document.body.appendChild(t),this._containerElement=t}static \u0275fac=function(r){return new(r||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})(),fy=class{_portalHost;constructor(e){this._portalHost=e}attach(e,t=!0){return this._portalHost.attach(e,t)}detach(){return this._portalHost.detach()}},UN=(()=>{class n{_overlayContainer=se(LN);_appRef=se(wd);_document=se(gd);_paneElements=new Map;create(t,r){return this._createOverlayRef(this.getPaneElement(t,r))}getPaneElement(t="",r){return this._paneElements.get(r)||this._paneElements.set(r,{}),this._paneElements.get(r)[t]||(this._paneElements.get(r)[t]=this._createPaneElement(t,r)),this._paneElements.get(r)[t]}_createPaneElement(t,r){let s=this._document.createElement("div");return s.id="toast-container",s.classList.add(t),s.classList.add("toast-container"),r?r.getContainerElement().appendChild(s):this._overlayContainer.getContainerElement().appendChild(s),s}_createPortalHost(t){return new dy(t,this._appRef)}_createOverlayRef(t){return new fy(this._createPortalHost(t))}static \u0275fac=function(r){return new(r||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})(),py=class{_overlayRef;componentInstance;duplicatesCount=0;_afterClosed=new en;_activate=new en;_manualClose=new en;_resetTimeout=new en;_countDuplicate=new en;constructor(e){this._overlayRef=e}manualClose(){this._manualClose.next(),this._manualClose.complete()}manualClosed(){return this._manualClose.asObservable()}timeoutReset(){return this._resetTimeout.asObservable()}countDuplicate(){return this._countDuplicate.asObservable()}close(){this._overlayRef.detach(),this._afterClosed.next(),this._manualClose.next(),this._afterClosed.complete(),this._manualClose.complete(),this._activate.complete(),this._resetTimeout.complete(),this._countDuplicate.complete()}afterClosed(){return this._afterClosed.asObservable()}isInactive(){return this._activate.closed}activate(){this._activate.next(),this._activate.complete()}afterActivate(){return this._activate.asObservable()}onDuplicate(e,t){e&&this._resetTimeout.next(),t&&this._countDuplicate.next(++this.duplicatesCount)}},BN=(()=>{class n{overlay=se(UN);_injector=se(To);sanitizer=se(Fv);ngZone=se(Ve);toastrConfig;currentlyActive=0;toasts=[];overlayContainer;previousToastMessage;index=0;constructor(){let t=se(FC);this.toastrConfig=Q(Q({},t.default),t.config),t.config.iconClasses&&(this.toastrConfig.iconClasses=Q(Q({},t.default.iconClasses),t.config.iconClasses))}show(t,r,s={},i=""){return this._preBuildNotification(i,t,r,this.applyConfig(s))}success(t,r,s={}){let i=this.toastrConfig.iconClasses.success||"";return this._preBuildNotification(i,t,r,this.applyConfig(s))}error(t,r,s={}){let i=this.toastrConfig.iconClasses.error||"";return this._preBuildNotification(i,t,r,this.applyConfig(s))}info(t,r,s={}){let i=this.toastrConfig.iconClasses.info||"";return this._preBuildNotification(i,t,r,this.applyConfig(s))}warning(t,r,s={}){let i=this.toastrConfig.iconClasses.warning||"";return this._preBuildNotification(i,t,r,this.applyConfig(s))}clear(t){for(let r of this.toasts)if(t!==void 0){if(r.toastId===t){r.toastRef.manualClose();return}}else r.toastRef.manualClose()}remove(t){let r=this._findToast(t);if(!r||(r.activeToast.toastRef.close(),this.toasts.splice(r.index,1),this.currentlyActive=this.currentlyActive-1,!this.toastrConfig.maxOpened||!this.toasts.length))return!1;if(this.currentlyActivethis._buildNotification(t,r,s,i)):this._buildNotification(t,r,s,i)}_buildNotification(t,r,s,i){if(!i.toastComponent)throw new Error("toastComponent required");let o=this.findDuplicate(s,r,this.toastrConfig.resetTimeoutOnDuplicate&&i.timeOut>0,this.toastrConfig.countDuplicates);if((this.toastrConfig.includeTitleDuplicates&&s||r)&&this.toastrConfig.preventDuplicates&&o!==null)return o;this.previousToastMessage=r;let a=!1;this.toastrConfig.maxOpened&&this.currentlyActive>=this.toastrConfig.maxOpened&&(a=!0,this.toastrConfig.autoDismiss&&this.clear(this.toasts[0].toastId));let l=this.overlay.create(i.positionClass,this.overlayContainer);this.index=this.index+1;let u=r;r&&i.enableHtml&&(u=this.sanitizer.sanitize(Pv.HTML,r));let d=new py(l),p=new yc(this.index,i,u,s,t,d),m=[{provide:yc,useValue:p}],v=To.create({providers:m,parent:this._injector}),S=new uy(i.toastComponent,v),x=l.attach(S,i.newestOnTop);d.componentInstance=x.instance;let k={toastId:this.index,title:s||"",message:r||"",toastRef:d,onShown:d.afterActivate(),onHidden:d.afterClosed(),onTap:p.onTap(),onAction:p.onAction(),portal:x};return a||(this.currentlyActive=this.currentlyActive+1,setTimeout(()=>{k.toastRef.activate()})),this.toasts.push(k),k}static \u0275fac=function(r){return new(r||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})(),qN=(()=>{class n{ngZone=se(Ve);setInterval(t,r){return this.ngZone?this.ngZone.runOutsideAngular(()=>window.setInterval(()=>this.runInsideAngular(t),r)):window.setInterval(()=>t(),r)}setTimeout(t,r){return this.ngZone?this.ngZone.runOutsideAngular(()=>window.setTimeout(()=>this.runInsideAngular(t),r)):window.setTimeout(()=>t(),r)}runInsideAngular(t){this.ngZone?this.ngZone.run(()=>t()):t()}static \u0275fac=function(r){return new(r||n)};static \u0275prov=Xe({token:n,factory:n.\u0275fac,providedIn:"root"})}return n})(),LC=(()=>{class n{toastPackage=se(yc);toastrService=se(BN);appRef=se(wd);timeoutsService=se(qN);duplicatesCount;hideTime;width=Gs(-1);state=Gs("inactive");displayStyle=zs(()=>this.state()==="inactive"?"none":void 0);message=zs(()=>this.toastPackage.message);title=zs(()=>this.toastPackage.title);options=Dv(()=>this.toastPackage.config);originalTimeout=zs(()=>this.toastPackage.config.timeOut);toastClasses=zs(()=>`${this.toastPackage.toastType} ${this.toastPackage.config.toastClass}`);timeout;intervalId;afterActivateSubscription;manualClosedSubscription;timeoutResetSubscription;countDuplicateSubscription;constructor(){this.afterActivateSubscription=this.toastPackage.toastRef.afterActivate().subscribe(()=>{this.activateToast()}),this.manualClosedSubscription=this.toastPackage.toastRef.manualClosed().subscribe(()=>{this.remove()}),this.timeoutResetSubscription=this.toastPackage.toastRef.timeoutReset().subscribe(()=>{this.resetTimeout()}),this.countDuplicateSubscription=this.toastPackage.toastRef.countDuplicate().subscribe(t=>{this.duplicatesCount=t})}ngOnDestroy(){this.afterActivateSubscription.unsubscribe(),this.manualClosedSubscription.unsubscribe(),this.timeoutResetSubscription.unsubscribe(),this.countDuplicateSubscription.unsubscribe(),clearInterval(this.intervalId),clearTimeout(this.timeout)}activateToast(){let t=this.options();this.state.set("active"),!(t.disableTimeOut===!0||t.disableTimeOut==="timeOut")&&t.timeOut&&(this.timeout=this.timeoutsService.setTimeout(()=>this.remove(),t.timeOut),this.hideTime=new Date().getTime()+t.timeOut,t.progressBar&&(this.intervalId=this.timeoutsService.setInterval(()=>this.updateProgress(),10)))}updateProgress(){let t=this.options();if(this.width()===0||this.width()===100||!t.timeOut)return;let r=new Date().getTime(),s=this.hideTime-r;this.width.set(s/t.timeOut*100),t.progressAnimation==="increasing"&&this.width.update(i=>100-i),this.width()<=0&&this.width.set(0),this.width()>=100&&this.width.set(100)}resetTimeout(){let t=this.options();clearTimeout(this.timeout),clearInterval(this.intervalId),this.state.set("active"),this.options.update(r=>tt(Q({},r),{timeOut:this.originalTimeout()})),this.timeout=this.timeoutsService.setTimeout(()=>this.remove(),this.originalTimeout()),this.hideTime=new Date().getTime()+(this.originalTimeout()||0),this.width.set(-1),t.progressBar&&(this.intervalId=this.timeoutsService.setInterval(()=>this.updateProgress(),10))}remove(){this.state()!=="removed"&&(clearTimeout(this.timeout),this.state.set("removed"),this.timeout=this.timeoutsService.setTimeout(()=>this.toastrService.remove(this.toastPackage.toastId)))}tapToast(){this.state()!=="removed"&&(this.toastPackage.triggerTap(),this.options().tapToDismiss&&this.remove())}stickAround(){this.state()!=="removed"&&this.options().disableTimeOut!=="extendedTimeOut"&&(clearTimeout(this.timeout),this.options.update(t=>tt(Q({},t),{timeOut:0})),this.hideTime=0,clearInterval(this.intervalId),this.width.set(0))}delayedHideToast(){let t=this.options();if(t.disableTimeOut===!0||t.disableTimeOut==="extendedTimeOut"||t.extendedTimeOut===0||this.state()==="removed")return;let r=t.extendedTimeOut;this.timeout=this.timeoutsService.setTimeout(()=>this.remove(),r),this.options.update(s=>tt(Q({},s),{timeOut:r})),this.hideTime=new Date().getTime()+(r||0),this.width.set(-1),t.progressBar&&(this.intervalId=this.timeoutsService.setInterval(()=>this.updateProgress(),10))}static \u0275fac=function(r){return new(r||n)};static \u0275cmp=vd({type:n,selectors:[["","toast-component",""]],hostVars:4,hostBindings:function(r,s){r&1&&Nv("mouseenter",function(){return s.stickAround()})("mouseleave",function(){return s.delayedHideToast()})("click",function(){return s.tapToast()}),r&2&&(Jn(s.toastClasses()),bo("display",s.displayStyle()))},attrs:OC,decls:5,vars:5,consts:[["type","button","aria-label","Close",1,"toast-close-button"],[3,"class"],["type","button","aria-label","Close",1,"toast-close-button",3,"click"],["aria-hidden","true"],["role","alert",3,"class","innerHTML"],["role","alert",3,"class"],["role","alert",3,"innerHTML"],["role","alert"],[1,"toast-progress"]],template:function(r,s){if(r&1&&(Cd(0),Tt(1,AN,3,0,"button",0),Tt(2,CN,3,5,"div",1),Tt(3,PN,2,1),Tt(4,xN,2,2,"div")),r&2){let i=Sd(s.options());qe(),It(i.closeButton?1:-1),qe(),It(s.title()?2:-1),qe(),It(s.message()?3:-1),qe(),It(i.progressBar?4:-1)}},encapsulation:2,changeDetection:0})}return n})(),jN=(()=>{class n extends LC{params={easeTime:this.toastPackage.config.easeTime,easing:"ease-in"};elementRef=se(Rv);remove(){this.state()!=="removed"&&(clearTimeout(this.timeout),this.state.set("removed"),this.elementRef.nativeElement.classList.add("toast-out"),this.timeout=this.timeoutsService.setTimeout(()=>this.toastrService.remove(this.toastPackage.toastId),+this.params.easeTime))}static \u0275fac=(()=>{let t;return function(s){return(t||(t=Sv(n)))(s||n)}})();static \u0275cmp=vd({type:n,selectors:[["","toast-component",""]],hostVars:4,hostBindings:function(r,s){r&1&&kv("toast-in"),r&2&&bo("--animation-easing",s.params.easing)("--animation-duration",s.params.easeTime+"ms")},features:[xv],attrs:OC,decls:5,vars:5,consts:[["type","button","aria-label","Close",1,"toast-close-button"],[3,"class"],["type","button","aria-label","Close",1,"toast-close-button",3,"click"],["aria-hidden","true"],["role","alert",3,"class","innerHTML"],["role","alert",3,"class"],["role","alert",3,"innerHTML"],["role","alert"],[1,"toast-progress"]],template:function(r,s){if(r&1&&(Cd(0),Tt(1,kN,3,0,"button",0),Tt(2,DN,3,5,"div",1),Tt(3,MN,2,1),Tt(4,FN,2,2,"div")),r&2){let i=Sd(s.options());qe(),It(i.closeButton?1:-1),qe(),It(s.title()?2:-1),qe(),It(s.message()?3:-1),qe(),It(i.progressBar?4:-1)}},styles:[".toast-in[_nghost-%COMP%]{animation:_ngcontent-%COMP%_toast-animation var(--animation-duration) var(--animation-easing)}.toast-out[_nghost-%COMP%]{animation:_ngcontent-%COMP%_toast-animation var(--animation-duration) var(--animation-easing) reverse forwards}@keyframes _ngcontent-%COMP%_toast-animation{0%{opacity:0}to{opacity:1}}"],changeDetection:0})}return n})(),GN=tt(Q({},MC),{toastComponent:jN}),zN=(n={})=>bv([{provide:FC,useValue:{default:GN,config:n}}]),dO=(()=>{class n{static forRoot(t={}){return{ngModule:n,providers:[zN(t)]}}static \u0275fac=function(r){return new(r||n)};static \u0275mod=rn({type:n});static \u0275inj=nn({})}return n})();var fO=tt(Q({},MC),{toastComponent:LC});export{Qv as a,xo as b,Yv as c,xD as d,m1 as e,IV as f,ZV as g,BN as h,dO as i};